Compare commits

...
Author SHA1 Message Date
huiyadanli d61f804442 Update version to 0.61.2 2026-06-01 13:30:00 +00:00
辉鸭蛋 4747c39ae1 修复 发送webhook请求时,screenshot字段值为空的问题 #2506 2026-05-30 02:13:28 +08:00
huiyadanli 7a6854e7d5 Update version to 0.61.1-alpha.2 2026-05-28 19:19:12 +00:00
辉鸭蛋 6f7c78b474 性能优化(日志模块): 调整日志清理阈值并优化日志输出条件 #3161
将日志文本框的自动清理行数从1000调整为200,减少日志堆积的内存占用。
修改日志输出触发条件,仅当遮罩窗口启用且显示日志框时才写入日志,避免不必要的性能开销。
2026-05-29 03:17:25 +08:00
ShadowLemoon 43701b90f0 refactor: 增强状态机节点注册与重试兜底 (#3159) 2026-05-28 02:08:02 +08:00
huiyadanli 6090cce849 Update version to 0.61.1-alpha.1 2026-05-27 08:55:59 +00:00
cookie981 96cf2d5261 fix:新增一键宏按住时重复(旧)模式 (#3154) 2026-05-27 15:48:14 +08:00
ShadowLemoon 8813235ebf feat: 通过Silero Vad识别对话结束并延后选项选择 (#3130) 2026-05-26 23:48:03 +08:00
cookie981 bbd9634c07 Fix:优化一键宏 (#3150) 2026-05-25 22:56:13 +08:00
ShadowLemoon d7b6ab9365 chore: 调整周日奖励字段名称 (#3149) 2026-05-25 22:53:11 +08:00
ShadowLemoon 13f3951d7f feat: 优化一条龙每周秘境配置与下拉选择显示 (#3142) 2026-05-25 02:58:12 +08:00
huiyadanli c8fba493c1 Update version to 0.61.0 2026-05-23 19:49:45 +00:00
躁动的氨气andClaude Opus 4.7 96f523d4b8 fix: 修复复制配置组问题与加载器依赖解析问题 (#3139)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-05-24 03:47:02 +08:00
huiyadanli f8e231c235 Update version to 0.60.3-alpha.2 2026-05-21 17:47:22 +00:00
辉鸭蛋 58bceffe0e 6.6角色 2026-05-22 01:18:40 +08:00
郝凯阳andhaokaiyang 4c6232fdb3 auto tcg: update character card config to v6.6 (#3132)
Co-authored-by: haokaiyang <[email protected]>
2026-05-21 14:31:16 +08:00
Jamis 1eb483b639 Update tp.json with new version and domains (#3128) 2026-05-20 23:29:32 +08:00
huiyadanli 796bda0af3 Update version to 0.60.3-alpha.1 2026-05-20 03:17:16 +00:00
辉鸭蛋 6d8bbc18fc Update BetterGI.Assets.Model package version 2026-05-20 11:13:39 +08:00
cookie981 753c595625 fix:一键宏停止时立即松开所有按键 (#3126) 2026-05-17 23:10:24 +08:00
DarkFlameMaster 88bd60ab93 feat(BvLocator): 使重试回调支持异步方法,添加设置超时和重试间隔的方法 (#3117)
* feat(BvLocator): 使重试回调支持异步方法

* feat(BvLocator): 支持自定义超时和重试间隔

新增WithTimeout和WithRetryInterval链式调用方法

* 可能是bug?

* fix
2026-05-12 22:03:35 +08:00
DarkFlameMaster 36669b89ef feat: 增加 HTML 遮罩窗口点击穿透模式切换功能 (#3100)
* 增加html遮罩点击穿透模式的切换

* fix:修两个小问题

* 切换穿透状态时自动切换焦点

* feat:停止脚本自动关闭html遮罩,并修复衍生问题
2026-05-12 01:43:34 +08:00
ema 70b3f6dd99 修复出错啦窗口显示版本号错误问题 (#3116) 2026-05-12 01:43:03 +08:00
37 changed files with 3245 additions and 568 deletions

No files matched your search

+1 -1
View File
@@ -78,7 +78,7 @@ public partial class App : Application
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
if (all.MaskWindowConfig.MaskEnabled)
if (all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true })
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.60.2-alpha.4</Version>
<Version>0.61.2</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -44,7 +44,7 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.22" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.24" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.15" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
@@ -85,17 +85,18 @@
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<!-- <PackageReference Include="supabase-csharp" Version="0.16.2" />-->
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
<PackageReference Include="XamlAnimatedGif" Version="2.3.1" />
<PackageReference Include="WPF-UI" Version="4.2.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.2.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.2.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.2.0.10" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.3.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.0" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
+80 -15
View File
@@ -21,10 +21,12 @@ public class BvLocator
{
private static readonly ILogger Logger = App.GetLogger<BvLocator>();
private readonly CancellationToken _cancellationToken;
private int? _timeout;
private int? _retryInterval;
public RecognitionObject RecognitionObject { get; }
public Action<List<Region>>? RetryAction { get; set; }
public Func<List<Region>, Task>? RetryAction { get; set; }
public static int DefaultTimeout { get; set; } = 10000;
@@ -98,17 +100,21 @@ public class BvLocator
public async Task<List<Region>> WaitFor(int? timeout = null)
{
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
List<Region> results = [];
var retryRes = await NewRetry.WaitForAction(() =>
var retryRes = await NewRetry.WaitForAction(async () =>
{
results = FindAll();
var b = results.Count > 0;
RetryAction?.Invoke(results);
if (!b && RetryAction != null)
{
await RetryAction(results);
}
return b;
}, _cancellationToken, retryCount, DefaultRetryInterval);
}, _cancellationToken, retryCount, actualRetryInterval);
if (retryRes)
{
@@ -150,20 +156,21 @@ public class BvLocator
public async Task WaitForDisappear(int? timeout = null)
{
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var retryRes = await NewRetry.WaitForAction(() =>
var retryRes = await NewRetry.WaitForAction(async () =>
{
var results = FindAll();
var b = results.Count == 0;
if (!b)
if (!b && RetryAction != null)
{
RetryAction?.Invoke(results);
await RetryAction(results);
}
return b;
}, _cancellationToken, retryCount, DefaultRetryInterval);
}, _cancellationToken, retryCount, actualRetryInterval);
if (!retryRes)
{
@@ -205,19 +212,77 @@ public class BvLocator
public BvLocator WithRetryAction(Action<List<Region>>? action)
{
RetryAction = action;
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = (results) =>
{
action(results);
return Task.CompletedTask;
};
}
return this;
}
/// <summary>
/// 设置超时时间(毫秒)
/// </summary>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns></returns>
public BvLocator WithTimeout(int timeout)
{
if (timeout <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout), "timeout 必须大于 0");
}
_timeout = timeout;
return this;
}
/// <summary>
/// 设置重试间隔(毫秒)
/// </summary>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns></returns>
public BvLocator WithRetryInterval(int retryInterval)
{
if (retryInterval <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retryInterval), "retryInterval 必须大于 0");
}
_retryInterval = retryInterval;
return this;
}
/// <summary>
/// 为 JavaScript 提供的动态参数重载
/// 解决 ClearScript 无法将 JS 函数隐式转换为 Action 委托的问题
/// 支持同步和异步 JS 函数
/// </summary>
/// <param name="action">JS 回调函数</param>
/// <returns></returns>
public BvLocator WithRetryAction(dynamic action)
{
RetryAction = (results) => action(results);
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = async (results) =>
{
var taskResult = action(results);
// 如果 JS 返回的是 Promise/Task,等待其完成
if (taskResult is Task task)
{
await task;
}
};
}
return this;
}
}
}
@@ -46,13 +46,13 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private int _minResinToKeep = 0;
// 领取每日奖励的好感数量
// 普通周日或限时奖励选项
[ObservableProperty]
private string _sundayEverySelectedValue = "0";
// 领取每日奖励的好感数量
// 每周秘境的全局限时奖励选项,单日留空时使用
[ObservableProperty]
private string _sundaySelectedValue = "0";
private string _sundayWeeklySelectedValue = "0";
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
[ObservableProperty]
@@ -151,6 +151,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _mondayDomainName = string.Empty;
[ObservableProperty]
private string _mondaySelectedValue = "0";
//周二
@@ -159,6 +162,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _tuesdayDomainName = string.Empty;
[ObservableProperty]
private string _tuesdaySelectedValue = "0";
//周三
[ObservableProperty]
@@ -166,6 +172,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _wednesdayDomainName = string.Empty;
[ObservableProperty]
private string _wednesdaySelectedValue = "0";
//周四
[ObservableProperty]
@@ -173,6 +182,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _thursdayDomainName = string.Empty;
[ObservableProperty]
private string _thursdaySelectedValue = "0";
//周五
[ObservableProperty]
@@ -180,6 +192,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _fridayDomainName = string.Empty;
[ObservableProperty]
private string _fridaySelectedValue = "0";
//周六
[ObservableProperty]
@@ -187,6 +202,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _saturdayDomainName = string.Empty;
[ObservableProperty]
private string _saturdaySelectedValue = "0";
//周日
[ObservableProperty]
@@ -195,6 +213,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _sundayDomainName = string.Empty;
[ObservableProperty]
private string _sundaySelectedValue = "0";
// 完成后操作
[ObservableProperty]
private string _completionAction = string.Empty;
@@ -208,22 +229,37 @@ public partial class OneDragonFlowConfig : ObservableObject
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => (MondayPartyName, MondayDomainName,SundaySelectedValue),
DayOfWeek.Tuesday => (TuesdayPartyName, TuesdayDomainName,SundaySelectedValue),
DayOfWeek.Wednesday => (WednesdayPartyName, WednesdayDomainName,SundaySelectedValue),
DayOfWeek.Thursday => (ThursdayPartyName, ThursdayDomainName,SundaySelectedValue),
DayOfWeek.Friday => (FridayPartyName, FridayDomainName,SundaySelectedValue),
DayOfWeek.Saturday => (SaturdayPartyName, SaturdayDomainName,SundaySelectedValue),
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName,SundaySelectedValue),
_ => (PartyName, DomainName,SundaySelectedValue)
DayOfWeek.Monday => (GetWeeklyPartyName(MondayPartyName), GetWeeklyDomainName(MondayDomainName), GetWeeklySelectedValue(MondaySelectedValue)),
DayOfWeek.Tuesday => (GetWeeklyPartyName(TuesdayPartyName), GetWeeklyDomainName(TuesdayDomainName), GetWeeklySelectedValue(TuesdaySelectedValue)),
DayOfWeek.Wednesday => (GetWeeklyPartyName(WednesdayPartyName), GetWeeklyDomainName(WednesdayDomainName), GetWeeklySelectedValue(WednesdaySelectedValue)),
DayOfWeek.Thursday => (GetWeeklyPartyName(ThursdayPartyName), GetWeeklyDomainName(ThursdayDomainName), GetWeeklySelectedValue(ThursdaySelectedValue)),
DayOfWeek.Friday => (GetWeeklyPartyName(FridayPartyName), GetWeeklyDomainName(FridayDomainName), GetWeeklySelectedValue(FridaySelectedValue)),
DayOfWeek.Saturday => (GetWeeklyPartyName(SaturdayPartyName), GetWeeklyDomainName(SaturdayDomainName), GetWeeklySelectedValue(SaturdaySelectedValue)),
DayOfWeek.Sunday => (GetWeeklyPartyName(SundayPartyName), GetWeeklyDomainName(SundayDomainName), GetWeeklySelectedValue(SundaySelectedValue)),
_ => (PartyName, DomainName, SundayWeeklySelectedValue)
};
}
else
{
return (PartyName, DomainName,SundayEverySelectedValue);
return (PartyName, DomainName, SundayEverySelectedValue);
}
}
private string GetWeeklyPartyName(string partyName)
{
return string.IsNullOrWhiteSpace(partyName) ? PartyName : partyName;
}
private string GetWeeklyDomainName(string domainName)
{
return string.IsNullOrWhiteSpace(domainName) ? DomainName : domainName;
}
private string GetWeeklySelectedValue(string selectedValue)
{
return string.IsNullOrWhiteSpace(selectedValue) || selectedValue == "0" ? SundayWeeklySelectedValue : selectedValue;
}
public bool ShouldRunLeyLineToday()
{
if (!LeyLineRunMonday
@@ -61,6 +61,12 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel BgiQClassify =
Register("BgiQClassify", @"Assets\Model\Common\q_classify_sim.onnx");
/// <summary>
/// Silero 人声检测模型
/// </summary>
public static readonly BgiOnnxModel SileroVad =
Register("SileroVad", @"Assets\Model\Vad\silero_vad.onnx");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -145,6 +145,35 @@ public class HtmlMask : IDisposable
/// </summary>
public bool Exists(string id) => HtmlMaskWindow.Exists(id);
/// <summary>
/// 设置窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThrough(string windowId, bool enabled)
{
HtmlMaskWindow.SetClickThrough(windowId, enabled);
}
/// <summary>
/// 获取窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>true=点击穿透,false=可交互</returns>
public bool GetClickThrough(string windowId)
{
return HtmlMaskWindow.GetClickThrough(windowId);
}
/// <summary>
/// 切换窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public void ToggleClickThrough(string windowId)
{
HtmlMaskWindow.ToggleClickThrough(windowId);
}
#endregion
#region 消息通信
@@ -96,7 +96,7 @@ public class EngineExtend
// 导入 JavaScript 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.AllowCategoryMismatch;
if (searchPaths != null)
{
var normalizedPaths = new List<string>();
@@ -9,7 +9,7 @@ using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DocumentLoader
public class PackageDocumentLoader : DefaultDocumentLoader
{
private readonly string _scriptRootPath;
@@ -22,21 +22,42 @@ namespace BetterGenshinImpact.Core.Script
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
// ResolvePhysicalPath 可能因 sourceInfo 为空而失败,直接从脚本根目录兜底
if (targetPath == null || !File.Exists(targetPath))
{
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
var stripped = Regex.Replace(specifier, @"^(?:\.\.?/)+", "");
if (!Path.IsPathRooted(stripped))
{
var fullPath = Path.GetFullPath(Path.Combine(_scriptRootPath, stripped));
if (fullPath.StartsWith(_scriptRootPath, StringComparison.OrdinalIgnoreCase)
&& File.Exists(fullPath))
{
targetPath = fullPath;
}
}
}
if (targetPath == null || !File.Exists(targetPath))
{
throw new FileNotFoundException($"无法解析模块导入路径: '{specifier}'", specifier);
}
// 处理 JS 文件的重写
if (Path.GetExtension(targetPath).ToLower() == ".js")
{
var uri = new Uri(targetPath);
// 检查缓存
var cached = GetCachedDocument(uri);
if (cached != null) return cached;
string content = await File.ReadAllTextAsync(targetPath);
string processedCode = RewriteScriptCode(content, targetPath);
var documentInfo = new DocumentInfo(new Uri(targetPath)) { Category = ModuleCategory.Standard };
return new StringDocument(documentInfo, processedCode);
var documentInfo = new DocumentInfo(uri) { Category = ModuleCategory.Standard };
return CacheDocument(new StringDocument(documentInfo, processedCode), false);
}
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
throw new FileNotFoundException($"不支持的模块导入类型: '{specifier}' (仅支持 .js 文件)", specifier);
}
/// <summary>
@@ -54,11 +75,9 @@ namespace BetterGenshinImpact.Core.Script
{
string importPart = match.Groups[1].Value.Trim();
string quote = match.Groups[2].Value;
string rawPath = match.Groups[3].Value;
string path = rawPath.Replace("../../../packages", "packages");
string path = match.Groups[3].Value.Replace("../../../packages", "packages");
string? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
if (resourceFullPath != null && File.Exists(resourceFullPath))
{
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
@@ -88,7 +107,24 @@ namespace BetterGenshinImpact.Core.Script
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
return ResolvePathInternal(settings.SearchPath, sourceInfo?.Name, specifier);
string? referrer = null;
if (sourceInfo.HasValue)
{
var sourceUri = sourceInfo.Value.Uri;
if (sourceUri != null && sourceUri.IsAbsoluteUri && sourceUri.IsFile)
{
referrer = sourceUri.LocalPath;
}
else if (!string.IsNullOrEmpty(sourceInfo.Value.Name))
{
if (Uri.TryCreate(sourceInfo.Value.Name, UriKind.Absolute, out var nameUri) && nameUri.IsFile)
{
referrer = nameUri.LocalPath;
}
}
}
return ResolvePathInternal(settings.SearchPath, referrer, specifier);
}
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
@@ -98,6 +134,12 @@ namespace BetterGenshinImpact.Core.Script
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
var packagesMatch = Regex.Match(specifier, @"^(?:\.\.\/)+(packages/.*)$");
if (packagesMatch.Success)
{
return ProbeFile(Path.Combine(_scriptRootPath, packagesMatch.Groups[1].Value));
}
if (specifier.StartsWith("."))
{
if (!string.IsNullOrEmpty(referrer))
@@ -128,8 +170,9 @@ namespace BetterGenshinImpact.Core.Script
{
try
{
if (File.Exists(path)) return path;
if (File.Exists(path + ".js")) return path + ".js";
var normalized = Path.GetFullPath(path);
if (File.Exists(normalized)) return normalized;
if (File.Exists(normalized + ".js")) return normalized + ".js";
}
catch { }
return null;
@@ -2075,5 +2075,41 @@
"nameEn": "Linnea",
"skillCD": 18,
"weapon": "10"
},
{
"alias": [
"洛恩",
"Lohen"
],
"burstCD": 15,
"id": "10000129",
"name": "洛恩",
"nameEn": "Lohen",
"skillCD": 18,
"weapon": "10"
},
{
"alias": [
"尼可",
"Nicole"
],
"burstCD": 15,
"id": "10000131",
"name": "尼可",
"nameEn": "Nicole",
"skillCD": 16,
"weapon": "10"
},
{
"alias": [
"布伦妮",
"Prune"
],
"burstCD": 18,
"id": "10000132",
"name": "布伦妮",
"nameEn": "Prune",
"skillCD": 15,
"weapon": "10"
}
]
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.Model;
@@ -7,9 +8,11 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -19,7 +22,8 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
/// </summary>
public class OneKeyFightTask : Singleton<OneKeyFightTask>
{
public static readonly string HoldOnMode = "按住时重复";
public static readonly string HoldOnMode = "按住时重复(新)";
public static readonly string HoldFinishMode = "按住时重复(旧)";
public static readonly string TickMode = "触发";
private Dictionary<string, List<CombatCommand>>? _avatarMacros;
@@ -31,6 +35,11 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
private DateTime _lastUpdateTime = DateTime.MinValue;
private CombatScenes? _currentCombatScenes;
// 宏启动前快照当前按下的键,停止时只释放宏期间新增的按键
private HashSet<User32.VK> _preMacroKeys = [];
private bool _hasMacroSnapshot = false;
// 代际编号:每次启动新 Task 时递增,旧 Task 的 finally 判断自己过期了就不清理全局状态
private int _macroGen = 0;
public void KeyDown()
{
@@ -48,25 +57,53 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
Logger.LogInformation("加载一键宏配置完成");
}
if (IsHoldOnMode())
if (IsHoldOnMode() || IsHoldFinishMode())
{
if (_cts == null || _cts.Token.IsCancellationRequested)
{
SnapshotPressedKeys();
_macroGen++;
_cts = new CancellationTokenSource();
_fightTask = FightTask(_cts.Token);
if (!_fightTask.IsCompleted)
var gen = _macroGen;
_fightTask = FightTask(_cts.Token, gen);
if (_fightTask.IsCompleted)
{
RollbackSnapshot();
}
else
{
_fightTask.Start();
}
}
else if (IsHoldFinishMode())
{
// 覆盖重新运行:取消旧的 Task,启动新的
_preMacroKeys.Clear();
_hasMacroSnapshot = false;
_macroGen++;
_cts?.Cancel();
_cts?.Dispose();
SnapshotPressedKeys();
_cts = new CancellationTokenSource();
var gen = _macroGen;
_fightTask = FightTask(_cts.Token, gen);
_fightTask.Start();
}
}
else if (IsTickMode())
{
if (_cts == null || _cts.Token.IsCancellationRequested)
{
SnapshotPressedKeys();
_macroGen++;
_cts = new CancellationTokenSource();
_fightTask = FightTask(_cts.Token);
if (!_fightTask.IsCompleted)
var gen = _macroGen;
_fightTask = FightTask(_cts.Token, gen);
if (_fightTask.IsCompleted)
{
RollbackSnapshot();
}
else
{
_fightTask.Start();
}
@@ -74,6 +111,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
else
{
_cts.Cancel();
ReleaseMacroOnlyKeys();
}
}
}
@@ -81,15 +119,18 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
public void KeyUp()
{
_isKeyDown = false;
// 清理放在 IsEnabled 之前,确保停止时始终释放按键
if (IsHoldOnMode() && _hasMacroSnapshot)
{
_cts?.Cancel();
ReleaseMacroOnlyKeys();
}
// HoldFinish 模式:只标记松手,让 Task 执行完当前轮后在 finally 中自动清理
if (!IsEnabled())
{
return;
}
if (IsHoldOnMode())
{
_cts?.Cancel();
}
}
// public void Run()
@@ -126,7 +167,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
/// <summary>
/// 循环执行战斗宏
/// </summary>
private Task FightTask(CancellationToken ct)
private Task FightTask(CancellationToken ct, int gen = 0)
{
var imageRegion = CaptureToRectArea();
var combatScenes = new CombatScenes().InitializeTeam(imageRegion);
@@ -167,29 +208,48 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
{
return new Task(() =>
{
var round = 1;
while (!ct.IsCancellationRequested && IsEnabled())
try
{
Logger.LogInformation("→ {Name}执行宏 (第{Round}轮)", activeAvatar.Name, round);
if (IsHoldOnMode() && !_isKeyDown)
var round = 1;
while (!ct.IsCancellationRequested && IsEnabled())
{
break;
}
// 通用化战斗策略
foreach (var command in combatCommands)
{
if (command.ActivatingRound != null && command.ActivatingRound.Count > 0 && !command.ActivatingRound.Contains(round))
Logger.LogInformation("→ {Name}执行宏 (第{Round}轮)", activeAvatar.Name, round);
if (IsHoldOnMode() && !_isKeyDown)
{
// 跳过强制首轮指令
continue;
break;
}
command.Execute(activeAvatar);
}
round++;
}
Logger.LogInformation("→ {Name}停止宏", activeAvatar.Name);
// 通用化战斗策略
foreach (var command in combatCommands)
{
if (ct.IsCancellationRequested) break;
if (command.ActivatingRound != null && command.ActivatingRound.Count > 0 && !command.ActivatingRound.Contains(round))
{
continue;
}
command.Execute(activeAvatar);
}
round++;
// HoldFinish:执行完本轮再检查松手信号
if (IsHoldFinishMode() && !_isKeyDown)
{
break;
}
}
Logger.LogInformation("→ {Name}停止宏", activeAvatar.Name);
}
finally
{
// 确保任何退出路径都清理快照和 CTS,避免残留状态影响下次操作
// 代际检查:如果已被覆盖(gen != _macroGen),不动全局字段
if (gen == _macroGen)
{
ReleaseMacroOnlyKeys();
RollbackSnapshot();
}
}
});
}
else
@@ -251,8 +311,60 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == HoldOnMode;
}
public static bool IsHoldFinishMode()
{
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == HoldFinishMode;
}
public static bool IsTickMode()
{
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == TickMode;
}
// 记录宏启动前已按下的键,停止时只释放不在快照中的键
private void SnapshotPressedKeys()
{
_preMacroKeys = [];
foreach (User32.VK key in Enum.GetValues(typeof(User32.VK)))
{
if ((User32.GetAsyncKeyState((int)key) & 0x8000) != 0)
{
_preMacroKeys.Add(key);
}
}
_hasMacroSnapshot = true;
}
// 停止宏时释放键,但保留用户事先按着的(在快照中的键跳过释放)
private void ReleaseMacroOnlyKeys()
{
if (!_hasMacroSnapshot) return;
var hWnd = TaskContext.Instance().GameHandle;
// PostMessage 替代 SendInput,避免钩子上下文中 SendInput 触发递归死锁
var postMsg = Simulation.PostMessage(hWnd);
foreach (User32.VK key in Enum.GetValues(typeof(User32.VK)))
{
if ((User32.GetAsyncKeyState((int)key) & 0x8000) != 0 && !_preMacroKeys.Contains(key))
{
postMsg.KeyUp(key);
}
}
// 鼠标键不做快照检查,统一释放
postMsg.LeftButtonUp();
postMsg.RightButtonUp();
User32.PostMessage(hWnd, 0x208, IntPtr.Zero, IntPtr.Zero); // WM_MBUTTONUP
_preMacroKeys.Clear();
_hasMacroSnapshot = false;
}
// FightTask 提前返回时撤销本轮快照,避免残留状态影响下次
private void RollbackSnapshot()
{
_preMacroKeys.Clear();
_hasMacroSnapshot = false;
_cts?.Dispose();
_cts = null;
}
}
@@ -717,7 +717,7 @@
"nameEn": "wriothesley",
"type": "character",
"name": "莱欧斯利",
"hp": 10,
"hp": 11,
"energy": 3,
"element": "冰元素",
"weapon": "法器",
@@ -4670,6 +4670,83 @@
}
]
},
{
"id": 1418,
"nameEn": "flins",
"type": "character",
"name": "菲林斯",
"hp": 10,
"energy": 4,
"element": "雷元素",
"weapon": "长柄武器",
"skills": [
{
"nameEn": "pocztowy_demonspear",
"name": "扈圣魔枪",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "ancient_rite_arcane_light",
"name": "古律·孤灯遗秘",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 2
}
]
},
{
"nameEn": "ancient_ritual_cometh_the_night",
"name": "旧仪·夜客致访",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 4
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 4
}
]
},
{
"nameEn": "moonsign_benediction_old_world_secrets",
"name": "月兆祝赐·旧世潜藏",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1501,
"nameEn": "sucrose",
@@ -5296,7 +5373,7 @@
"nameEn": "xianyun",
"type": "character",
"name": "闲云",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "风元素",
"weapon": "法器",
@@ -7224,6 +7301,83 @@
}
]
},
{
"id": 1711,
"nameEn": "lauma",
"type": "character",
"name": "菈乌玛",
"hp": 11,
"energy": 2,
"element": "草元素",
"weapon": "法器",
"skills": [
{
"nameEn": "peregrination_of_linnunrata",
"name": "林麓旅踏",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "runo_dawnless_rest_of_karsikko",
"name": "圣言述咏·终宵永眠",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
}
]
},
{
"nameEn": "runo_all_hearts_become_the_beating_moon",
"name": "圣言述咏·众心为月",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "moonsign_benediction_natures_chorus",
"name": "月兆祝赐·千籁恩宠",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 2101,
"nameEn": "fatui_cryo_cicin_mage",
@@ -9515,6 +9669,75 @@
}
]
},
{
"id": 2605,
"nameEn": "experimental_field_generator",
"type": "character",
"name": "实验性场力发生装置",
"hp": 11,
"energy": 2,
"element": "岩元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "gravity_application_crush",
"name": "重力应用程式·砸击",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "gravity_application_point_null",
"name": "重力应用程式·点状抵消",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
}
]
},
{
"nameEn": "gravity_application_field_reduction",
"name": "重力应用程式·削减场域",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
}
]
},
{
"id": 2701,
"nameEn": "jadeplume_terrorshroom",
@@ -0,0 +1,279 @@
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoSkip.Audio;
internal sealed class DialogueOptionAudioWaiter
{
private const int SilenceDurationMilliseconds = 2000;
private const int SpeechStartGraceMilliseconds = 5000;
private const int NoSpeechQuietDurationMilliseconds = 1200;
private const int SpeechRiseDurationMilliseconds = 160;
private const int DetectorRetryDelayMilliseconds = 5000;
private const float SpeechProbabilityThreshold = 0.60f;
private const float MaybeSpeechProbabilityThreshold = 0.35f;
private readonly object _detectorLock = new();
private DialogueOptionVoiceDetector? _detector;
private int? _unavailableProcessId;
private DateTime _detectorRetryAfter = DateTime.MinValue;
private WaitState? _waitState;
public bool IsWaiting
{
get
{
using var _ = EnterDetectorLock();
return _waitState != null;
}
}
public void Cancel()
{
using var _ = EnterDetectorLock();
_waitState = null;
}
public void ReleaseDetector()
{
lock (_detectorLock)
{
if (_waitState?.Detector != null)
{
_waitState = null;
}
_detector?.Dispose();
_detector = null;
_unavailableProcessId = null;
_detectorRetryAfter = DateTime.MinValue;
}
}
public bool Start(int maxWaitMilliseconds, int fallbackDelayMilliseconds, ILogger logger)
{
using var _ = EnterDetectorLock();
if (maxWaitMilliseconds <= 0)
{
return StartFallbackWait(fallbackDelayMilliseconds);
}
var detector = GetDetector(logger);
if (detector == null)
{
return StartFallbackWait(fallbackDelayMilliseconds);
}
detector.Reset();
_waitState = WaitState.ForAudio(detector, maxWaitMilliseconds, fallbackDelayMilliseconds);
return true;
}
public bool Update(ILogger logger)
{
using var _ = EnterDetectorLock();
if (_waitState == null)
{
return true;
}
if (_waitState.IsFallback)
{
if (_waitState.Stopwatch.ElapsedMilliseconds < _waitState.MaxWaitMilliseconds)
{
return false;
}
_waitState = null;
return true;
}
try
{
var waitState = _waitState;
var elapsedMilliseconds = waitState.Stopwatch.ElapsedMilliseconds;
if (elapsedMilliseconds >= waitState.MaxWaitMilliseconds)
{
logger.LogDebug("自动剧情:Silero VAD 检测超时,最大语音概率 {ProbabilityMax:F2}", waitState.ProbabilityMax);
_waitState = null;
return true;
}
var probability = waitState.Detector!.Update();
if (float.IsNaN(probability) || float.IsInfinity(probability))
{
probability = 0f;
}
waitState.ProbabilityMax = Math.Max(waitState.ProbabilityMax, probability);
if (probability >= SpeechProbabilityThreshold)
{
waitState.VoiceLikeSinceMilliseconds ??= elapsedMilliseconds;
if (elapsedMilliseconds - waitState.VoiceLikeSinceMilliseconds >= SpeechRiseDurationMilliseconds)
{
waitState.HeardSpeech = true;
}
waitState.QuietSinceMilliseconds = null;
return false;
}
waitState.VoiceLikeSinceMilliseconds = null;
if (!waitState.HeardSpeech && probability > MaybeSpeechProbabilityThreshold)
{
waitState.QuietSinceMilliseconds = null;
return false;
}
waitState.QuietSinceMilliseconds ??= elapsedMilliseconds;
var requiredQuietMilliseconds = waitState.HeardSpeech ? SilenceDurationMilliseconds : NoSpeechQuietDurationMilliseconds;
if (!waitState.HeardSpeech && elapsedMilliseconds < SpeechStartGraceMilliseconds)
{
return false;
}
if (elapsedMilliseconds - waitState.QuietSinceMilliseconds < requiredQuietMilliseconds)
{
return false;
}
logger.LogDebug("自动剧情:Silero VAD 检测到{Text},最大语音概率 {ProbabilityMax:F2}", waitState.HeardSpeech ? "语音结束" : "语音未起播", waitState.ProbabilityMax);
_waitState = null;
return true;
}
catch (Exception e)
{
logger.LogWarning(e, "自动剧情:Silero VAD 检测失败,回退到固定延迟");
var fallbackDelayMilliseconds = _waitState?.FallbackDelayMilliseconds ?? 0;
ReleaseDetector();
_waitState = null;
return !StartFallbackWait(fallbackDelayMilliseconds);
}
}
private DialogueOptionVoiceDetector? GetDetector(ILogger logger)
{
lock (_detectorLock)
{
var targetProcessId = GetGameProcessId();
if (targetProcessId is not > 0)
{
logger.LogWarning("自动剧情:未能获取游戏进程 PID,将使用固定延迟");
return null;
}
var processId = targetProcessId.Value;
if (_detector != null && _detector.TargetProcessId == processId)
{
return _detector;
}
_detector?.Dispose();
_detector = null;
var now = DateTime.Now;
if (_unavailableProcessId == processId && now < _detectorRetryAfter)
{
return null;
}
try
{
_detector = DialogueOptionVoiceDetector.Create(processId);
_unavailableProcessId = null;
_detectorRetryAfter = DateTime.MinValue;
logger.LogDebug("自动剧情:Silero VAD 采样来源 游戏进程音频 PID={ProcessId}", processId);
return _detector;
}
catch (Exception e)
{
_unavailableProcessId = processId;
_detectorRetryAfter = now.AddMilliseconds(DetectorRetryDelayMilliseconds);
logger.LogWarning(e, "自动剧情:初始化 Silero VAD 失败,将使用固定延迟,稍后重试");
return null;
}
}
}
private static int? GetGameProcessId()
{
using var process = SystemControl.GetProcessByHandle(TaskContext.Instance().GameHandle);
return process?.Id;
}
private bool StartFallbackWait(int milliseconds)
{
if (milliseconds <= 0)
{
return false;
}
_waitState = WaitState.ForFallback(milliseconds);
return true;
}
private DetectorLockScope EnterDetectorLock()
{
Monitor.Enter(_detectorLock);
return new DetectorLockScope(_detectorLock);
}
private readonly struct DetectorLockScope : IDisposable
{
private readonly object _lockObject;
public DetectorLockScope(object lockObject)
{
_lockObject = lockObject;
}
public void Dispose()
{
Monitor.Exit(_lockObject);
}
}
private sealed class WaitState
{
private WaitState(DialogueOptionVoiceDetector? detector, int maxWaitMilliseconds, int fallbackDelayMilliseconds, bool isFallback)
{
Detector = detector;
MaxWaitMilliseconds = maxWaitMilliseconds;
FallbackDelayMilliseconds = fallbackDelayMilliseconds;
IsFallback = isFallback;
Stopwatch = Stopwatch.StartNew();
}
public DialogueOptionVoiceDetector? Detector { get; }
public int MaxWaitMilliseconds { get; }
public int FallbackDelayMilliseconds { get; }
public bool IsFallback { get; }
public Stopwatch Stopwatch { get; }
public bool HeardSpeech { get; set; }
public float ProbabilityMax { get; set; }
public long? VoiceLikeSinceMilliseconds { get; set; }
public long? QuietSinceMilliseconds { get; set; }
public static WaitState ForAudio(DialogueOptionVoiceDetector detector, int maxWaitMilliseconds, int fallbackDelayMilliseconds)
{
return new WaitState(detector, maxWaitMilliseconds, fallbackDelayMilliseconds, false);
}
public static WaitState ForFallback(int milliseconds)
{
return new WaitState(null, milliseconds, 0, true);
}
}
}
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoSkip.Audio;
internal sealed class DialogueOptionVoiceDetector : IDisposable
{
private readonly ProcessLoopbackAudioCapture _capture;
private readonly SileroVadDetector _vad;
private readonly List<float> _pendingSamples = [];
private int _pendingSampleOffset;
private DialogueOptionVoiceDetector(int targetProcessId, ProcessLoopbackAudioCapture capture, SileroVadDetector vad)
{
TargetProcessId = targetProcessId;
_capture = capture;
_vad = vad;
}
public int TargetProcessId { get; }
public static DialogueOptionVoiceDetector Create(int targetProcessId)
{
ProcessLoopbackAudioCapture? capture = null;
SileroVadDetector? vad = null;
try
{
vad = new SileroVadDetector();
capture = new ProcessLoopbackAudioCapture(targetProcessId);
return new DialogueOptionVoiceDetector(targetProcessId, capture, vad);
}
catch
{
capture?.Dispose();
vad?.Dispose();
throw;
}
}
public void Reset()
{
_pendingSamples.Clear();
_pendingSampleOffset = 0;
_vad.Reset();
_capture.DiscardAvailableSamples();
}
public float Update()
{
_capture.ReadAvailableSamples(_pendingSamples);
var probabilityMax = 0f;
while (_pendingSamples.Count - _pendingSampleOffset >= SileroVadDetector.FrameSampleCount)
{
var frame = new float[SileroVadDetector.FrameSampleCount];
_pendingSamples.CopyTo(_pendingSampleOffset, frame, 0, frame.Length);
_pendingSampleOffset += frame.Length;
probabilityMax = Math.Max(probabilityMax, _vad.Predict(frame));
}
CompactPendingSamples();
return probabilityMax;
}
private void CompactPendingSamples()
{
if (_pendingSampleOffset == 0)
{
return;
}
if (_pendingSampleOffset >= _pendingSamples.Count)
{
_pendingSamples.Clear();
}
else
{
_pendingSamples.RemoveRange(0, _pendingSampleOffset);
}
_pendingSampleOffset = 0;
}
public void Dispose()
{
_capture.Dispose();
_vad.Dispose();
}
}
@@ -0,0 +1,376 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using Vanara.PInvoke;
using static Vanara.PInvoke.CoreAudio;
namespace BetterGenshinImpact.GameTask.AutoSkip.Audio;
internal sealed class ProcessLoopbackAudioCapture : IDisposable
{
private const string VirtualAudioDeviceProcessLoopback = @"VAD\Process_Loopback";
private const long BufferDurationHundredNanoseconds = 1_000_000;
private const ushort WaveFormatPcm = 1;
private const ushort ChannelCount = 1;
private const ushort BitsPerSample = 16;
private const ushort BlockAlign = (ushort)(ChannelCount * BitsPerSample / 8);
private const uint AverageBytesPerSecond = (uint)(SileroVadDetector.SampleRate * BlockAlign);
private readonly IAudioClient _audioClient;
private readonly IAudioCaptureClient _captureClient;
private bool _started;
public ProcessLoopbackAudioCapture(int targetProcessId)
{
IAudioClient? audioClient = null;
IAudioCaptureClient? captureClient = null;
try
{
audioClient = ActivateAudioClient(targetProcessId);
InitializeAudioClient(audioClient);
var captureClientId = typeof(IAudioCaptureClient).GUID;
captureClient = (IAudioCaptureClient)audioClient.GetService(ref captureClientId);
audioClient.Start();
_audioClient = audioClient;
_captureClient = captureClient;
_started = true;
}
catch
{
ReleaseComObject(captureClient);
ReleaseComObject(audioClient);
throw;
}
}
public void ReadAvailableSamples(List<float> destination)
{
ReadAvailableSamplesCore(destination);
}
public void DiscardAvailableSamples()
{
ReadAvailableSamplesCore(null);
}
private void ReadAvailableSamplesCore(List<float>? destination)
{
while (true)
{
_captureClient.GetNextPacketSize(out var packetFrameCount).ThrowIfFailed();
if (packetFrameCount == 0)
{
return;
}
_captureClient.GetBuffer(out var dataPointer, out var frameCount, out var flags, out _, out _).ThrowIfFailed();
try
{
if (frameCount == 0)
{
continue;
}
var sampleCount = checked((int)frameCount);
if ((flags & AUDCLNT_BUFFERFLAGS.AUDCLNT_BUFFERFLAGS_SILENT) != 0)
{
if (destination != null)
{
for (var i = 0; i < sampleCount; i++)
{
destination.Add(0f);
}
}
continue;
}
if (destination == null)
{
continue;
}
var samples = new short[sampleCount];
Marshal.Copy(dataPointer, samples, 0, samples.Length);
for (var i = 0; i < samples.Length; i++)
{
destination.Add(samples[i] / 32768f);
}
}
finally
{
_captureClient.ReleaseBuffer(frameCount).ThrowIfFailed();
}
}
}
public void Dispose()
{
try
{
if (_started)
{
_audioClient.Stop();
}
}
catch (Exception)
{
// Best-effort cleanup only.
}
finally
{
ReleaseComObject(_captureClient);
ReleaseComObject(_audioClient);
}
}
private static void InitializeAudioClient(IAudioClient audioClient)
{
var format = new WaveFormatEx
{
WFormatTag = WaveFormatPcm,
NChannels = ChannelCount,
NSamplesPerSec = SileroVadDetector.SampleRate,
NAvgBytesPerSec = AverageBytesPerSecond,
NBlockAlign = BlockAlign,
WBitsPerSample = BitsPerSample,
CbSize = 0
};
var formatPointer = Marshal.AllocHGlobal(Marshal.SizeOf<WaveFormatEx>());
try
{
Marshal.StructureToPtr(format, formatPointer, false);
var audioSessionGuid = Guid.Empty;
var streamFlags =
AUDCLNT_STREAMFLAGS.AUDCLNT_STREAMFLAGS_LOOPBACK |
AUDCLNT_STREAMFLAGS.AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM |
AUDCLNT_STREAMFLAGS.AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
audioClient.Initialize(
AUDCLNT_SHAREMODE.AUDCLNT_SHAREMODE_SHARED,
streamFlags,
BufferDurationHundredNanoseconds,
0,
formatPointer,
ref audioSessionGuid).ThrowIfFailed();
}
finally
{
Marshal.FreeHGlobal(formatPointer);
}
}
private static IAudioClient ActivateAudioClient(int targetProcessId)
{
var parameters = new AudioClientActivationParams
{
ActivationType = AudioClientActivationType.ProcessLoopback,
ProcessLoopbackParams = new AudioClientProcessLoopbackParams
{
TargetProcessId = (uint)targetProcessId,
ProcessLoopbackMode = ProcessLoopbackMode.IncludeTargetProcessTree
}
};
var size = Marshal.SizeOf<AudioClientActivationParams>();
var parametersPointer = Marshal.AllocHGlobal(size);
IActivateAudioInterfaceAsyncOperation? operation = null;
try
{
Marshal.StructureToPtr(parameters, parametersPointer, false);
var propVariant = PropVariant.FromBlob(parametersPointer, (uint)size);
using var handler = new AudioInterfaceActivationHandler();
var audioClientId = typeof(IAudioClient).GUID;
Marshal.ThrowExceptionForHR(ActivateAudioInterfaceAsyncNative(
VirtualAudioDeviceProcessLoopback,
ref audioClientId,
ref propVariant,
handler,
out operation));
var audioClient = handler.WaitForAudioClient();
GC.KeepAlive(handler);
return audioClient;
}
finally
{
if (operation != null)
{
ReleaseComObject(operation);
}
Marshal.FreeHGlobal(parametersPointer);
}
}
private static void ReleaseComObject(object? comObject)
{
if (comObject == null)
{
return;
}
try
{
if (Marshal.IsComObject(comObject))
{
Marshal.ReleaseComObject(comObject);
}
}
catch (InvalidComObjectException)
{
}
catch (COMException)
{
}
}
[DllImport("Mmdevapi.dll", EntryPoint = "ActivateAudioInterfaceAsync", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
private static extern int ActivateAudioInterfaceAsyncNative(
[MarshalAs(UnmanagedType.LPWStr)] string deviceInterfacePath,
ref Guid riid,
ref PropVariant activationParams,
IActivateAudioInterfaceCompletionHandler completionHandler,
out IActivateAudioInterfaceAsyncOperation activationOperation);
[StructLayout(LayoutKind.Sequential)]
private struct AudioClientProcessLoopbackParams
{
public uint TargetProcessId;
public ProcessLoopbackMode ProcessLoopbackMode;
}
[StructLayout(LayoutKind.Sequential)]
private struct AudioClientActivationParams
{
public AudioClientActivationType ActivationType;
public AudioClientProcessLoopbackParams ProcessLoopbackParams;
}
[StructLayout(LayoutKind.Sequential)]
private struct Blob
{
public uint CbSize;
public IntPtr PBlobData;
}
[StructLayout(LayoutKind.Explicit)]
private struct PropVariant
{
private const ushort VtBlob = 65;
[FieldOffset(0)]
public ushort Vt;
[FieldOffset(2)]
public ushort WReserved1;
[FieldOffset(4)]
public ushort WReserved2;
[FieldOffset(6)]
public ushort WReserved3;
[FieldOffset(8)]
public Blob Blob;
public static PropVariant FromBlob(IntPtr data, uint size)
{
return new PropVariant
{
Vt = VtBlob,
Blob = new Blob
{
CbSize = size,
PBlobData = data
}
};
}
}
private enum ProcessLoopbackMode
{
IncludeTargetProcessTree = 0,
ExcludeTargetProcessTree = 1
}
private enum AudioClientActivationType
{
Default = 0,
ProcessLoopback = 1
}
[StructLayout(LayoutKind.Sequential)]
private struct WaveFormatEx
{
public ushort WFormatTag;
public ushort NChannels;
public uint NSamplesPerSec;
public uint NAvgBytesPerSec;
public ushort NBlockAlign;
public ushort WBitsPerSample;
public ushort CbSize;
}
[ComVisible(true)]
private sealed class AudioInterfaceActivationHandler : IActivateAudioInterfaceCompletionHandler, IDisposable
{
private readonly ManualResetEventSlim _completed = new(false);
private volatile bool _disposed;
private Exception? _exception;
private IAudioClient? _audioClient;
public void ActivateCompleted(IActivateAudioInterfaceAsyncOperation operation)
{
try
{
operation.GetActivateResult(out var activateResult, out var activatedInterface).ThrowIfFailed();
activateResult.ThrowIfFailed();
_audioClient = activatedInterface as IAudioClient
?? throw new InvalidCastException("ActivateAudioInterfaceAsync 未返回 IAudioClient");
}
catch (Exception e)
{
_exception = e;
}
finally
{
if (!_disposed)
{
try
{
_completed.Set();
}
catch (ObjectDisposedException)
{
}
}
}
}
public IAudioClient WaitForAudioClient()
{
if (!_completed.Wait(TimeSpan.FromSeconds(5)))
{
throw new TimeoutException("等待进程音频接口激活超时");
}
if (_exception != null)
{
throw _exception;
}
return _audioClient ?? throw new InvalidOperationException("进程音频接口激活失败");
}
public void Dispose()
{
_disposed = true;
_completed.Dispose();
}
}
}
@@ -0,0 +1,87 @@
using BetterGenshinImpact.Core.Recognition.ONNX;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using System;
using System.IO;
using System.Linq;
namespace BetterGenshinImpact.GameTask.AutoSkip.Audio;
internal sealed class SileroVadDetector : IDisposable
{
public const int SampleRate = 16000;
public const int FrameSampleCount = 512;
private const int StatePlaneCount = 2;
private const int StateBatchCount = 1;
private const int StateSize = 128;
private readonly InferenceSession _session;
private readonly float[] _state = new float[StatePlaneCount * StateBatchCount * StateSize];
private readonly long[] _sampleRate = [SampleRate];
public SileroVadDetector()
{
var modelPath = BgiOnnxModel.SileroVad.ModalPath;
if (!File.Exists(modelPath))
{
throw new FileNotFoundException("Silero VAD 模型文件不存在", modelPath);
}
_session = new InferenceSession(modelPath, CreateSessionOptions());
}
public void Reset()
{
Array.Clear(_state);
}
public float Predict(float[] samples)
{
if (samples.Length != FrameSampleCount)
{
throw new ArgumentException($"Silero VAD 需要 {FrameSampleCount} 个采样点", nameof(samples));
}
var inputTensor = new DenseTensor<float>(samples, [1, FrameSampleCount]);
var stateTensor = new DenseTensor<float>(_state, [StatePlaneCount, StateBatchCount, StateSize]);
var sampleRateTensor = new DenseTensor<long>(_sampleRate, Array.Empty<int>());
using var results = _session.Run(
[
NamedOnnxValue.CreateFromTensor("input", inputTensor),
NamedOnnxValue.CreateFromTensor("state", stateTensor),
NamedOnnxValue.CreateFromTensor("sr", sampleRateTensor)
]);
var probability = results.First(x => x.Name == "output").AsEnumerable<float>().FirstOrDefault();
var nextState = results.First(x => x.Name == "stateN").AsEnumerable<float>();
var index = 0;
foreach (var value in nextState)
{
if (index >= _state.Length)
{
break;
}
_state[index++] = value;
}
return Math.Clamp(probability, 0f, 1f);
}
public void Dispose()
{
_session.Dispose();
}
private static SessionOptions CreateSessionOptions()
{
return new SessionOptions
{
ExecutionMode = ExecutionMode.ORT_SEQUENTIAL,
GraphOptimizationLevel = GraphOptimizationLevel.ORT_ENABLE_BASIC,
InterOpNumThreads = 1,
IntraOpNumThreads = 1
};
}
}
@@ -36,6 +36,18 @@ public partial class AutoSkipConfig : ObservableObject
[ObservableProperty]
private int _afterChooseOptionSleepDelay = 0;
/// <summary>
/// 选择剧情选项前,通过游戏进程音频的人声检测自动等待语音结束
/// </summary>
[ObservableProperty]
private bool _autoWaitDialogueOptionVoiceEnabled = false;
/// <summary>
/// 人声检测等待语音结束的最大等待时间(秒)
/// </summary>
[ObservableProperty]
private int _dialogueOptionVoiceMaxWaitSeconds = 30;
/// <summary>
/// 点击对话框前的延迟(毫秒)
/// </summary>
@@ -4,6 +4,7 @@ using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoSkip.Audio;
using BetterGenshinImpact.GameTask.AutoSkip.Assets;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using BetterGenshinImpact.GameTask.Common;
@@ -37,7 +38,24 @@ public partial class AutoSkipTrigger : ITaskTrigger
private readonly ILogger<AutoSkipTrigger> _logger = App.GetLogger<AutoSkipTrigger>();
public string Name => "自动剧情";
public bool IsEnabled { get; set; }
private bool _isEnabled;
public bool IsEnabled
{
get => _isEnabled;
set
{
if (_isEnabled == value)
{
return;
}
_isEnabled = value;
if (!value)
{
ReleaseChooseOptionWait("触发器关闭");
}
}
}
public int Priority => 20;
public bool IsExclusive => false;
@@ -55,6 +73,7 @@ public partial class AutoSkipTrigger : ITaskTrigger
private readonly AutoSkipAssets _autoSkipAssets;
private readonly AutoSkipConfig _config;
private readonly DialogueOptionAudioWaiter _dialogueOptionAudioWaiter = new();
/// <summary>
/// 不自动点击的选项,优先级低于橙色文字点击
@@ -162,25 +181,50 @@ public partial class AutoSkipTrigger : ITaskTrigger
private DateTime _prevClickTime = DateTime.MinValue;
private DateTime _prevBringToFrontTime = DateTime.MinValue;
private DateTime _chooseOptionDelayUntil = DateTime.MinValue;
private DateTime _chooseOptionWaitRecheckUntil = DateTime.MinValue;
private bool _pendingBringToFront;
public void OnCapture(CaptureContent content)
{
if ((DateTime.Now - _prevExecute).TotalMilliseconds <= 200)
RefreshOperationMode();
if (!_config.AutoWaitDialogueOptionVoiceEnabled)
{
return;
if (_dialogueOptionAudioWaiter.IsWaiting)
{
CancelChooseOptionWait("人声检测配置关闭");
}
_dialogueOptionAudioWaiter.ReleaseDetector();
}
UseBackgroundOperation = IsBackgroundRunning && !SystemControl.IsGenshinImpactActive();
_prevExecute = DateTime.Now;
GetDailyRewardsEsc(_config, content);
// 找左上角剧情自动的按钮
var isPlaying = content.CurrentGameUiCategory == GameUiCategory.Talk
|| Bv.IsInTalkUi(content.CaptureRectArea); // 播放中
if (IsChooseOptionWaiting())
{
if (!HasDialogueAdvanceTarget(content.CaptureRectArea, isPlaying))
{
CancelChooseOptionWait("对话或选项已变化");
}
else
{
UpdateChooseOptionWait();
return;
}
}
if ((DateTime.Now - _prevExecute).TotalMilliseconds <= 200)
{
return;
}
_prevExecute = DateTime.Now;
GetDailyRewardsEsc(_config, content);
if (isPlaying && UseBackgroundOperation)
{
_pendingBringToFront = true;
@@ -487,7 +531,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
if (isInChat)
{
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
if (!PrepareBeforeChooseOption())
{
return true;
}
var fKey = AutoPickAssets.Instance.PickVk;
if (_config.IsClickFirstChatOption())
{
@@ -536,7 +584,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
using var exclamationIconRa = region.Find(_autoSkipAssets.ExclamationIconRo);
if (!exclamationIconRa.IsEmpty())
{
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
if (!PrepareBeforeChooseOption())
{
return true;
}
exclamationIconRa.Click();
AutoSkipLog("点击感叹号选项");
return true;
@@ -604,7 +656,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
{
if (item.Text.Contains(customOption))
{
ClickOcrRegion(item);
if (!ClickOcrRegion(item))
{
return true;
}
return true;
}
}
@@ -624,7 +680,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
// 选择关键词
if (_selectList.Any(s => item.Text.Contains(s)))
{
ClickOcrRegion(item);
if (!ClickOcrRegion(item))
{
return true;
}
return true;
}
@@ -643,7 +703,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
{
if (_config.AutoGetDailyRewardsEnabled && (item.Text.Contains("每日") || item.Text.Contains("委托")))
{
ClickOcrRegion(item, "每日委托");
if (!ClickOcrRegion(item, "每日委托"))
{
return true;
}
TaskControl.Sleep(800);
// 6.2 每日提示确认
@@ -658,7 +722,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
}
else if (_config.AutoReExploreEnabled && (item.Text.Contains("探索") || item.Text.Contains("派遣")))
{
ClickOcrRegion(item, "探索派遣");
if (!ClickOcrRegion(item, "探索派遣"))
{
return true;
}
Thread.Sleep(800); // 等待探索派遣界面打开
new OneKeyExpeditionTask().Run(_autoSkipAssets);
}
@@ -667,7 +735,10 @@ public partial class AutoSkipTrigger : ITaskTrigger
&& !item.Text.Contains("探索")
&& !item.Text.Contains("派遣"))
{
ClickOcrRegion(item);
if (!ClickOcrRegion(item))
{
return true;
}
}
return true;
@@ -697,8 +768,10 @@ public partial class AutoSkipTrigger : ITaskTrigger
clickRegion = rs[random.Next(0, rs.Count)];
}
ClickOcrRegion(clickRegion);
AutoSkipLog(clickRegion.Text);
if (!ClickOcrRegion(clickRegion))
{
return true;
}
}
else
{
@@ -709,8 +782,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
}
// 没OCR到文字,直接选择气泡选项
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
ClickOcrRegion(clickRect);
if (!ClickOcrRegion(clickRect))
{
return true;
}
var msg = _config.IsClickFirstChatOption() ? "第一个" : "最后一个";
AutoSkipLog($"点击{msg}气泡选项");
}
@@ -731,13 +807,17 @@ public partial class AutoSkipTrigger : ITaskTrigger
return false;
}
private void ClickOcrRegion(Region region, string optionType = "")
private bool ClickOcrRegion(Region region, string optionType = "")
{
if (string.IsNullOrEmpty(optionType))
{
Thread.Sleep(_config.AfterChooseOptionSleepDelay);
if (!PrepareBeforeChooseOption())
{
return false;
}
}
RefreshOperationMode();
if (UseBackgroundOperation && !SystemControl.IsGenshinImpactActive())
{
region.BackgroundClick();
@@ -748,6 +828,133 @@ public partial class AutoSkipTrigger : ITaskTrigger
}
AutoSkipLog(region.Text);
return true;
}
private bool PrepareBeforeChooseOption()
{
RefreshOperationMode();
if (DateTime.Now <= _chooseOptionWaitRecheckUntil)
{
return true;
}
if (IsChooseOptionWaiting())
{
return false;
}
if (_config.AutoWaitDialogueOptionVoiceEnabled)
{
var waitingStarted = _dialogueOptionAudioWaiter.Start(
Math.Clamp(_config.DialogueOptionVoiceMaxWaitSeconds, 0, 600) * 1000,
_config.AfterChooseOptionSleepDelay,
_logger);
return !waitingStarted;
}
if (_config.AfterChooseOptionSleepDelay > 0)
{
_chooseOptionDelayUntil = DateTime.Now.AddMilliseconds(_config.AfterChooseOptionSleepDelay);
return false;
}
return true;
}
private bool UpdateChooseOptionWait()
{
var waitCompleted = false;
if (_dialogueOptionAudioWaiter.IsWaiting && _dialogueOptionAudioWaiter.Update(_logger))
{
waitCompleted = true;
}
if (_chooseOptionDelayUntil != DateTime.MinValue && DateTime.Now >= _chooseOptionDelayUntil)
{
_chooseOptionDelayUntil = DateTime.MinValue;
waitCompleted = true;
}
if (!waitCompleted)
{
return false;
}
RefreshOperationMode();
_chooseOptionWaitRecheckUntil = DateTime.Now.AddMilliseconds(1200);
_logger.LogDebug("自动剧情:选项等待结束,放弃本轮旧识别结果,等待下一帧重新判断选项与前后台状态");
return true;
}
private bool IsChooseOptionWaiting()
{
return _dialogueOptionAudioWaiter.IsWaiting || _chooseOptionDelayUntil != DateTime.MinValue;
}
private void CancelChooseOptionWait(string reason)
{
if (!IsChooseOptionWaiting())
{
return;
}
_dialogueOptionAudioWaiter.Cancel();
_chooseOptionDelayUntil = DateTime.MinValue;
_chooseOptionWaitRecheckUntil = DateTime.MinValue;
_logger.LogDebug("自动剧情:选项等待取消,原因:{Reason}", reason);
}
private void ReleaseChooseOptionWait(string reason)
{
var hadWait = IsChooseOptionWaiting();
_dialogueOptionAudioWaiter.Cancel();
_dialogueOptionAudioWaiter.ReleaseDetector();
_chooseOptionDelayUntil = DateTime.MinValue;
_chooseOptionWaitRecheckUntil = DateTime.MinValue;
if (hadWait)
{
_logger.LogDebug("自动剧情:选项等待取消,原因:{Reason}", reason);
}
}
private bool HasDialogueOption(ImageRegion region)
{
using var chatOptionResult = region.Find(_autoSkipAssets.OptionIconRo);
if (chatOptionResult.IsExist())
{
return true;
}
using var pickRa = region.Find(AutoPickAssets.Instance.ChatPickRo);
if (pickRa.IsExist())
{
return true;
}
using var exclamationIconRa = region.Find(_autoSkipAssets.ExclamationIconRo);
return !exclamationIconRa.IsEmpty();
}
private bool HasDialogueAdvanceTarget(ImageRegion region, bool isPlaying)
{
if (isPlaying && HasDialogueOption(region))
{
return true;
}
if (Bv.IsInMainUi(region))
{
return false;
}
return TryHandleBottomTriangle(region, (_, _, _) => { });
}
private void RefreshOperationMode()
{
UseBackgroundOperation = IsBackgroundRunning && !SystemControl.IsGenshinImpactActive();
}
private void HangoutOptionClick(HangoutOption option)
@@ -830,9 +1037,35 @@ public partial class AutoSkipTrigger : ITaskTrigger
{
return;
}
//屏幕底部中间,实心三角的位置
TryHandleBottomTriangle(content.CaptureRectArea, (croppedRegion, triangleRect, area) =>
{
if (!PrepareBeforeChooseOption())
{
return;
}
using var triangleRegion = croppedRegion.Derive(triangleRect);
if (UseBackgroundOperation && !SystemControl.IsGenshinImpactActive())
{
triangleRegion.BackgroundClick();
}
else
{
triangleRegion.Click();
}
_prevCloseItemTime = DateTime.Now;
_logger.LogInformation("自动剧情:{Text} 面积 {Area}", "点击底部三角形", area);
_prevPlayingTime = DateTime.Now; // 此时认为还在自动剧情
});
}
private bool TryHandleBottomTriangle(ImageRegion captureRegion, Action<ImageRegion, Rect, double> onFound)
{
// 屏幕底部中间,实心三角的位置
var scale = TaskContext.Instance().SystemInfo.AssetScale;
using var croppedRegion = content.CaptureRectArea.DeriveCrop(900 * scale, 960 * scale, 120 * scale, 120 * scale);
using var croppedRegion = captureRegion.DeriveCrop(900 * scale, 960 * scale, 120 * scale, 120 * scale);
using var hsv = new Mat();
Cv2.CvtColor(croppedRegion.SrcMat, hsv, ColorConversionCodes.BGR2HSV);
@@ -853,19 +1086,11 @@ public partial class AutoSkipTrigger : ITaskTrigger
if (area < 10 || area > 50 || approx.Length != 3) continue;
if (UseBackgroundOperation && !SystemControl.IsGenshinImpactActive())
{
croppedRegion.Derive(Cv2.BoundingRect(approx)).BackgroundClick();
}
else
{
croppedRegion.Derive(Cv2.BoundingRect(approx)).Click();
}
_prevCloseItemTime = DateTime.Now;
_logger.LogInformation("自动剧情:{Text} 面积 {Area}", "点击底部三角形",area);
_prevPlayingTime = DateTime.Now; // 此时认为还在自动剧情
return;
onFound(croppedRegion, Cv2.BoundingRect(approx), area);
return true;
}
return false;
}
/// <summary>
@@ -105,55 +105,11 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
}
/// <summary>
/// 注册所有状态处理器和检测器 - 子类核心职责
/// 每个状态对应一个处理方法,消除 switch-case
/// 注册状态图并扫描 Attribute 标记的检测器、处理器。
/// </summary>
private void RegisterAllStateHandlers()
{
// ========== 注册状态检测器 ==========
// 注意:检测顺序会影响性能,先放快速的模板匹配检测
RegisterStateDetectors(
// 第一优先级:快速模板匹配(不需要 OCR)
(StygianState.ContinueOrExit, DetectContinueOrExit),
(StygianState.TeleportMap, DetectTeleportMap),
(StygianState.DomainLobby, DetectDomainLobby),
(StygianState.BattleArena, DetectBattleArena),
(StygianState.MainWorld, DetectMainWorld),
// 第二优先级:模板匹配 + 局部 OCR
(StygianState.BattleResultWin, DetectBattleResultWin),
(StygianState.BattleResultLose, DetectBattleResultLose),
// 第三优先级:OCR 检测
(StygianState.ResinSelect, DetectResinSelect),
(StygianState.LeylineFlowerPrompt, DetectLeylineFlowerPrompt),
(StygianState.BossSelect, DetectBossSelect),
(StygianState.DifficultySelect, DetectDifficultySelect),
(StygianState.DomainEntrance, DetectDomainEntrance),
(StygianState.EventMenu, DetectEventMenu),
(StygianState.StygianOnslaughtPage, DetectStygianOnslaughtPage)
);
// ========== 注册状态处理器 ==========
// 导航阶段处理器
RegisterStateHandlers(
(StygianState.MainWorld, HandleMainWorldState),
(StygianState.EventMenu, HandleEventMenuState),
(StygianState.StygianOnslaughtPage, HandleStygianOnslaughtPageState),
(StygianState.TeleportMap, HandleTeleportMapState),
(StygianState.DomainEntrance, HandleDomainEntranceState),
(StygianState.DifficultySelect, HandleDifficultySelectState),
(StygianState.DomainLobby, HandleDomainLobbyState),
// 战斗阶段处理器
(StygianState.BossSelect, HandleBossSelectState),
(StygianState.BattleArena, HandleBattleArenaState),
(StygianState.BattleResultWin, HandleBattleResultWinState),
(StygianState.BattleResultLose, HandleBattleResultLoseState),
(StygianState.LeylineFlowerPrompt, HandleLeylineFlowerState),
(StygianState.ResinSelect, HandleResinSelectState),
(StygianState.ContinueOrExit, HandleContinueOrExitState)
);
RegisterStateMethodsByAttribute();
// 注册状态转换关系 - 有限状态机的核心
// 每个状态只能转换到有限的下一个状态,用于优化检测
@@ -164,7 +120,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
(StygianState.EventMenu, [StygianState.StygianOnslaughtPage]),
(StygianState.StygianOnslaughtPage, [StygianState.TeleportMap, StygianState.DomainEntrance]),
(StygianState.TeleportMap, [StygianState.DomainEntrance]),
(StygianState.DomainEntrance, [StygianState.DomainEntrance, StygianState.DifficultySelect]),
(StygianState.DomainEntrance, [StygianState.DifficultySelect]),
(StygianState.DifficultySelect, [StygianState.DomainLobby]),
(StygianState.DomainLobby, [StygianState.BossSelect, StygianState.LeylineFlowerPrompt]),
@@ -177,9 +133,6 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
(StygianState.ResinSelect, [StygianState.ContinueOrExit, StygianState.DomainLobby]),
(StygianState.ContinueOrExit, [StygianState.BattleArena, StygianState.MainWorld])
);
// 未知状态处理器
RegisterUnknownStateHandler(HandleUnknownState);
}
public async Task Start(CancellationToken ct)
@@ -227,29 +180,34 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
// ========== 第一优先级:快速模板匹配 ==========
[StateDetector(StygianState.ContinueOrExit, Order = 10)]
private bool DetectContinueOrExit(ImageRegion ra)
{
return ra.Find(AutoFightAssets.Instance.ConfirmRa).IsExist() &&
ra.Find(AutoFightAssets.Instance.ExitRa).IsExist();
}
[StateDetector(StygianState.TeleportMap, Order = 20)]
private bool DetectTeleportMap(ImageRegion ra)
{
return ra.Find(QuickTeleportAssets.Instance.TeleportButtonRo).IsExist();
}
[StateDetector(StygianState.DomainLobby, Order = 30)]
private bool DetectDomainLobby(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.LeylineDisorderIconRo).IsExist() &&
ra.Find(ElementAssets.Instance.InventoryRo).IsExist();
}
[StateDetector(StygianState.BattleArena, Order = 40)]
private bool DetectBattleArena(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.LeylineDisorderIconRo).IsExist() &&
!ra.Find(ElementAssets.Instance.InventoryRo).IsExist();
}
[StateDetector(StygianState.MainWorld, Order = 50)]
private bool DetectMainWorld(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.PaimonMenuRo).IsExist();
@@ -257,6 +215,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
// ========== 第二优先级:模板匹配 + 局部 OCR ==========
[StateDetector(StygianState.BattleResultWin, Order = 60)]
private bool DetectBattleResultWin(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.BtnWhiteCancel).IsExist() &&
@@ -264,6 +223,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
.Any(o => o.Text.Contains("返回"));
}
[StateDetector(StygianState.BattleResultLose, Order = 70)]
private bool DetectBattleResultLose(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.BtnWhiteConfirm).IsExist() &&
@@ -273,6 +233,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
// ========== 第三优先级:OCR 检测 ==========
[StateDetector(StygianState.ResinSelect, Order = 80)]
private bool DetectResinSelect(ImageRegion ra)
{
var ocrResult = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.2, ra.Height * 0.2, ra.Width * 0.6, ra.Height * 0.6));
@@ -280,6 +241,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
ocrResult.Any(t => t.Text.Contains("浓缩树脂") || t.Text.Contains("原粹树脂"));
}
[StateDetector(StygianState.LeylineFlowerPrompt, Order = 90)]
private bool DetectLeylineFlowerPrompt(ImageRegion ra)
{
var ocrResult = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.2, ra.Height * 0.2, ra.Width * 0.6, ra.Height * 0.6));
@@ -287,6 +249,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return found;
}
[StateDetector(StygianState.BossSelect, Order = 100)]
private bool DetectBossSelect(ImageRegion ra)
{
// "角色预览" 在右上角,"开始挑战" 在右下角
@@ -298,6 +261,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return found;
}
[StateDetector(StygianState.DifficultySelect, Order = 110)]
private bool DetectDifficultySelect(ImageRegion ra)
{
// "单人挑战" 在右下角
@@ -305,6 +269,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
.Any(o => o.Text.Contains("单人挑战"));
}
[StateDetector(StygianState.DomainEntrance, Order = 120)]
private bool DetectDomainEntrance(ImageRegion ra)
{
// 秘境入口特征:屏幕右侧有"幽境危战"四个字
@@ -314,6 +279,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
.Any(o => o.Text.Contains("幽境危战"));
}
[StateDetector(StygianState.EventMenu, Order = 130)]
private bool DetectEventMenu(ImageRegion ra)
{
// 活动一览位置:左上角(125, 142), 右下角(238, 170)
@@ -322,6 +288,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
.Any(o => o.Text.Contains("活动一览"));
}
[StateDetector(StygianState.StygianOnslaughtPage, Order = 140)]
private bool DetectStygianOnslaughtPage(ImageRegion ra)
{
return ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.55, ra.Height * 0.3, ra.Width * 0.4, ra.Height * 0.6))
@@ -332,6 +299,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
#region 状态处理器实现 - 每个 case 的行为
[StateHandler(StygianState.MainWorld)]
private async Task<StateHandlerResult> HandleMainWorldState(BvPage page)
{
Logger.LogInformation($"{Name}:打开活动菜单");
@@ -340,6 +308,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 EventMenu 或 StygianOnslaughtPage
}
[StateHandler(StygianState.EventMenu, RetryTimeout = 30000)]
private async Task<StateHandlerResult> HandleEventMenuState(BvPage page)
{
Logger.LogInformation($"{Name}:在活动菜单中查找幽境危战");
@@ -380,11 +349,13 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
Logger.LogInformation($"{Name}:第 {attempt + 1} 次未找到幽境危战,尝试反向滑动");
}
// 如果两次都没找到,可能"幽境危战"已经被选中,直接尝试检测下一状态
Logger.LogWarning($"{Name}:未找到幽境危战,可能已被选中,尝试检测 StygianOnslaughtPage");
return StateHandlerResult.Success; // 让状态机继续等待邻接状态出现
// 如果两次都没找到,可能详情页已在右侧;交给状态机检测下一状态。
// 若检测不到 StygianOnslaughtPage,基类会累计当前 EventMenu 状态的转场超时次数,并在超限后退出。
Logger.LogWarning($"{Name}:未找到幽境危战,尝试检测 StygianOnslaughtPage");
return StateHandlerResult.Success;
}
[StateHandler(StygianState.StygianOnslaughtPage, RetryTimes = 10)]
private async Task<StateHandlerResult> HandleStygianOnslaughtPageState(BvPage page)
{
Logger.LogInformation($"{Name}:点击前往挑战");
@@ -400,6 +371,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 TeleportMap 或 DomainEntrance
}
[StateHandler(StygianState.TeleportMap)]
private async Task<StateHandlerResult> HandleTeleportMapState(BvPage page)
{
Logger.LogInformation($"{Name}:点击传送");
@@ -415,6 +387,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 DomainEntrance
}
[StateHandler(StygianState.DomainEntrance, RetryTimeout = 15000)]
private async Task<StateHandlerResult> HandleDomainEntranceState(BvPage page)
{
Logger.LogInformation($"{Name}:交互秘境入口");
@@ -423,6 +396,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 DifficultySelect
}
[StateHandler(StygianState.DifficultySelect)]
private async Task<StateHandlerResult> HandleDifficultySelectState(BvPage page)
{
Logger.LogInformation($"{Name}:选择困难难度并进入");
@@ -444,6 +418,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 DomainLobby
}
[StateHandler(StygianState.DomainLobby)]
private async Task<StateHandlerResult> HandleDomainLobbyState(BvPage page)
{
Logger.LogInformation($"{Name}:步行前往钥匙");
@@ -451,6 +426,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 BossSelect 或 LeylineFlowerPrompt
}
[StateHandler(StygianState.BossSelect)]
private async Task<StateHandlerResult> HandleBossSelectState(BvPage page)
{
Logger.LogInformation($"{Name}:选择Boss并开始挑战");
@@ -468,6 +444,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 BattleArena
}
[StateHandler(StygianState.BattleArena)]
private Task<StateHandlerResult> HandleBattleArenaState(BvPage page)
{
// 战斗场地已准备就绪,无需额外操作
@@ -476,6 +453,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return Task.FromResult(StateHandlerResult.Wait); // 状态机会检测到目标状态并退出
}
[StateHandler(StygianState.BattleResultWin)]
private async Task<StateHandlerResult> HandleBattleResultWinState(BvPage page)
{
Logger.LogInformation($"{Name}:挑战成功,等待返回大厅");
@@ -485,6 +463,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 DomainLobby
}
[StateHandler(StygianState.BattleResultLose)]
private async Task<StateHandlerResult> HandleBattleResultLoseState(BvPage page)
{
Logger.LogWarning($"{Name}:挑战失败,等待返回Boss选择");
@@ -494,6 +473,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 BossSelect
}
[StateHandler(StygianState.LeylineFlowerPrompt)]
private async Task<StateHandlerResult> HandleLeylineFlowerState(BvPage page)
{
Logger.LogInformation($"{Name}:交互地脉花");
@@ -502,6 +482,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 ResinSelect
}
[StateHandler(StygianState.ResinSelect)]
private async Task<StateHandlerResult> HandleResinSelectState(BvPage page)
{
Logger.LogInformation($"{Name}:选择树脂");
@@ -510,6 +491,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 ContinueOrExit 或 DomainLobby
}
[StateHandler(StygianState.ContinueOrExit)]
private async Task<StateHandlerResult> HandleContinueOrExitState(BvPage page)
{
Logger.LogInformation($"{Name}:处理继续/退出选择");
@@ -540,6 +522,7 @@ public class AutoStygianOnslaughtTask : StateMachineBase<StygianState, BvPage>,
return StateHandlerResult.Success; // 等待转换到 BattleArena 或 MainWorld
}
[UnknownStateHandler]
private async Task<StateHandlerResult> HandleUnknownState(BvPage page)
{
Logger.LogWarning("未知状态,尝试返回主界面");
@@ -1,6 +1,6 @@
{
"language": "CHS",
"version": "56882a11588d5e79a1b6b51739f9fb27e9952fd7",
"version": "cffc7f010f1a4bf4a0bdfb0865d0737d4aec6b7a",
"data": [
{
"sceneId": 3,
@@ -14224,6 +14224,29 @@
9669.12
]
},
{
"id": 2003,
"type": "BlessDomain",
"name": "山风的荆冕",
"country": "蒙德",
"areas": [
"风息山"
],
"position": [
3266.666,
290.28,
47.39246
],
"tranPosition": [
3258.3,
289.17,
47.8
],
"rewards": [
"天之美赐",
"影中沉凝的幻灭"
]
},
{
"id": 2009,
"type": "TeleportWaypoint",
@@ -14318,6 +14341,31 @@
347.94803,
-217.91002
]
},
{
"id": 2053,
"type": "TrounceDomain",
"name": "万有涅槃缚境",
"country": "须弥",
"areas": [
"护世森",
"茸蕈窟"
],
"position": [
221.1095,
270.9658,
2915.052
],
"tranPosition": [
217.3052,
268.16556,
2917.7302
],
"rewards": [
"亵渎的新芽",
"扭曲的枯枝",
"赝作的树脂"
]
}
]
},
@@ -16234,4 +16282,4 @@
]
}
]
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -89,6 +89,28 @@ public static class NewRetry
return false;
}
/// <summary>
/// 重试执行异步 action,直到返回 true 或达到最大重试次数。
/// </summary>
/// <param name="action">判断条件(异步)</param>
/// <param name="ct">取消令牌</param>
/// <param name="retryTimes">最大重试次数</param>
/// <param name="delayMs">每次重试间隔(毫秒)</param>
/// <returns>是否成功</returns>
public static async Task<bool> WaitForAction(Func<Task<bool>> action, CancellationToken ct, int retryTimes = 10, int delayMs = 1000)
{
for (var i = 0; i < retryTimes; i++)
{
await TaskControl.Delay(delayMs, ct);
if (await action())
{
return true;
}
}
return false;
}
/// <summary>
/// 重试直到某个元素出现,可执行键盘或鼠标操作。
/// </summary>
@@ -1,32 +1,28 @@
# StateMachineBase 状态机框架
## 概述
`StateMachineBase<TState, TContext>` 是给游戏自动化任务使用的有限状态机基类。它把 UI 场景识别、场景处理、状态转移、重试和超时兜底放到统一框架里,避免任务里堆一长串 `switch`、`while` 和零散的超时判断。
`StateMachineBase<TState, TContext>` 是一个通用的有限状态机基类,专为游戏自动化场景设计。
推荐写法是:
1. 用枚举定义所有 UI 状态。
2. 用 `[StateDetector]` 标记状态检测方法。
3. 用 `[StateHandler]` 标记状态处理方法,并在节点上声明重试策略。
4. 在一个地方集中注册状态转移图。
5. 调用 `RunStateMachineUntil` 运行到目标状态。
## 核心概念
| 概念 | 说明 |
|------|------|
| **State** | 游戏界面的抽象(如 MainWorld、EventMenu) |
| **Transition** | 状态之间的有向边,定义从一个状态可能到达的下一个状态 |
| **Handler** | 状态处理器,执行当前状态的操作(如点击按钮),返回 `StateHandlerResult` |
| **Detector** | 状态检测器,根据截图判断当前是否处于某个状态 |
| --- | --- |
| `State` | 一个明确的 UI 场景,比如 `MainWorld`、`EventMenu`、`DomainEntrance` |
| `Detector` | 状态检测器,签名为 `bool Method(ImageRegion ra)`,只判断当前截图是否匹配这个状态 |
| `Handler` | 状态处理器,签名为 `Task<StateHandlerResult> Method(TContext context)`,负责在当前状态执行动作 |
| `Transition` | 状态图的有向边,声明某个状态执行成功后允许到达哪些状态 |
| `RetryPolicy` | 节点级兜底策略,可按次数或按时间限制当前状态的重试 |
## StateHandlerResult
`TState` 必须是枚举。建议第一个枚举值是 `Unknown`,因为 `default(TState)` 会被框架当作“未识别到状态”使用。
Handler 必须返回 `StateHandlerResult`,状态机根据返回值决定下一步行为:
| 返回值 | 语义 | 状态机行为 | 使用场景 |
|--------|------|-----------|----------|
| `Success` | 操作成功 | 等待邻接状态转换 | 点击按钮后等待界面切换 |
| `Wait` | 可预期的等待 | 继续循环,重新检测 | 动画播放中、已到达目标状态 |
| `Retry` | 意外失败 | 重试计数+1,超限后异常 | 找不到按钮、OCR 识别失败 |
| `Fail` | 无法恢复 | 立即抛出异常 | 严重错误需要停止 |
## 使用步骤
### 1. 定义状态枚举
## 基本模板
```csharp
public enum MyState
@@ -34,231 +30,316 @@ public enum MyState
Unknown,
MainWorld,
EventMenu,
BattleArena
TargetPage,
}
```
### 2. 继承 StateMachineBase
```csharp
public class MyTask : StateMachineBase<MyState, BvPage>
public class MyTask : StateMachineBase<MyState, BvPage>, ISoloTask
{
protected override ILogger Logger => _logger;
private readonly ILogger<MyTask> _logger;
protected override ILogger Logger => TaskControl.Logger;
public MyTask()
{
RegisterAllStateHandlers();
}
private void RegisterAllStateHandlers()
{
RegisterStateMethodsByAttribute();
RegisterStateTransitions(
(MyState.MainWorld, [MyState.EventMenu]),
(MyState.EventMenu, [MyState.TargetPage])
);
}
public async Task Start(CancellationToken ct)
{
Initialize(ct, MyState.Unknown);
var page = new BvPage(ct);
await RunStateMachineUntil(page, MyState.TargetPage);
}
}
```
### 3. 注册 Handlers
## Detector
Detector 只负责“当前截图是不是这个状态”,不要在里面点击、等待或修改状态。
```csharp
RegisterStateHandlers(
(MyState.MainWorld, HandleMainWorld),
(MyState.EventMenu, HandleEventMenu)
);
[StateDetector(MyState.MainWorld, Order = 10)]
private bool DetectMainWorld(ImageRegion ra)
{
return ra.Find(ElementAssets.Instance.PaimonMenuRo).IsExist();
}
RegisterUnknownStateHandler(HandleUnknown);
[StateDetector(MyState.EventMenu, Order = 20)]
private bool DetectEventMenu(ImageRegion ra)
{
return ra.FindMulti(RecognitionObject.Ocr(125, 142, 113, 28))
.Any(o => o.Text.Contains("活动一览"));
}
```
### 4. 注册 Detectors
`Order` 表示全量检测时的检测顺序,数值越小越先检测。建议把快且稳定的模板匹配放前面,把大范围 OCR 放后面。
```csharp
RegisterStateDetectors(
(MyState.MainWorld, DetectMainWorld),
(MyState.EventMenu, DetectEventMenu),
(MyState.BattleArena, DetectBattleArena)
);
```
状态机每轮只截图一次并复用给多个检测器。若当前状态注册了邻接状态,则只检测邻接状态;若当前状态没有注册转移关系,则回退到全量检测。
### 5. 注册状态转换
## Handler
```csharp
RegisterStateTransitions(
(MyState.MainWorld, [MyState.EventMenu]),
(MyState.EventMenu, [MyState.BattleArena])
);
```
### 6. 实现 Handler
Handler 只负责“在当前状态做一步动作”,动作结果用 `StateHandlerResult` 表达。
```csharp
[StateHandler(MyState.MainWorld)]
private async Task<StateHandlerResult> HandleMainWorld(BvPage page)
{
Simulation.SendInput.SimulateAction(GIActions.OpenTheEventsMenu);
await Delay(500, _ct);
return StateHandlerResult.Success; // 等待转换到 EventMenu
}
private async Task<StateHandlerResult> HandleEventMenu(BvPage page)
{
var button = page.GetByText("开始").FindAll().FirstOrDefault();
if (button == null)
{
return StateHandlerResult.Retry; // 找不到按钮,重试
}
button.Click();
await Delay(300, _ct);
return StateHandlerResult.Success;
}
private Task<StateHandlerResult> HandleBattleArena(BvPage page)
[StateHandler(MyState.EventMenu, RetryTimeout = 30000)]
private async Task<StateHandlerResult> HandleEventMenu(BvPage page)
{
// 已到达目标状态
return Task.FromResult(StateHandlerResult.Wait);
}
var target = page.GetByText("目标活动").FindAll().FirstOrDefault();
if (target == null)
{
return StateHandlerResult.Retry;
}
private async Task<StateHandlerResult> HandleUnknown(BvPage page)
target.Click();
await Delay(300, _ct);
return StateHandlerResult.Success;
}
```
`StateHandlerResult` 语义如下:
| 返回值 | 框架行为 | 典型场景 |
| --- | --- | --- |
| `Success` | 动作完成,框架等待当前状态的邻接状态出现;若转场超时,会占用当前状态的 retry 预算 | 点击按钮、发送交互键后等待页面切换 |
| `Wait` | 不计 retry,直接进入下一轮检测 | 加载中、动画中、当前状态无需动作 |
| `Retry` | 当前状态 retry 次数加一,超限后抛异常 | 按钮没找到、OCR 暂时失败、动作没法确认 |
| `Fail` | 立即抛异常 | 配置错误、关键条件不满足、无法恢复 |
目标状态通常不会执行 Handler。`RunStateMachineUntil` 每轮会先检测当前状态,发现已到达目标状态就直接返回。
## Unknown Handler
未知状态处理器用于兜底恢复,例如回主界面后重新识别。
```csharp
[UnknownStateHandler]
private async Task<StateHandlerResult> HandleUnknownState(BvPage page)
{
await new ReturnMainUiTask().Start(_ct);
return StateHandlerResult.Wait; // 尝试恢复后重新检测
return StateHandlerResult.Wait;
}
```
### 7. 实现 Detector
未知状态处理器最多只能注册一个。它适合做“恢复到已知入口”的动作,不适合吞掉真正的业务错误。
## 状态转移图
状态转移关系必须集中注册,保持流程可读。
```csharp
private bool DetectMainWorld(ImageRegion ra)
{
return ra.Find(MainWorldAssets.Minimap).IsExist();
}
private bool DetectEventMenu(ImageRegion ra)
{
return ra.FindMulti(RecognitionObject.Ocr(100, 50, 200, 50))
.Any(t => t.Text.Contains("活动"));
}
RegisterStateTransitions(
(MyState.MainWorld, [MyState.EventMenu]),
(MyState.EventMenu, [MyState.TargetPage])
);
```
### 8. 运行状态机
状态图是严格的:
- 当前状态有邻接关系时,框架只检测邻接状态。
- 每个注册的状态转移必须至少有一个邻接状态;结束节点不要注册状态转移。
- 邻接状态不能包含自身,注册时会直接抛异常。
- 如果需要在同一页面重试,不要写自环,应该让 Handler 返回 `Retry` 或 `Success` 后转场超时进入 retry。
- `Success` 状态必须有合理的下一跳,否则等待邻接状态会失败并消耗 retry。
候选状态顺序会影响检测优先级。更具体、更不容易误判的状态应放在前面。
## 结束节点
结束节点用 `RunStateMachineUntil` 的目标状态表达,不需要也不应该注册空邻接。
```csharp
public async Task Start(CancellationToken ct)
RegisterStateTransitions(
(MyState.MainWorld, [MyState.EventMenu]),
(MyState.EventMenu, [MyState.TargetPage])
);
await RunStateMachineUntil(page, MyState.TargetPage);
```
上面这个例子里,`TargetPage` 没有出边,所以不注册 `(MyState.TargetPage, [])`。状态机每轮会先检测是否到达目标状态,命中后直接退出,不会执行目标状态的 Handler。
如果一个状态在某个阶段是结束节点,在另一个阶段还要继续流转,也可以注册它的出边。是否结束由本次 `RunStateMachineUntil` 的目标状态决定,不由状态本身永久决定。
## Retry 策略
节点可以在 `[StateHandler]` 上声明 retry 策略:
```csharp
[StateHandler(MyState.EventMenu, RetryTimeout = 30000, RetryInterval = 500)]
private async Task<StateHandlerResult> HandleEventMenu(BvPage page)
{
Initialize(ct, MyState.MainWorld);
using var page = Bv.Page();
await RunStateMachineUntil(page, MyState.BattleArena);
// 状态机退出后,已到达 BattleArena
await ExecuteBattle();
...
}
[StateHandler(MyState.TargetPage, RetryTimes = 10)]
private async Task<StateHandlerResult> HandleTargetPage(BvPage page)
{
...
}
```
## API 参考
| 属性 | 说明 |
| --- | --- |
| `RetryTimes` | 当前状态最多允许多少次 retry |
| `RetryTimeout` | 当前状态最多允许在 retry 窗口内持续多久,单位毫秒 |
| `RetryInterval` | 发生 retry 后下一轮状态机循环的等待时间,单位毫秒 |
| `TransitionTimeout` | Handler 返回 `Success` 后等待邻接状态出现的超时时间,单位毫秒 |
### 核心方法
`RetryTimes` 和 `RetryTimeout` 互斥,不能同时设置。
| 方法 | 说明 |
|------|------|
| `Initialize(ct, initialState)` | 初始化状态机 |
| `RunStateMachineUntil(context, targetStates)` | 运行直到达到目标状态 |
| `RunStateMachineUntil(context, targetState)` | 运行直到达到单个目标状态 |
| `EnsureNextStateTransition(timeout)` | 等待邻接状态转换(供特殊场景使用) |
retry 预算会被两类事件消耗:
### 注册方法
- Handler 返回 `Retry`。
- Handler 返回 `Success`,但等待邻接状态转换超时。
| 方法 | 说明 |
|------|------|
| `RegisterStateHandler(state, handler)` | 注册单个状态处理器 |
| `RegisterStateHandlers(...)` | 批量注册状态处理器 |
| `RegisterUnknownStateHandler(handler)` | 注册未知状态处理器 |
| `RegisterStateDetector(state, detector)` | 注册单个状态检测器 |
| `RegisterStateDetectors(...)` | 批量注册状态检测器 |
| `RegisterStateTransitions(...)` | 注册状态转换关系 |
状态变化后 retry 计数和 retry 计时都会重置。
### 可重写属性
## 什么时候用次数,什么时候用时间
| 属性 | 默认值 | 说明 |
|------|--------|------|
| `DefaultDetectionInterval` | 300ms | 状态检测间隔 |
| `DefaultTransitionTimeout` | 10000ms | 状态转换超时 |
| `DefaultMaxRetries` | 3 | 最大重试次数 |
| `StateMachineLoopInterval` | 200ms | 状态机循环间隔 |
用 `RetryTimes`:
## 状态机循环流程
- Handler 能明确判断本次动作失败。
- 每次 retry 的成本相近。
- 失败次数比耗时更能表达问题。
```
┌─────────────────────────────────────────────────────┐
│ RunStateMachineUntil │
└─────────────────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ RefreshCurrentState │ ◄─────────────┐
│ (检测当前状态) │ │
└──────────────────────┘ │
│ │
▼ │
┌──────────────────────┐ │
│ 是否到达目标状态? │ │
└──────────────────────┘ │
│ │ │
Yes No │
│ │ │
▼ ▼ │
┌────────┐ ┌──────────────────────┐ │
│ 退出 │ │ 执行 Handler │ │
└────────┘ └──────────────────────┘ │
│ │
▼ │
┌─────────────────────────────┐ │
│ Handler 返回值 │ │
└─────────────────────────────┘ │
│ │ │ │ │
┌──────────────┤ │ │ │ │
│ │ │ │ │ │
▼ ▼ ▼ ▼ │ │
┌─────────┐ ┌─────┐ ┌───┐ ┌────┐│ │
│ Success │ │Wait │ │Rty│ │Fail││ │
└─────────┘ └─────┘ └───┘ └────┘│ │
│ │ │ │ │ │
▼ │ │ ▼ │ │
┌───────────────┐ │ │ 抛出 │ │
│EnsureNextState│ │ │ 异常 │ │
│ Transition │ │ │ │ │
└───────────────┘ │ │ │ │
│ │ ▼ │ │
│ │ ┌────────┐ │ │
│ │ │重试计数│ │ │
│ │ │ +1 │ │ │
│ │ └────────┘ │ │
│ │ │ │ │
└──────────────┴────┴────────┴────────────┘
```
用 `RetryTimeout`:
## 性能优化
- Handler 动作是幂等的。
- 没法确认本次动作是否已经触发转场。
- 可能卡在加载、动画、弹窗等中间态,按次数容易误杀。
### 检测器顺序
例如“找不到活动入口”和“交互秘境入口后没法确认是否已经选中”属于同一类问题:动作可重复,但最终只能靠后续状态检测确认。这类节点更适合设置 `RetryTimeout`。
注册检测器时按速度排序(先快后慢):
## 转场超时
1. **模板匹配**(~10ms)- 最快
2. **小范围 OCR**(~50ms)
3. **大范围 OCR**(~100-200ms)- 最慢
`DefaultTransitionTimeout` 表示:Handler 返回 `Success` 后,如果仍然停留在原状态,最多等多久。默认是 3000ms。
### 邻接状态顺序
`DefaultIntermediateTransitionTimeout` 表示:如果界面已经离开原状态,但还没到任何邻接目标,最多允许中间态持续多久。默认是 120000ms。这个设计是为了避免游戏加载、传送、黑屏等中间态被短转场超时误判。
`RegisterStateTransitions` 中候选状态的顺序影响检测优先级,更具体的状态应放在前面:
可以在节点上覆盖转场超时:
```csharp
// 正确:更具体的状态放前面
(TeleportMap, [DomainEntrance, MainWorld])
// 错误:通用状态会被优先检测
(TeleportMap, [MainWorld, DomainEntrance])
[StateHandler(MyState.TeleportMap, TransitionTimeout = 10000)]
private async Task<StateHandlerResult> HandleTeleportMap(BvPage page)
{
...
}
```
## 示例
## Handler 内可读状态
完整示例见 `GameTask/AutoStygianOnslaught/AutoStygianOnslaughtTask.cs`
Handler 内可以读取当前 retry 信息,用于调整动作强度或打印日志:
状态图:
```csharp
if (CurrentStateRetryCount > 3)
{
Logger.LogWarning("当前状态已重试 {Count} 次", CurrentStateRetryCount);
}
```
MainWorld ─► EventMenu ─► StygianOnslaughtPage ─► TeleportMap
│
▼
DomainLobby ◄── DifficultySelect ◄── DomainEntrance ◄─┘
│
▼
BossSelect ─► BattleArena ─► BattleResult ─► DomainLobby
可读属性:
| 属性 | 说明 |
| --- | --- |
| `CurrentState` | 当前状态 |
| `CurrentStateRetryCount` | 当前状态已累计 retry 次数 |
| `CurrentStateRetryLimit` | 当前状态的次数上限,使用时间策略时为 0 |
| `CurrentStateRetryTimeout` | 当前状态的时间上限,使用次数策略时为 null |
| `CurrentStateRetryUsesTimeout` | 当前状态是否使用时间策略 |
| `CurrentStateRetryInterval` | 当前状态 retry 后的循环间隔 |
| `CurrentStateTransitionTimeout` | 当前状态等待邻接状态的转场超时 |
这些属性都是只读保护属性,节点不能直接改框架内部计数。
## 完整示例
自动幽境危战任务是当前状态机的完整示例:
`GameTask/AutoStygianOnslaught/AutoStygianOnslaughtTask.cs`
简化状态图:
```mermaid
flowchart LR
Unknown --> MainWorld
MainWorld --> EventMenu
MainWorld --> StygianOnslaughtPage
EventMenu --> StygianOnslaughtPage
StygianOnslaughtPage --> TeleportMap
StygianOnslaughtPage --> DomainEntrance
TeleportMap --> DomainEntrance
DomainEntrance --> DifficultySelect
DifficultySelect --> DomainLobby
DomainLobby --> BossSelect
DomainLobby --> LeylineFlowerPrompt
BossSelect --> BattleArena
BattleArena --> BattleResultWin
BattleArena --> BattleResultLose
BattleResultWin --> DomainLobby
BattleResultLose --> BossSelect
LeylineFlowerPrompt --> ResinSelect
ResinSelect --> ContinueOrExit
ResinSelect --> DomainLobby
ContinueOrExit --> BattleArena
ContinueOrExit --> MainWorld
```
幽境危战里的两个典型兜底:
```csharp
[StateHandler(StygianState.EventMenu, RetryTimeout = 30000)]
private async Task<StateHandlerResult> HandleEventMenuState(BvPage page)
{
...
}
[StateHandler(StygianState.StygianOnslaughtPage, RetryTimes = 10)]
private async Task<StateHandlerResult> HandleStygianOnslaughtPageState(BvPage page)
{
...
}
```
`EventMenu` 使用时间预算,因为找不到活动入口时无法确认是否已经进入右侧详情页,只能交给后续状态检测兜底。`StygianOnslaughtPage` 使用次数预算,因为找不到“前往挑战”按钮是当前页内的明确失败。
## 常见坑
- 不要把自身放到邻接状态里。需要重复当前页面动作时,使用 `Retry` 或节点 retry 策略。
- 不要在 Detector 里点击或等待。Detector 只做识别。
- 不要让 Handler 自己写无限循环。循环、retry、超时交给状态机。
- 不要把所有状态都塞进邻接状态。邻接表越精确,误判越少。
- `Wait` 不消耗 retry。只在确实可预期等待时使用,否则可能靠 `maxIterations` 兜底才退出。
- `Success` 表示“动作已发出”,不是“已经到达下一页”。下一页确认由状态机的邻接状态检测完成。
- 如果节点动作可重复但无法确认效果,优先考虑 `RetryTimeout`。
- 如果节点失败很明确,优先考虑 `RetryTimes`。
## 迁移旧任务
旧代码如果手动调用 `RegisterStateHandlers` 和 `RegisterStateDetectors`,可以按下面步骤迁移:
1. 保留原来的状态枚举。
2. 在检测方法上加 `[StateDetector(State, Order = n)]`。
3. 在处理方法上加 `[StateHandler(State)]`。
4. 未知状态处理方法加 `[UnknownStateHandler]`。
5. 注册入口改成先调用 `RegisterStateMethodsByAttribute()`。
6. 保留并整理 `RegisterStateTransitions(...)`。
7. 把节点级 retry 策略从集中注册迁到对应 `[StateHandler]` 上。
迁移后,状态的检测逻辑、处理逻辑和节点策略都贴在方法声明处;状态图仍集中维护。
@@ -4,6 +4,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
@@ -17,7 +18,7 @@ using static TaskControl;
public enum StateHandlerResult
{
/// <summary>
/// 成功:操作完成,状态机自动等待邻接状态转换
/// 成功:操作完成,状态机自动等待邻接状态转换;转场超时会占用当前状态的重试次数
/// </summary>
Success,
@@ -42,6 +43,57 @@ public enum StateHandlerResult
/// </summary>
public delegate Task<StateHandlerResult> StateHandlerDelegate<in TContext>(TContext context);
/// <summary>
/// 状态检测器标记。检测器方法签名必须为 bool Method(ImageRegion ra)。
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class StateDetectorAttribute(object state) : Attribute
{
public object State { get; } = state;
/// <summary>
/// 检测顺序,数值越小越先检测。
/// </summary>
public int Order { get; set; }
}
/// <summary>
/// 状态处理器标记。处理器方法签名必须为 Task&lt;StateHandlerResult&gt; Method(TContext context)。
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class StateHandlerAttribute(object state) : Attribute
{
public object State { get; } = state;
/// <summary>
/// 当前状态的重试次数上限,未设置时使用状态机默认值。
/// </summary>
public int RetryTimes { get; set; } = -1;
/// <summary>
/// 当前状态的重试时间上限(毫秒),与 RetryTimes 互斥。
/// </summary>
public int RetryTimeout { get; set; } = -1;
/// <summary>
/// 当前状态触发重试后的下一轮循环间隔(毫秒)。
/// </summary>
public int RetryInterval { get; set; } = -1;
/// <summary>
/// 当前状态 Handler 返回 Success 后等待邻接状态转换的超时时间(毫秒)。
/// </summary>
public int TransitionTimeout { get; set; } = -1;
}
/// <summary>
/// 未知状态处理器标记。处理器方法签名必须为 Task&lt;StateHandlerResult&gt; Method(TContext context)。
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class UnknownStateHandlerAttribute : Attribute
{
}
/// <summary>
/// 有限状态机基类
///
@@ -76,6 +128,36 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
/// </summary>
public TState CurrentState { get; protected set; }
/// <summary>
/// 当前状态已累计的重试次数。首次执行当前状态 Handler 时为 0。
/// </summary>
protected int CurrentStateRetryCount { get; private set; }
/// <summary>
/// 当前状态的重试次数上限。使用时间策略时为 0。
/// </summary>
protected int CurrentStateRetryLimit { get; private set; }
/// <summary>
/// 当前状态的重试超时时间(毫秒)。为 null 时表示当前状态使用次数上限。
/// </summary>
protected int? CurrentStateRetryTimeout { get; private set; }
/// <summary>
/// 当前状态是否使用重试超时策略。
/// </summary>
protected bool CurrentStateRetryUsesTimeout => CurrentStateRetryTimeout.HasValue;
/// <summary>
/// 当前状态触发重试后的下一轮循环间隔(毫秒)。
/// </summary>
protected int CurrentStateRetryInterval { get; private set; }
/// <summary>
/// 当前状态 Handler 返回 Success 后等待邻接状态转换的超时时间(毫秒)。
/// </summary>
protected int CurrentStateTransitionTimeout { get; private set; }
/// <summary>
/// 状态处理器注册表
/// </summary>
@@ -93,6 +175,26 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
/// </summary>
private readonly Dictionary<TState, TState[]> _stateTransitions = new();
/// <summary>
/// 状态重试上限表 - 未注册时使用运行状态机传入的默认重试次数
/// </summary>
private readonly Dictionary<TState, int> _stateRetryLimits = new();
/// <summary>
/// 状态重试超时表 - 注册后与重试次数上限互斥
/// </summary>
private readonly Dictionary<TState, int> _stateRetryTimeouts = new();
/// <summary>
/// 状态重试间隔表 - 未注册时使用状态机循环间隔
/// </summary>
private readonly Dictionary<TState, int> _stateRetryIntervals = new();
/// <summary>
/// 状态转换超时表 - 未注册时使用默认状态转换超时
/// </summary>
private readonly Dictionary<TState, int> _stateTransitionTimeouts = new();
/// <summary>
/// 未知状态处理器
/// </summary>
@@ -106,7 +208,12 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
/// <summary>
/// 默认状态转换超时(毫秒)
/// </summary>
protected virtual int DefaultTransitionTimeout => 10000;
protected virtual int DefaultTransitionTimeout => 3000;
/// <summary>
/// 默认中间态转换超时(毫秒)
/// </summary>
protected virtual int DefaultIntermediateTransitionTimeout => 120000;
/// <summary>
/// 默认最大重试次数
@@ -150,6 +257,156 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
_unknownStateHandler = handler;
}
/// <summary>
/// 扫描当前任务类中带 Attribute 的方法,自动注册状态检测器、处理器和未知状态处理器。
/// </summary>
protected void RegisterStateMethodsByAttribute()
{
var methods = GetType()
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(method => !method.IsSpecialName)
.ToArray();
var detectorStates = new HashSet<TState>();
var detectors = methods
.Select(method => (method, attribute: method.GetCustomAttribute<StateDetectorAttribute>()))
.Where(item => item.attribute != null)
.OrderBy(item => item.attribute!.Order)
.ThenBy(item => item.method.Name, StringComparer.Ordinal);
foreach (var (method, attribute) in detectors)
{
var state = ConvertAttributeState(attribute!.State, method);
if (!detectorStates.Add(state))
{
throw new InvalidOperationException($"状态 {state} 注册了多个检测器");
}
ValidateDetectorMethod(method);
RegisterStateDetector(state, (Func<ImageRegion, bool>)method.CreateDelegate(typeof(Func<ImageRegion, bool>), this));
}
var handlerStates = new HashSet<TState>();
var handlers = methods
.Select(method => (method, attribute: method.GetCustomAttribute<StateHandlerAttribute>()))
.Where(item => item.attribute != null)
.OrderBy(item => item.method.Name, StringComparer.Ordinal);
foreach (var (method, attribute) in handlers)
{
var state = ConvertAttributeState(attribute!.State, method);
if (!handlerStates.Add(state))
{
throw new InvalidOperationException($"状态 {state} 注册了多个处理器");
}
ValidateHandlerMethod(method);
RegisterStateHandler(state, (StateHandlerDelegate<TContext>)method.CreateDelegate(typeof(StateHandlerDelegate<TContext>), this));
RegisterHandlerOptions(state, attribute, method);
}
var unknownHandlers = methods
.Where(method => method.GetCustomAttribute<UnknownStateHandlerAttribute>() != null)
.ToArray();
if (unknownHandlers.Length > 1)
{
throw new InvalidOperationException("未知状态处理器只能注册一个");
}
if (unknownHandlers.Length == 1)
{
var method = unknownHandlers[0];
ValidateHandlerMethod(method);
RegisterUnknownStateHandler((StateHandlerDelegate<TContext>)method.CreateDelegate(typeof(StateHandlerDelegate<TContext>), this));
}
}
private static TState ConvertAttributeState(object state, MethodInfo method)
{
if (state is TState typedState)
{
return typedState;
}
if (state == null)
{
throw new InvalidOperationException($"方法 {method.Name} 的状态不能为空");
}
var stateTypeName = state.GetType().Name;
throw new InvalidOperationException($"方法 {method.Name} 的状态类型 {stateTypeName} 与状态机状态类型 {typeof(TState).Name} 不匹配");
}
private static void ValidateDetectorMethod(MethodInfo method)
{
var parameters = method.GetParameters();
if (method.ReturnType != typeof(bool) ||
parameters.Length != 1 ||
parameters[0].ParameterType != typeof(ImageRegion))
{
throw new InvalidOperationException($"状态检测器 {method.Name} 的签名必须是 bool {method.Name}(ImageRegion ra)");
}
}
private static void ValidateHandlerMethod(MethodInfo method)
{
var parameters = method.GetParameters();
if (method.ReturnType != typeof(Task<StateHandlerResult>) ||
parameters.Length != 1 ||
parameters[0].ParameterType != typeof(TContext))
{
throw new InvalidOperationException($"状态处理器 {method.Name} 的签名必须是 Task<StateHandlerResult> {method.Name}({typeof(TContext).Name} context)");
}
}
private void RegisterHandlerOptions(TState state, StateHandlerAttribute attribute, MethodInfo method)
{
if (attribute.RetryTimes == 0)
{
throw new InvalidOperationException($"状态处理器 {method.Name} 的 RetryTimes 必须大于 0");
}
if (attribute.RetryTimeout == 0)
{
throw new InvalidOperationException($"状态处理器 {method.Name} 的 RetryTimeout 必须大于 0");
}
if (attribute.RetryTimes > 0 && attribute.RetryTimeout > 0)
{
throw new InvalidOperationException($"状态处理器 {method.Name} 不能同时设置 RetryTimes 和 RetryTimeout");
}
if (attribute.RetryTimes > 0)
{
RegisterStateRetryLimit(state, attribute.RetryTimes);
}
if (attribute.RetryTimeout > 0)
{
RegisterStateRetryTimeout(state, attribute.RetryTimeout);
}
if (attribute.RetryInterval == 0)
{
throw new InvalidOperationException($"状态处理器 {method.Name} 的 RetryInterval 必须大于 0");
}
if (attribute.RetryInterval > 0)
{
RegisterStateRetryInterval(state, attribute.RetryInterval);
}
if (attribute.TransitionTimeout == 0)
{
throw new InvalidOperationException($"状态处理器 {method.Name} 的 TransitionTimeout 必须大于 0");
}
if (attribute.TransitionTimeout > 0)
{
RegisterStateTransitionTimeout(state, attribute.TransitionTimeout);
}
}
#endregion
#region 状态转换注册【推荐 - 有限状态机核心】
@@ -167,6 +424,7 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
/// <param name="toStates">可能的目标状态数组(邻接状态)</param>
protected void RegisterStateTransition(TState fromState, params TState[] toStates)
{
ValidateStateTransition(fromState, toStates);
_stateTransitions[fromState] = toStates;
}
@@ -177,7 +435,20 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
{
foreach (var (from, to) in transitions)
{
_stateTransitions[from] = to;
RegisterStateTransition(from, to);
}
}
private static void ValidateStateTransition(TState fromState, TState[] toStates)
{
if (toStates == null || toStates.Length == 0)
{
throw new InvalidOperationException($"状态 {fromState} 必须至少注册一个邻接状态;如果这是结束节点,请不要注册状态转移");
}
if (toStates.Any(state => EqualityComparer<TState>.Default.Equals(state, fromState)))
{
throw new InvalidOperationException($"状态 {fromState} 的邻接状态不能包含自身");
}
}
@@ -192,6 +463,141 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
#endregion
#region 状态重试上限注册
/// <summary>
/// 注册指定状态的重试上限,用于覆盖状态机运行时传入的默认重试次数
/// </summary>
protected void RegisterStateRetryLimit(TState state, int maxRetries)
{
if (maxRetries <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maxRetries), "状态重试上限必须大于 0");
}
_stateRetryLimits[state] = maxRetries;
_stateRetryTimeouts.Remove(state);
}
/// <summary>
/// 批量注册指定状态的重试上限
/// </summary>
protected void RegisterStateRetryLimits(params (TState state, int maxRetries)[] retryLimits)
{
foreach (var (state, maxRetries) in retryLimits)
{
RegisterStateRetryLimit(state, maxRetries);
}
}
private int GetMaxRetriesForState(TState state, int defaultMaxRetries)
{
return _stateRetryLimits.TryGetValue(state, out var maxRetries) ? maxRetries : defaultMaxRetries;
}
/// <summary>
/// 注册指定状态的重试超时时间,用于替代次数上限。
/// </summary>
protected void RegisterStateRetryTimeout(TState state, int timeoutMs)
{
if (timeoutMs <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeoutMs), "状态重试超时时间必须大于 0");
}
_stateRetryTimeouts[state] = timeoutMs;
_stateRetryLimits.Remove(state);
}
/// <summary>
/// 批量注册指定状态的重试超时时间
/// </summary>
protected void RegisterStateRetryTimeouts(params (TState state, int timeoutMs)[] retryTimeouts)
{
foreach (var (state, timeoutMs) in retryTimeouts)
{
RegisterStateRetryTimeout(state, timeoutMs);
}
}
/// <summary>
/// 注册指定状态触发重试后的下一轮循环间隔,未注册时使用 StateMachineLoopInterval。
/// </summary>
protected void RegisterStateRetryInterval(TState state, int intervalMs)
{
if (intervalMs <= 0)
{
throw new ArgumentOutOfRangeException(nameof(intervalMs), "状态重试间隔必须大于 0");
}
_stateRetryIntervals[state] = intervalMs;
}
/// <summary>
/// 注册指定状态 Handler 返回 Success 后等待邻接状态转换的超时时间。
/// </summary>
protected void RegisterStateTransitionTimeout(TState state, int timeoutMs)
{
if (timeoutMs <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeoutMs), "状态转换超时时间必须大于 0");
}
_stateTransitionTimeouts[state] = timeoutMs;
}
private (bool useTimeout, int value) GetRetryPolicyForState(TState state, int defaultMaxRetries)
{
if (_stateRetryTimeouts.TryGetValue(state, out var timeoutMs))
{
return (true, timeoutMs);
}
return (false, GetMaxRetriesForState(state, defaultMaxRetries));
}
private int GetRetryIntervalForState(TState state)
{
return _stateRetryIntervals.TryGetValue(state, out var intervalMs) ? intervalMs : StateMachineLoopInterval;
}
private int GetTransitionTimeoutForState(TState state)
{
return _stateTransitionTimeouts.TryGetValue(state, out var timeoutMs) ? timeoutMs : DefaultTransitionTimeout;
}
private void RecordStateRetry(string reason, (bool useTimeout, int value) retryPolicy, Stopwatch stateRetryStopwatch)
{
CurrentStateRetryCount++;
if (retryPolicy.useTimeout)
{
var elapsedMilliseconds = stateRetryStopwatch.ElapsedMilliseconds;
if (elapsedMilliseconds >= retryPolicy.value)
{
Logger.LogError("状态 {State} {Reason},重试超时达到上限 {Max} ms,转为失败",
CurrentState, reason, retryPolicy.value);
throw new InvalidOperationException($"状态 {CurrentState} 重试超时达到上限 {retryPolicy.value} ms");
}
Logger.LogWarning("状态 {State} {Reason},将在重试超时窗口内继续重试(第 {Count} 次,已用 {Elapsed}/{Max} ms)",
CurrentState, reason, CurrentStateRetryCount, elapsedMilliseconds, retryPolicy.value);
return;
}
if (CurrentStateRetryCount >= retryPolicy.value)
{
Logger.LogError("状态 {State} {Reason},重试次数达到上限 {Max},转为失败",
CurrentState, reason, retryPolicy.value);
throw new InvalidOperationException($"状态 {CurrentState} 重试次数达到上限 {retryPolicy.value}");
}
Logger.LogWarning("状态 {State} {Reason},将重试当前状态(第 {Count}/{Max} 次)",
CurrentState, reason, CurrentStateRetryCount, retryPolicy.value);
}
#endregion
#region 状态机运行
/// <summary>
@@ -210,14 +616,20 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
/// <param name="context">上下文对象</param>
/// <param name="targetStates">目标状态(到达任一即停止)</param>
/// <param name="maxIterations">最大迭代次数(防止无限循环)</param>
/// <param name="maxRetries">单个状态最大重试次数(Retry 返回值触发)</param>
/// <param name="maxRetries">默认单个状态最大重试次数,可通过 RegisterStateRetryLimit 覆盖指定状态</param>
/// <exception cref="InvalidOperationException">Handler 返回 Fail、重试超限、转场超时超限或达到最大迭代次数时抛出</exception>
protected async Task RunStateMachineUntil(TContext context, TState[] targetStates, int maxIterations = 1000, int maxRetries = 5)
{
Logger.LogInformation("========== 状态机启动,目标状态:{Targets} ==========",
string.Join(", ", targetStates));
int retryCount = 0;
CurrentStateRetryCount = 0;
CurrentStateRetryLimit = maxRetries;
CurrentStateRetryTimeout = null;
CurrentStateRetryInterval = StateMachineLoopInterval;
CurrentStateTransitionTimeout = DefaultTransitionTimeout;
TState lastRetryState = default;
var stateRetryStopwatch = Stopwatch.StartNew();
for (int iteration = 0; iteration < maxIterations; iteration++)
{
@@ -229,8 +641,9 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
// 状态变化时重置重试计数
if (!EqualityComparer<TState>.Default.Equals(CurrentState, lastRetryState))
{
retryCount = 0;
CurrentStateRetryCount = 0;
lastRetryState = CurrentState;
stateRetryStopwatch.Restart();
}
// 检查是否到达目标状态
@@ -241,6 +654,14 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
}
Logger.LogDebug("状态机迭代 {Iteration},当前状态:{State}", iteration, CurrentState);
var retryPolicy = GetRetryPolicyForState(CurrentState, maxRetries);
var retryInterval = GetRetryIntervalForState(CurrentState);
var transitionTimeout = GetTransitionTimeoutForState(CurrentState);
CurrentStateRetryLimit = retryPolicy.useTimeout ? 0 : retryPolicy.value;
CurrentStateRetryTimeout = retryPolicy.useTimeout ? retryPolicy.value : null;
CurrentStateRetryInterval = retryInterval;
CurrentStateTransitionTimeout = transitionTimeout;
var nextLoopInterval = StateMachineLoopInterval;
// 执行状态处理器
if (_stateHandlers.TryGetValue(CurrentState, out var handler))
@@ -250,12 +671,17 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
switch (result)
{
case StateHandlerResult.Success:
// 成功:等待邻接状态转换
retryCount = 0; // 重置重试计数
var nextState = await EnsureNextStateTransition();
// 成功:等待邻接状态转换;转场超时视为当前状态的一次重试
var nextState = await EnsureNextStateTransition(transitionTimeout);
if (EqualityComparer<TState>.Default.Equals(nextState, default))
{
Logger.LogWarning("等待邻接状态转换超时");
RecordStateRetry("等待邻接状态转换超时", retryPolicy, stateRetryStopwatch);
nextLoopInterval = retryInterval;
}
else
{
CurrentStateRetryCount = 0; // 成功转换后重置重试计数
stateRetryStopwatch.Restart();
}
break;
@@ -266,13 +692,8 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
case StateHandlerResult.Retry:
// 意外失败重试:检查重试次数
retryCount++;
if (retryCount >= maxRetries)
{
Logger.LogError("状态 {State} 重试次数达到上限 {Max},转为失败", CurrentState, maxRetries);
throw new InvalidOperationException($"状态 {CurrentState} 重试次数达到上限 {maxRetries}");
}
Logger.LogWarning("Handler 返回 Retry,将重试当前状态(第 {Count}/{Max} 次)", retryCount, maxRetries);
RecordStateRetry("Handler 返回 Retry", retryPolicy, stateRetryStopwatch);
nextLoopInterval = retryInterval;
break;
case StateHandlerResult.Fail:
@@ -294,10 +715,12 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
Logger.LogWarning("状态 {State} 无注册处理器,跳过", CurrentState);
}
await Delay(StateMachineLoopInterval, _ct);
await Delay(nextLoopInterval, _ct);
}
Logger.LogWarning("状态机达到最大迭代次数 {Max},强制退出", maxIterations);
Logger.LogError("状态机达到最大迭代次数 {Max},目标状态:{Targets},当前状态:{State}",
maxIterations, string.Join(", ", targetStates), CurrentState);
throw new InvalidOperationException($"状态机达到最大迭代次数 {maxIterations},未到达目标状态:{string.Join(", ", targetStates)}");
}
/// <summary>
@@ -405,38 +828,6 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
}
}
/// <summary>
/// 等待状态转换(内部方法)
/// 执行动作后,等待目标状态出现
/// </summary>
/// <param name="expectedState">期望的目标状态</param>
/// <param name="timeoutMs">超时时间(毫秒)</param>
/// <returns>是否成功转换到目标状态</returns>
private async Task<bool> EnsureStateTransition(TState expectedState, int? timeoutMs = null)
{
var timeout = timeoutMs ?? DefaultTransitionTimeout;
var stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < timeout)
{
_ct.ThrowIfCancellationRequested();
// 只检测期望的状态
var currentState = DetectStateAmong([expectedState]);
if (EqualityComparer<TState>.Default.Equals(currentState, expectedState))
{
CurrentState = currentState;
Logger.LogDebug("状态转换成功:{State}", expectedState);
return true;
}
await Delay(DefaultDetectionInterval, _ct);
}
Logger.LogWarning("状态转换超时,期望:{Expected},当前:{Current}", expectedState, DetectCurrentState());
return false;
}
/// <summary>
/// 等待任一目标状态出现(内部方法)
/// </summary>
@@ -446,26 +837,58 @@ public abstract class StateMachineBase<TState, TContext> where TState : struct,
private async Task<TState> EnsureAnyStateTransition(TState[] expectedStates, int? timeoutMs = null)
{
var timeout = timeoutMs ?? DefaultTransitionTimeout;
var stopwatch = Stopwatch.StartNew();
var sourceState = CurrentState;
var transitionTargetStates = expectedStates
.Where(state => !EqualityComparer<TState>.Default.Equals(state, sourceState))
.ToArray();
while (stopwatch.ElapsedMilliseconds < timeout)
if (transitionTargetStates.Length == 0)
{
Logger.LogWarning("状态 {State} 没有可等待的非自身邻接状态", sourceState);
return default;
}
var sourceVisibleStopwatch = Stopwatch.StartNew();
var intermediateStopwatch = Stopwatch.StartNew();
var intermediateTimeout = Math.Max(timeout, DefaultIntermediateTransitionTimeout);
while (sourceVisibleStopwatch.ElapsedMilliseconds < timeout &&
intermediateStopwatch.ElapsedMilliseconds < intermediateTimeout)
{
_ct.ThrowIfCancellationRequested();
// 只检测期望的状态
var currentState = DetectStateAmong(expectedStates);
if (expectedStates.Contains(currentState))
var currentState = DetectStateAmong(transitionTargetStates);
if (transitionTargetStates.Contains(currentState))
{
CurrentState = currentState;
Logger.LogDebug("状态转换成功:{State}", currentState);
return currentState;
}
var detectedState = DetectCurrentState();
if (EqualityComparer<TState>.Default.Equals(detectedState, sourceState))
{
intermediateStopwatch.Restart();
}
else
{
sourceVisibleStopwatch.Restart();
}
await Delay(DefaultDetectionInterval, _ct);
}
Logger.LogWarning("状态转换超时,期望任一:{Expected},当前:{Current}",
string.Join(",", expectedStates), DetectCurrentState());
if (sourceVisibleStopwatch.ElapsedMilliseconds >= timeout)
{
Logger.LogWarning("状态转换超时,期望任一:{Expected},当前仍停留在原状态:{Current}",
string.Join(",", transitionTargetStates), sourceState);
}
else
{
Logger.LogWarning("状态转换超时,期望任一:{Expected},中间态等待超过 {Timeout} ms,当前:{Current}",
string.Join(",", transitionTargetStates), intermediateTimeout, DetectCurrentState());
}
return default;
}
@@ -190,6 +190,7 @@ public class TaskRunner
TaskTriggerDispatcher.Instance().SetTriggers(GameTaskManager.LoadInitialTriggers());
VisionContext.Instance().DrawContent.ClearAll();
HtmlMaskWindow.CloseAll();
}
}
@@ -12,6 +12,31 @@ public static class DomainCascadingItems
public static IReadOnlyList<ICascadingItem> Items =>
_items ??= BuildItems();
private static readonly Dictionary<string, (int Order, string Text)> TalentRewardDisplays = new()
{
["「自由」的哲学"] = (1, "「自由」(1/4)"),
["「抗争」的哲学"] = (2, "「抗争」(2/5)"),
["「诗文」的哲学"] = (3, "「诗文」(3/6)"),
["「繁荣」的哲学"] = (1, "「繁荣」(1/4)"),
["「勤劳」的哲学"] = (2, "「勤劳」(2/5)"),
["「黄金」的哲学"] = (3, "「黄金」(3/6)"),
["「浮世」的哲学"] = (1, "「浮世」(1/4)"),
["「风雅」的哲学"] = (2, "「风雅」(2/5)"),
["「天光」的哲学"] = (3, "「天光」(3/6)"),
["「诤言」的哲学"] = (1, "「诤言」(1/4)"),
["「巧思」的哲学"] = (2, "「巧思」(2/5)"),
["「笃行」的哲学"] = (3, "「笃行」(3/6)"),
["「公平」的哲学"] = (1, "「公平」(1/4)"),
["「正义」的哲学"] = (2, "「正义」(2/5)"),
["「秩序」的哲学"] = (3, "「秩序」(3/6)"),
["「角逐」的哲学"] = (1, "「角逐」(1/4)"),
["「焚燔」的哲学"] = (2, "「焚燔」(2/5)"),
["「纷争」的哲学"] = (3, "「纷争」(3/6)"),
["「月光」的哲学"] = (1, "「月光」(1/4)"),
["「乐园」的哲学"] = (2, "「乐园」(2/5)"),
["「浪迹」的哲学"] = (3, "「浪迹」(3/6)")
};
private static IReadOnlyList<ICascadingItem> BuildItems()
{
return MapLazyAssets.Instance.CountryToDomains.Keys
@@ -22,11 +47,22 @@ public static class DomainCascadingItems
.AsEnumerable()
.Reverse()
.Select(d => (ICascadingItem)new CascadingItem(
d.Name! + " | " + string.Join(" ", d.Rewards))
d.Name! + " | " + FormatRewards(d.Rewards))
{
Tag = d.Name
})
))
.ToList();
}
private static string FormatRewards(IEnumerable<string> rewards)
{
return string.Join(" ", rewards
.Select((reward, index) => TalentRewardDisplays.TryGetValue(reward, out var display)
? (display.Order, Index: index, display.Text)
: (Order: int.MaxValue, Index: index, Text: reward))
.OrderBy(reward => reward.Order)
.ThenBy(reward => reward.Index)
.Select(reward => reward.Text));
}
}
@@ -1,27 +1,40 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
namespace BetterGenshinImpact.Service.Notification.Converter;
public class ImageToBase64Converter : JsonConverter<Image>
public class ImageToBase64Converter : JsonConverter<Image<Rgb24>?>
{
public override Image? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override Image<Rgb24>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.GetString() is { } base64)
if (reader.TokenType == JsonTokenType.Null)
{
return Image.FromStream(new MemoryStream(Convert.FromBase64String(base64)));
return null;
}
if (reader.GetString() is { Length: > 0 } base64)
{
return Image.Load<Rgb24>(Convert.FromBase64String(base64));
}
return null;
}
public override void Write(Utf8JsonWriter writer, Image value, JsonSerializerOptions options)
public override void Write(Utf8JsonWriter writer, Image<Rgb24>? value, JsonSerializerOptions options)
{
if (value == null)
{
writer.WriteNullValue();
return;
}
using var ms = new MemoryStream();
value.Save(ms, ImageFormat.Jpeg);
value.Save(ms, new JpegEncoder());
writer.WriteBase64StringValue(ms.ToArray());
}
}
@@ -1,13 +1,17 @@
using BetterGenshinImpact.Service.Notifier.Exception;
using BetterGenshinImpact.Service.Notifier.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model;
using System.Collections.Generic;
using BetterGenshinImpact.Service.Notification;
using System;
using BetterGenshinImpact.Service.Notification.Model;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
namespace BetterGenshinImpact.Service.Notifier;
@@ -21,7 +25,7 @@ public class WebhookNotifier : INotifier
private string SendTo { get; set; }
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
@@ -40,7 +44,7 @@ public class WebhookNotifier : INotifier
{
throw new NotifierException("Webhook 地址为空");
}
try
{
var response = await _httpClient.PostAsync(Endpoint, TransformData(content));
@@ -63,14 +67,14 @@ public class WebhookNotifier : INotifier
private StringContent TransformData(BaseNotificationData notificationData)
{
// 使用 SendTo 属性来设置 send_to 字段,并将 notification_data 的内容合并到外层字典
var dataToSend = new Dictionary<string, object>
var dataToSend = new Dictionary<string, object?>
{
{ "send_to", SendTo },
{ "event", notificationData.Event },
{ "result", notificationData.Result },
{ "timestamp", notificationData.Timestamp },
// 修改截图数据的处理方式,先转换为字节数组再进行Base64编码
{ "screenshot", notificationData.Screenshot != null ? ConvertToBase64(notificationData.Screenshot) : null },
// 修改截图数据的处理方式,先转换为字节数组再进行 Base64 编码
{ "screenshot", ConvertToBase64(notificationData.Screenshot) },
{ "message", notificationData.Message },
{ "data", notificationData.Data }
};
@@ -79,16 +83,17 @@ public class WebhookNotifier : INotifier
return new StringContent(serializedData, Encoding.UTF8, "application/json");
}
// 添加新的辅助方法,用于将图像转换为Base64字符串
private string ConvertToBase64(object imageObj)
// 添加新的辅助方法,用于将图像转换为 Base64 字符串
private static string? ConvertToBase64(Image<Rgb24>? imageObj)
{
if (imageObj is byte[] byteArray)
if (imageObj == null)
{
return Convert.ToBase64String(byteArray);
return null;
}
// 如果是ImageSharp图像对象,需要先转换为字节数组
// 这里假设使用PNG格式编码
return null; // 或者根据实际需要处理其他图像类型
using var ms = new MemoryStream();
imageObj.Save(ms, new JpegEncoder());
return Convert.ToBase64String(ms.ToArray());
}
}
}
@@ -0,0 +1,156 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.View.Behavior;
public static class DomainCascadingComboBoxBehavior
{
private static readonly DependencyProperty LastCommittedItemProperty =
DependencyProperty.RegisterAttached(
"LastCommittedItem",
typeof(ICascadingItem),
typeof(DomainCascadingComboBoxBehavior),
new PropertyMetadata(null));
private static readonly DependencyProperty LastCommittedTextProperty =
DependencyProperty.RegisterAttached(
"LastCommittedText",
typeof(string),
typeof(DomainCascadingComboBoxBehavior),
new PropertyMetadata(string.Empty));
public static readonly DependencyProperty UseFullLabelsWhenOpenProperty =
DependencyProperty.RegisterAttached(
"UseFullLabelsWhenOpen",
typeof(bool),
typeof(DomainCascadingComboBoxBehavior),
new PropertyMetadata(false, OnUseFullLabelsWhenOpenChanged));
public static bool GetUseFullLabelsWhenOpen(DependencyObject obj)
{
return (bool)obj.GetValue(UseFullLabelsWhenOpenProperty);
}
public static void SetUseFullLabelsWhenOpen(DependencyObject obj, bool value)
{
obj.SetValue(UseFullLabelsWhenOpenProperty, value);
}
private static void OnUseFullLabelsWhenOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not CascadingComboBox comboBox)
return;
comboBox.DropDownClosed -= OnDropDownClosed;
comboBox.DropDownOpened -= OnDropDownOpened;
comboBox.SelectionChanged -= OnSelectionChanged;
comboBox.Loaded -= OnLoaded;
if (e.NewValue is true)
{
comboBox.DropDownClosed += OnDropDownClosed;
comboBox.DropDownOpened += OnDropDownOpened;
comboBox.SelectionChanged += OnSelectionChanged;
comboBox.Loaded += OnLoaded;
comboBox.Dispatcher.BeginInvoke(() => UpdateCommittedSelection(comboBox, restoreInvalidSelection: false));
}
}
private static void OnLoaded(object sender, RoutedEventArgs e)
{
if (sender is CascadingComboBox comboBox)
comboBox.Dispatcher.BeginInvoke(() => UpdateCommittedSelection(comboBox, restoreInvalidSelection: false));
}
private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is CascadingComboBox comboBox)
comboBox.Dispatcher.BeginInvoke(() => UpdateCommittedSelection(comboBox, restoreInvalidSelection: false));
}
private static void OnDropDownOpened(object? sender, System.EventArgs e)
{
if (sender is CascadingComboBox comboBox)
comboBox.Dispatcher.BeginInvoke(() => UpdateCommittedSelection(comboBox, restoreInvalidSelection: false));
}
private static void OnDropDownClosed(object? sender, System.EventArgs e)
{
if (sender is CascadingComboBox comboBox)
comboBox.Dispatcher.BeginInvoke(() => UpdateCommittedSelection(comboBox, restoreInvalidSelection: true));
}
private static void UpdateCommittedSelection(CascadingComboBox comboBox, bool restoreInvalidSelection)
{
if (IsSelectableDomain(comboBox.SelectedCascadingItem))
CommitSelectedItem(comboBox, comboBox.SelectedCascadingItem);
else if (GetLastCommittedItem(comboBox) == null)
comboBox.SetValue(LastCommittedTextProperty, comboBox.PlaceholderText);
else if (restoreInvalidSelection && GetLastCommittedItem(comboBox) is { } lastCommittedItem)
comboBox.SetCurrentValue(CascadingComboBox.SelectedCascadingItemProperty, lastCommittedItem);
ApplySelectedPreviewBinding(comboBox);
}
private static bool IsSelectableDomain(ICascadingItem? item)
{
return item?.Tag is string name && !string.IsNullOrWhiteSpace(name);
}
private static ICascadingItem? GetLastCommittedItem(DependencyObject obj)
{
return (ICascadingItem?)obj.GetValue(LastCommittedItemProperty);
}
private static void CommitSelectedItem(CascadingComboBox comboBox, ICascadingItem? item)
{
if (!IsSelectableDomain(item))
return;
comboBox.SetValue(LastCommittedItemProperty, item);
comboBox.SetValue(LastCommittedTextProperty, item!.Tag as string ?? string.Empty);
}
private static void ApplySelectedPreviewBinding(CascadingComboBox comboBox)
{
comboBox.ApplyTemplate();
BindPreviewText(comboBox, "PART_SelectedText");
BindPreviewText(comboBox, "PART_SelectedValueText");
}
private static void BindPreviewText(CascadingComboBox comboBox, string partName)
{
if (FindVisualChild<TextBlock>(comboBox, partName) is not { } selectedText)
return;
BindingOperations.SetBinding(selectedText, TextBlock.TextProperty, new Binding("SelectedCascadingItem.Tag")
{
Source = comboBox,
Mode = BindingMode.OneWay,
Path = new PropertyPath("(0)", LastCommittedTextProperty),
TargetNullValue = comboBox.PlaceholderText,
FallbackValue = comboBox.PlaceholderText
});
}
private static T? FindVisualChild<T>(DependencyObject parent, string name) where T : FrameworkElement
{
var childCount = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < childCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
if (child is T element && element.Name == name)
return element;
var result = FindVisualChild<T>(child, name);
if (result != null)
return result;
}
return null;
}
}
@@ -26,8 +26,9 @@ public class DomainNameToCascadingItemConverter : IValueConverter
public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is ICascadingItem item)
return item.Tag as string;
return null;
if (value is ICascadingItem { Tag: string name } && !string.IsNullOrWhiteSpace(name))
return name;
return Binding.DoNothing;
}
}
+5 -3
View File
@@ -9,7 +9,9 @@
WindowStartupLocation="Manual"
ShowInTaskbar="False"
Topmost="True">
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
<Border x:Name="ClickThroughBorder" Background="Transparent">
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
</Border>
</Window>
+148 -13
View File
@@ -17,7 +17,7 @@ using Microsoft.Web.WebView2.Core;
namespace BetterGenshinImpact.View;
/// <summary>
/// HTML遮罩窗口 - 仅用于显示,不可交互(点击穿透)
/// HTML遮罩窗口
/// </summary>
public partial class HtmlMaskWindow : Window
{
@@ -29,12 +29,21 @@ public partial class HtmlMaskWindow : Window
private readonly string _webView2DataPath;
private readonly string _pageUrl;
private bool _navigationCompleted;
private bool _styleCaptured;
private int _originalStyle;
private volatile bool _isClickThrough = true;
private readonly System.Windows.Media.SolidColorBrush _backgroundBrush = new();
/// <summary>
/// 窗口唯一标识
/// </summary>
public string MaskId => _id;
/// <summary>
/// 当前是否处于点击穿透模式
/// </summary>
public bool IsClickThrough => _isClickThrough;
private HtmlMaskWindow(string url, string? id, string workDir)
{
_id = id ?? Guid.NewGuid().ToString("N");
@@ -42,6 +51,7 @@ public partial class HtmlMaskWindow : Window
_webView2DataPath = Path.Combine(workDir, "WebView2Data");
_pageUrl = url;
InitializeComponent();
ClickThroughBorder.Background = _backgroundBrush;
Loaded += OnLoaded;
InitializeAsync(url);
}
@@ -156,6 +166,47 @@ public partial class HtmlMaskWindow : Window
return _windows.ContainsKey(id);
}
/// <summary>
/// 获取窗口实例,不存在则抛出异常
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>窗口实例</returns>
private static HtmlMaskWindow GetWindowOrThrow(string windowId)
{
if (_windows.TryGetValue(windowId, out var window))
return window;
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
}
/// <summary>
/// 设置指定窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public static void SetClickThrough(string windowId, bool enabled)
{
GetWindowOrThrow(windowId).SetClickThroughMode(enabled);
}
/// <summary>
/// 获取指定窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>点击穿透状态</returns>
public static bool GetClickThrough(string windowId)
{
return GetWindowOrThrow(windowId).IsClickThrough;
}
/// <summary>
/// 原子切换指定窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public static void ToggleClickThrough(string windowId)
{
GetWindowOrThrow(windowId).ToggleClickThroughCore();
}
/// <summary>
/// 通知窗口刷新待推送的消息
/// </summary>
@@ -164,13 +215,24 @@ public partial class HtmlMaskWindow : Window
if (!_windows.TryGetValue(windowId, out var window)) return;
window.Dispatcher.BeginInvoke(() =>
{
// 页面还没加载完,消息留在队列中由 NavigationCompleted 统一推送
if (!window._navigationCompleted) return;
if (window.WebView.CoreWebView2 == null) return;
HtmlMask.FlushPendingMessages(windowId, json =>
try
{
window.WebView.CoreWebView2.PostWebMessageAsString(json);
});
// 页面还没加载完,消息留在队列中由 NavigationCompleted 统一推送
if (!window._navigationCompleted) return;
if (window.WebView.CoreWebView2 == null) return;
HtmlMask.FlushPendingMessages(windowId, json =>
{
window.WebView.CoreWebView2.PostWebMessageAsString(json);
});
}
catch (ObjectDisposedException)
{
// WebView 已被释放,忽略此消息推送
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩窗口消息推送异常");
}
});
}
@@ -178,7 +240,7 @@ public partial class HtmlMaskWindow : Window
private void OnLoaded(object sender, RoutedEventArgs e)
{
SetClickThrough();
SetClickThrough(true);
UpdatePosition();
}
@@ -387,14 +449,87 @@ public partial class HtmlMaskWindow : Window
}
/// <summary>
/// 设置点击穿透
/// 设置点击穿透模式
/// </summary>
private void SetClickThrough()
/// <param name="enabled">true=点击穿透,false=可交互</param>
private void SetClickThrough(bool enabled)
{
var hwnd = new WindowInteropHelper(this).Handle;
var style = (int)GetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE);
User32.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE,
(IntPtr)(style | (int)User32.WindowStylesEx.WS_EX_TRANSPARENT));
if (hwnd == IntPtr.Zero) return;
if (!_styleCaptured)
{
_originalStyle = (int)GetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE);
_styleCaptured = true;
}
int newStyle = enabled
? (_originalStyle | (int)User32.WindowStylesEx.WS_EX_TRANSPARENT | (int)User32.WindowStylesEx.WS_EX_LAYERED)
: _originalStyle;
User32.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE, (IntPtr)newStyle);
_isClickThrough = enabled;
SetBackgroundOpacity(!enabled);
if (!enabled)
{
// 禁用穿透:激活遮罩窗口,确保获得键盘和鼠标焦点
try
{
User32.SetForegroundWindow(hwnd);
User32.BringWindowToTop(hwnd);
Dispatcher.Invoke(() => Activate());
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩窗口激活失败");
}
}
else
{
// 开启穿透:将焦点还给游戏窗口
try
{
var gameHandle = TaskContext.Instance().GameHandle;
if (gameHandle != IntPtr.Zero)
{
SystemControl.FocusWindow(gameHandle);
}
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩恢复游戏焦点失败");
}
}
}
/// <summary>
/// 设置背景透明度
/// </summary>
/// <param name="isInteractive">是否处于交互模式</param>
private void SetBackgroundOpacity(bool isInteractive)
{
_backgroundBrush.Color = isInteractive
? System.Windows.Media.Color.FromArgb(1, 0, 0, 0)
: System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
}
/// <summary>
/// 设置点击穿透模式
/// </summary>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThroughMode(bool enabled)
{
Dispatcher.Invoke(() => SetClickThrough(enabled));
}
/// <summary>
/// 切换点击穿透模式
/// </summary>
private void ToggleClickThroughCore()
{
Dispatcher.Invoke(() => SetClickThrough(!_isClickThrough));
}
/// <summary>
+1 -1
View File
@@ -336,7 +336,7 @@ public partial class MaskWindow : Window
private void LogTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
if (LogTextBox.Document.Blocks.FirstBlock is Paragraph p && p.Inlines.Count > 1000)
if (LogTextBox.Document.Blocks.FirstBlock is Paragraph p && p.Inlines.Count > 200)
{
(p.Inlines as System.Collections.IList).RemoveAt(0);
}
@@ -5,6 +5,7 @@
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:dd="urn:gong-wpf-dragdrop"
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
xmlns:helpers="clr-namespace:BetterGenshinImpact.Helpers"
xmlns:local="clr-namespace:BetterGenshinImpact.View.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
@@ -21,7 +22,7 @@
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<b:Interaction.Triggers>
<b:EventTrigger EventName="Loaded">
<b:InvokeCommandAction Command="{Binding LoadedCommand}" CommandParameter="{Binding}" />
@@ -463,7 +464,7 @@
MaxWidth="800"
Margin="20,0,36,0"
Text="{Binding SelectedConfig.PartyName, Mode=TwoWay}"
PlaceholderText="填写队伍名称"
PlaceholderText="留空则不切换队伍"
TextAlignment="Center"
TextWrapping="Wrap" />
</Grid>
@@ -499,6 +500,7 @@
Width="100"
HorizontalAlignment="Left"
Margin="10,0,10,0"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.DomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ui:TextBlock Grid.Row="0"
@@ -578,240 +580,325 @@
Text="周期始于凌晨 4:00 ,如周一 4:00 至周二 3:59 刷取周一秘境"
TextWrapping="Wrap">
</ui:TextBlock>
<Grid Margin="16">
<Grid Margin="20,16,20,4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="日期"
TextAlignment="Center" />
<ui:TextBlock Grid.Column="1"
Margin="8,0,8,0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
HorizontalAlignment="Center"
Text="队伍"
TextAlignment="Center" />
<ui:TextBlock Grid.Column="2"
Margin="8,0,8,0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="秘境"
TextAlignment="Center" />
<ui:TextBlock Grid.Column="3"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="奖励"
TextAlignment="Center" />
</Grid>
<Grid Margin="20,8,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Column="0"
HorizontalAlignment="Center"
Text="默认"
VerticalAlignment="Center" />
<ui:TextBox Grid.Column="1"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.PartyName, Mode=TwoWay}"
TextAlignment="Center"
TextWrapping="Wrap"
PlaceholderText="留空则不切换队伍" />
<vio:CascadingComboBox Grid.Column="2"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.DomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.SundayWeeklySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周一"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.MondayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.MondayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.MondaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周二"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.TuesdayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.TuesdayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.TuesdaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周三"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.WednesdayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.WednesdayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.WednesdaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周四"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.ThursdayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.ThursdayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.ThursdaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周五"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.FridayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.FridayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.FridaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周六"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.SaturdayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.SaturdayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.SaturdaySelectedValue, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid Margin="20,16,20,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="56" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
Margin="38,0,0,0"
HorizontalAlignment="Center"
Text="周日"
VerticalAlignment="Center" />
<ui:TextBox Grid.Row="0"
Grid.Column="1"
MinWidth="140"
Margin="5,0,12,0"
MinWidth="0"
Margin="8,0,8,0"
Text="{Binding SelectedConfig.SundayPartyName, Mode=TwoWay}"
TextWrapping="Wrap"
VerticalAlignment="Center"
TextAlignment="Center"
PlaceholderText="填写队伍名称 " />
PlaceholderText="留空使用默认队伍" />
<vio:CascadingComboBox Grid.Row="0"
Grid.Column="2"
Width="100"
Margin="0,0,36,0"
MinWidth="0"
Margin="8,0,8,0"
HorizontalAlignment="Stretch"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding SelectedConfig.SundayDomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
<Border Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.RowSpan="2"
Margin="0,21,100,10"
Background="{DynamicResource ControlFillColorDefaultBrush}"
BorderBrush="{DynamicResource ControlElevationBorderBrush}"
BorderThickness="1"
CornerRadius="5"
Width="Auto"
HorizontalAlignment="Right"
Padding="10">
<ui:TextBlock FontTypography="Body"
FontSize="13"
Text="周日或限时三种奖励,从上往下(1/2/3)序号:"
TextAlignment="Justify"
TextWrapping="Wrap" />
</Border>
<ComboBox Grid.Row="1"
Grid.Column="2"
Grid.RowSpan="2"
Margin="20,11,37,0"
HorizontalAlignment="Right"
<ComboBox Grid.Row="0"
Grid.Column="3"
MinWidth="56"
HorizontalContentAlignment="Center"
VerticalAlignment="Center"
ItemsSource="{Binding SundaySelectedValueList , Mode=TwoWay}"
SelectedItem="{Binding SelectedConfig.SundaySelectedValue, Mode=TwoWay}">
</ComboBox>
ItemsSource="{Binding SundaySelectedValueList}"
SelectedItem="{Binding SelectedConfig.SundaySelectedValue, Mode=TwoWay}" />
</Grid>
</StackPanel>
</ui:CardExpander>
@@ -4,6 +4,7 @@
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
xmlns:helpers="clr-namespace:BetterGenshinImpact.Helpers"
xmlns:markup="clr-namespace:BetterGenshinImpact.Markup"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
@@ -1326,6 +1327,7 @@
Grid.Column="1"
Width="180"
Margin="0,0,36,0"
behavior:DomainCascadingComboBoxBehavior.UseFullLabelsWhenOpen="True"
ItemsSource="{x:Static helpers:DomainCascadingItems.Items}"
SelectedCascadingItem="{Binding Config.AutoDomainConfig.DomainName, Mode=TwoWay, Converter={StaticResource DomainNameConverter}}" />
</Grid>
@@ -488,6 +488,57 @@
Margin="0,0,24,0"
Text="{Binding Config.AutoSkipConfig.AfterChooseOptionSleepDelay, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="听完语音后再选择对话选项"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="通过游戏进程音频的人声检测判断台词结束;等待数秒仍未检测到语音时继续,无法读取游戏声音时使用上方固定延迟"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,8,0"
IsChecked="{Binding Config.AutoSkipConfig.AutoWaitDialogueOptionVoiceEnabled, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="语音结束检测最大等待(秒)"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="超过该时间仍未检测到语音结束时会继续选择,避免卡住剧情"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
MinWidth="90"
Margin="0,0,24,0"
Text="{Binding Config.AutoSkipConfig.DialogueOptionVoiceMaxWaitSeconds, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -18,7 +18,7 @@ public partial class MacroSettingsPageViewModel : ViewModel
private readonly INavigationService _navigationService;
[ObservableProperty]
private string[] _quickFightMacroHotkeyMode = [OneKeyFightTask.HoldOnMode, OneKeyFightTask.TickMode];
private string[] _quickFightMacroHotkeyMode = [OneKeyFightTask.HoldOnMode, OneKeyFightTask.HoldFinishMode, OneKeyFightTask.TickMode];
public MacroSettingsPageViewModel(IConfigService configService, INavigationService navigationService)
{
@@ -640,6 +640,18 @@ public partial class ScriptControlViewModel : ViewModel
if (newScriptGroup != null)
{
newScriptGroup.Name = str;
ScriptGroup.ResetGroupInfo(newScriptGroup);
foreach (var project in newScriptGroup.Projects)
{
try
{
project.BuildScriptProjectRelation();
}
catch
{
// ignored
}
}
ScriptGroups.Add(newScriptGroup);
}
@@ -22,7 +22,7 @@
<PackageReference Include="Vanara.Windows.Extensions" Version="4.1.3" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
</ItemGroup>
</Project>