Merge branch 'main' into refactor/20260930
This commit is contained in:
commit
6c222e1f1d
11 files changed
+293
-51
No files matched your search
@@ -1,7 +1,7 @@
|
||||
<!--
|
||||
感谢你的贡献!提交前请先阅读以下说明 / Thanks for contributing! Please read this before submitting:
|
||||
1. 请按模板逐项填写,请勿删除模板中的标题,否则内容无法被正确识别 / Fill in every section and do not delete the headings.
|
||||
2. 未填写关键信息(解决的需求、是否在游戏内实际运行、代码是否纯手工编写)的 PR 可能会被直接关闭 / PRs missing key information may be closed directly.
|
||||
2. 未填写关键信息(解决的需求、是否在游戏内实际运行、代码是否纯手工编写、使用的 AI 模型名称)的 PR 可能会被直接关闭 / PRs missing key information may be closed directly.
|
||||
3. 请保持改动聚焦,避免在一次 PR 中混入与需求无关的大规模改动 / Keep the change focused.
|
||||
-->
|
||||
|
||||
@@ -53,6 +53,10 @@
|
||||
- [ ] 部分代码由 AI 辅助生成,我已逐行阅读、理解并验证 / Partly AI-assisted; I have read, understood and verified it line by line
|
||||
- [ ] 本次代码完全由 AI 生成,我已逐行阅读、理解并验证 / Fully AI-generated; I have read, understood and verified it line by line
|
||||
|
||||
**使用的 AI 具体模型名称(未使用 AI 请填“无”;使用多个模型请逐一列出)/ Specific AI model names (write "None" if no AI was used; list all models used):**
|
||||
|
||||
<!-- 例:GPT 6.1 Sol、Claude Opus 5.5;请填写实际使用的具体模型,不要仅填写“GPT”或“Claude” / Examples: GPT 6.1 Sol, Claude Opus 5.5. Specify the actual models used, not just "GPT" or "Claude". -->
|
||||
|
||||
**AI 参与的部分及我的验证方式(未使用 AI 请填“无”)/ AI-involved parts and how I verified them (write "None" if no AI was used):**
|
||||
|
||||
**我确认 / I confirm:**
|
||||
@@ -60,13 +64,6 @@
|
||||
- [ ] 我理解本次改动的全部逻辑,能够解释每一处修改的原因 / I understand the entire change and can explain every modification
|
||||
- [ ] 提交的代码不包含来源不明、我无法解释的代码片段 / No unexplained code from unknown sources is included
|
||||
|
||||
## 改动类型 / Type of Change
|
||||
|
||||
- [ ] 新功能 / New feature
|
||||
- [ ] 问题修复 / Bug fix
|
||||
- [ ] 重构或性能优化 / Refactor or performance
|
||||
- [ ] 文档或其他杂项 / Docs or chores
|
||||
|
||||
## 影响范围 / Impact
|
||||
|
||||
**涉及的模块或功能 / Affected modules or features:**
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.66.3-alpha.1</Version>
|
||||
<Version>0.66.3-alpha.3</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net10.0-windows10.0.22621.0</TargetFramework>
|
||||
@@ -57,8 +57,8 @@
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.1.120" />
|
||||
|
||||
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.25" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.40" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.26" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.41" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.31" />
|
||||
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
|
||||
@@ -3,12 +3,14 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using BetterGenshinImpact.Infrastructure.Network.Download;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
@@ -348,13 +350,37 @@ public sealed class OnnxRuntimeInstaller : IOnnxRuntimeInstaller, IDisposable
|
||||
var registration = await ReadJsonAsync($"https://api.nuget.org/v3/registration5-gz-semver2/{lower}/{version}.json", token);
|
||||
var catalogUrl = new Uri(registration.Value<string>("catalogEntry")!);
|
||||
if (catalogUrl.Scheme != "https" || catalogUrl.Host != "api.nuget.org") throw new InvalidDataException("NuGet 元数据地址无效。");
|
||||
var catalog = await ReadJsonAsync(catalogUrl.AbsoluteUri, token);
|
||||
var entry = catalog;
|
||||
JObject entry;
|
||||
try
|
||||
{
|
||||
entry = await ReadJsonAsync(catalogUrl.AbsoluteUri, token);
|
||||
}
|
||||
catch (HttpRequestException e) when (e.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
// NuGet 的 Catalog 在中国不可用,但包内容仍可下载;通过 V2 获取同一版本的大小和摘要。
|
||||
var metadata = XDocument.Parse(await ReadTextAsync(
|
||||
$"https://www.nuget.org/api/v2/Packages(Id='{Uri.EscapeDataString(id)}',Version='{Uri.EscapeDataString(version)}')",
|
||||
token, "application/atom+xml"));
|
||||
XNamespace metadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
|
||||
XNamespace dataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
|
||||
var package = metadata.Root?.Element(metadataNamespace + "properties")
|
||||
?? throw new InvalidDataException("NuGet V2 包元数据无效。");
|
||||
entry = new JObject
|
||||
{
|
||||
["packageSize"] = (string?)package.Element(dataNamespace + "PackageSize"),
|
||||
["packageHashAlgorithm"] = (string?)package.Element(dataNamespace + "PackageHashAlgorithm"),
|
||||
["packageHash"] = (string?)package.Element(dataNamespace + "PackageHash")
|
||||
};
|
||||
}
|
||||
var size = entry.Value<long>("packageSize");
|
||||
if (size <= 0 || size > long.MaxValue / 4) throw new InvalidDataException("NuGet 包大小无效。");
|
||||
var algorithm = entry.Value<string>("packageHashAlgorithm")!;
|
||||
if (algorithm != "SHA512") throw new InvalidDataException("NuGet 包摘要算法不符合预期。");
|
||||
var hash = entry.Value<string>("packageHash");
|
||||
if (hash == null || !Convert.TryFromBase64String(hash, new byte[64], out var hashLength) || hashLength != 64)
|
||||
throw new InvalidDataException("NuGet 包 SHA512 摘要无效。");
|
||||
return new($"{id} {version}", new($"https://api.nuget.org/v3-flatcontainer/{lower}/{version}/{lower}.{version}.nupkg"), size, size * 4,
|
||||
entry.Value<string>("packageHash"), algorithm, id);
|
||||
hash, algorithm, id);
|
||||
}
|
||||
|
||||
private static RuntimeDownloadPackage GetNvidiaPackage(string product, string component, string version, JToken entry)
|
||||
@@ -366,12 +392,17 @@ public sealed class OnnxRuntimeInstaller : IOnnxRuntimeInstaller, IDisposable
|
||||
}
|
||||
|
||||
private async Task<JObject> ReadJsonAsync(string url, CancellationToken token)
|
||||
=> JObject.Parse(await ReadTextAsync(url, token));
|
||||
|
||||
private async Task<string> ReadTextAsync(string url, CancellationToken token, string? accept = null)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
using var response = await _client.GetAsync(url, timeout.Token);
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (accept != null) request.Headers.Accept.ParseAdd(accept);
|
||||
using var response = await _client.SendAsync(request, timeout.Token);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return JObject.Parse(await response.Content.ReadAsStringAsync(timeout.Token));
|
||||
return await response.Content.ReadAsStringAsync(timeout.Token);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
|
||||
@@ -2404,7 +2404,8 @@
|
||||
"没头脑",
|
||||
"风仙",
|
||||
"Vesna"
|
||||
]
|
||||
],
|
||||
"elementalType": "Anemo"
|
||||
},
|
||||
{
|
||||
"id": "10000137",
|
||||
@@ -2416,7 +2417,8 @@
|
||||
"alias": [
|
||||
"瓦列里",
|
||||
"Valeriy"
|
||||
]
|
||||
],
|
||||
"elementalType": "Electro"
|
||||
},
|
||||
{
|
||||
"id": "10000136",
|
||||
@@ -2428,6 +2430,34 @@
|
||||
"alias": [
|
||||
"米提亚",
|
||||
"Mitya"
|
||||
]
|
||||
],
|
||||
"elementalType": "Electro"
|
||||
},
|
||||
{
|
||||
"id": "10000147",
|
||||
"name": "达妮卡",
|
||||
"nameEn": "Danica",
|
||||
"weapon": "11",
|
||||
"skillCD": 18,
|
||||
"burstCD": 15,
|
||||
"alias": [
|
||||
"达妮卡",
|
||||
"Danica"
|
||||
],
|
||||
"elementalType": "Electro"
|
||||
},
|
||||
{
|
||||
"id": "10000149",
|
||||
"name": "安娜丝塔夏",
|
||||
"nameEn": "Anastasya",
|
||||
"weapon": "12",
|
||||
"skillCD": 15,
|
||||
"skillHoldCD": 15,
|
||||
"burstCD": 15,
|
||||
"alias": [
|
||||
"安娜丝塔夏",
|
||||
"Anastasya"
|
||||
],
|
||||
"elementalType": "Cryo"
|
||||
}
|
||||
]
|
||||
@@ -3,6 +3,7 @@ using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Threading;
|
||||
using TimeSpan = System.TimeSpan;
|
||||
using Vanara.PInvoke;
|
||||
@@ -44,7 +45,7 @@ public class CombatCommand
|
||||
if (Method == Method.Walk)
|
||||
{
|
||||
AssertUtils.IsTrue(Args.Count == 2, "walk方法必须有两个入参,第一个参数是方向,第二个参数是行走时间。例:walk(s, 0.2)");
|
||||
var s = double.Parse(Args[1]);
|
||||
var s = ParseSeconds(Args[1]);
|
||||
AssertUtils.IsTrue(s > 0, "行走时间必须大于0");
|
||||
}
|
||||
else if (Method == Method.W || Method == Method.A || Method == Method.S || Method == Method.D)
|
||||
@@ -74,6 +75,15 @@ public class CombatCommand
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析以秒为单位的参数。策略文本里的小数点固定为 '.',不能跟随系统区域设置,
|
||||
/// 否则在以 ',' 为小数点、'.' 为千分位的区域(如 pt-BR、de-DE)里 "0.85" 会被读成 85。
|
||||
/// </summary>
|
||||
internal static double ParseSeconds(string value)
|
||||
{
|
||||
return double.Parse(value, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return $"<CombatCommand {Name}, {Method}({Args}) (rounds {ActivatingRound})>";
|
||||
@@ -153,7 +163,7 @@ public class CombatCommand
|
||||
{
|
||||
if (Args is { Count: > 0 })
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Attack((int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else
|
||||
@@ -165,7 +175,7 @@ public class CombatCommand
|
||||
{
|
||||
if (Args is { Count: > 0 })
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Charge((int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else
|
||||
@@ -175,32 +185,32 @@ public class CombatCommand
|
||||
}
|
||||
else if (Method == Method.Walk)
|
||||
{
|
||||
var s = double.Parse(Args![1]);
|
||||
var s = ParseSeconds(Args![1]);
|
||||
avatar.Walk(Args![0], (int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.W)
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Walk("w", (int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.A)
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Walk("a", (int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.S)
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Walk("s", (int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.D)
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Walk("d", (int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.Wait)
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Wait((int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else if (Method == Method.Ready)
|
||||
@@ -219,7 +229,7 @@ public class CombatCommand
|
||||
{
|
||||
if (Args is { Count: > 0 })
|
||||
{
|
||||
var s = double.Parse(Args![0]);
|
||||
var s = ParseSeconds(Args![0]);
|
||||
avatar.Dash((int)TimeSpan.FromSeconds(s).TotalMilliseconds);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -403,7 +403,8 @@ public class AutoLeyLineOutcropTask : ISoloTask<AutoLeyLineOutcropParam, ResinCl
|
||||
|
||||
_ocrRo1 = RecognitionObject.Ocr(ScaleTo1080(800), ScaleTo1080(200), ScaleTo1080(300), ScaleTo1080(100));
|
||||
_ocrRo2 = RecognitionObject.Ocr(ScaleTo1080(0), ScaleTo1080(200), ScaleTo1080(300), ScaleTo1080(300));
|
||||
_ocrRo3 = RecognitionObject.Ocr(ScaleTo1080(1200), ScaleTo1080(520), ScaleTo1080(300), ScaleTo1080(300));
|
||||
// 其他玩家放置的造物会额外增加“拆除”等选项,将“接触地脉溢口”向上顶出原识别区。
|
||||
_ocrRo3 = RecognitionObject.Ocr(ScaleTo1080(1200), ScaleTo1080(300), ScaleTo1080(300), ScaleTo1080(520));
|
||||
}
|
||||
|
||||
private static int ScaleTo1080(int value)
|
||||
|
||||
@@ -429,6 +429,13 @@ public class TaskRunner
|
||||
|
||||
// 激活原神窗口;遮罩的显示由下一帧上报给 IMaskWindowHost 后自动恢复
|
||||
runtime.Window.Activate();
|
||||
|
||||
// 游戏获焦后再释放,避免鼠标抬起事件落到 BGI 界面。
|
||||
// [输入状态安全] 任务启动前释放所有残留按键。
|
||||
// 助手触发命令时,游戏角色可能正在赶路/鼓舞(W/Shift/空格等长按),按键可能残留按下状态。
|
||||
// 若不在新任务开始前释放,残留按键会导致新任务角色持续移动或行为异常。
|
||||
// 与 End() 中的 InputHub.ReleaseAll() 对称,保证任务以干净的输入状态进入。
|
||||
InputHub.ReleaseAll();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -633,7 +633,7 @@
|
||||
</StackPanel>
|
||||
</ui:CardExpander>
|
||||
|
||||
<!-- 云原神网页版:每个实例是一个独立的 BetterGI 进程,按实例名保存 WebView 数据(仅 Primary 显示);首页仅保留管理入口 -->
|
||||
<!-- 云原神网页版:每个实例是一个独立的 BetterGI 进程,按实例名保存 WebView 数据(仅 Debug 构建且已附加调试器的 Primary 显示);首页仅保留管理入口 -->
|
||||
<ui:CardControl Margin="0,0,0,12"
|
||||
Icon="{ui:SymbolIcon Cloud24}"
|
||||
Visibility="{Binding IsCloudWebEntryVisible, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}">
|
||||
|
||||
@@ -104,9 +104,11 @@ public partial class HomePageViewModel : ViewModel, IDisposable
|
||||
: "等待连接 · 1080P";
|
||||
|
||||
/// <summary>
|
||||
/// 「云原神网页版」卡片只在 Primary 显示
|
||||
/// 「云原神网页版」卡片只在 Debug 构建且已附加调试器的 Primary 显示
|
||||
/// </summary>
|
||||
public bool IsCloudWebEntryVisible => InstanceBootstrap.Current.Context.IsRoot;
|
||||
public bool IsCloudWebEntryVisible => RuntimeHelper.IsDebug
|
||||
&& RuntimeHelper.IsDebuggerAttached
|
||||
&& InstanceBootstrap.Current.Context.IsRoot;
|
||||
|
||||
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(StartTriggerCommand))]
|
||||
private bool _startButtonEnabled = true;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Fischless.GameCapture.Graphics.Helpers;
|
||||
@@ -21,6 +21,11 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
{
|
||||
// BGR Mat 池:有界 ConcurrentQueue,FIFO 回收
|
||||
private const int MaxPoolSize = 16;
|
||||
|
||||
// 帧池容量:到达即取模式(FrameArrived 内排干留最新 + stash)下池不攒帧,恒为 2 即够——
|
||||
// 1 个 buffer 被 stash 中的最新帧检出占用,1 个始终留给 DWM 写下一帧合成,与刷新率/消费节拍无关
|
||||
// (Sunshine display_wgc.cpp 同款取值)。容量 1 会让 DWM 推帧等消费释放,不可取
|
||||
private const int FramePoolCapacity = 2;
|
||||
private readonly ConcurrentQueue<Mat> _bgrQueue = new();
|
||||
private bool _bgrPoolClosed = true;
|
||||
private readonly HashSet<Mat> _bgrBorrowed = new();
|
||||
@@ -46,6 +51,19 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
|
||||
private readonly object _lock = new();
|
||||
|
||||
// 到达即取(Sunshine on_frame_arrived / 官方 sample BasicCapture 同款):
|
||||
// FrameArrived 回调内立即排干帧池、只保留最新一帧挂到 _stashedFrame,消费线程 Capture() 时
|
||||
// 取走渲染、读完立即检入归还。回调只做帧检出/检入(WinRT 轻量操作),不触碰 D3D11 设备上下文,
|
||||
// 渲染/回读仍在消费线程——不重开"回调线程持设备锁冻结其他线程"的通路。
|
||||
// _frameLock 仅保护 stash 本身;锁序:消费方 _lock → _frameLock,回调/泵线程只取 _frameLock,无反向路径
|
||||
private readonly object _frameLock = new();
|
||||
private Direct3D11CaptureFrame? _stashedFrame; // 到达线程写入的最新帧(已检出);消费取走后由消费方归还
|
||||
private long _stashedFrameGeneration; // stash 帧所属帧池代数(与 _stashedFrame 成对读写)
|
||||
|
||||
// 帧池代数:每次 Recreate 自增。stash 中可能残留 Recreate 前旧尺寸的帧,
|
||||
// 消费时按代数丢弃,避免旧尺寸帧再次触发反向 Recreate(把新池建回旧尺寸)
|
||||
private long _poolGeneration;
|
||||
|
||||
// FFmpeg gfxcapture 式限流:MinUpdateInterval 把 DWM 推帧率限到消费需求率(26100+,接口 QI 调用,见 TryApplyMinUpdateInterval)
|
||||
private Windows.Graphics.SizeInt32 _capSize;
|
||||
private long _minUpdateIntervalHns; // 默认 0 = 不启用限流,WinRT TimeSpan(100ns 单位)
|
||||
@@ -67,7 +85,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
// 在途捕获数(正持锁外 Map/读回)。Stop 与尺寸 Recreate 销毁 staging 前必须等其归零;仅锁内访问
|
||||
private int _activeCaptures;
|
||||
|
||||
// 无新帧跳过读回:消费时 TryGetNextFrame 为空(池已排空,无新内容),克隆缓存直接返回,
|
||||
// 无新帧跳过读回:消费时 stash 为空(到达回调已排干、无更新的帧),克隆缓存直接返回,
|
||||
// 避免对旧内容重复 GPU/PCIe 回读空转。缓存常建:每次消费新帧时写入缓存 + 克隆给消费者
|
||||
private Mat? _cachedBgr;
|
||||
private long _cachedFrameTs; // 缓存内容对应的帧时间戳
|
||||
@@ -157,7 +175,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
// Capture 返回空的节流日志时间点(Environment.TickCount64 毫秒)
|
||||
private long _lastNullLogMs;
|
||||
|
||||
// 帧到达信号计数(仅回调线程递增,诊断用;实际取帧由消费线程在 Capture 内完成)
|
||||
// 帧到达/排干计数(仅回调线程递增,诊断用)
|
||||
private long _arrivalSeq;
|
||||
|
||||
// WGC WinRT 对象(帧池/会话/捕获项)具有线程亲和性:Win10 上跨线程 Recreate 抛
|
||||
@@ -356,7 +374,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
_d3dDevice = Direct3D11Helper.CreateDevice();
|
||||
|
||||
// CreateFreeThreaded 契约:帧池对象可跨线程访问,不依赖 DispatcherQueue/消息泵;
|
||||
// TryGetNextFrame 由消费线程调用(FFmpeg gfxcapture 同款需求驱动模型),
|
||||
// TryGetNextFrame 由到达回调线程调用(Sunshine/官方 sample 同款到达即取模型),
|
||||
// Recreate/销毁则必须回到本泵线程执行
|
||||
try
|
||||
{
|
||||
@@ -369,7 +387,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
_captureFramePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
|
||||
_d3dDevice,
|
||||
_pixelFormat,
|
||||
2,
|
||||
FramePoolCapacity,
|
||||
_captureItem.Size);
|
||||
}
|
||||
catch (Exception)
|
||||
@@ -378,7 +396,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
_captureFramePool = Direct3D11CaptureFramePool.CreateFreeThreaded(
|
||||
_d3dDevice,
|
||||
_pixelFormat,
|
||||
2,
|
||||
FramePoolCapacity,
|
||||
_captureItem.Size);
|
||||
_isHdrEnabled = false;
|
||||
}
|
||||
@@ -580,20 +598,60 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
|
||||
private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
|
||||
{
|
||||
// ffmpeg gfxcapture 同款需求驱动模型:到达回调只做计数信号,绝不在此线程触碰 D3D11。
|
||||
// 取帧、Recreate、绘制、回读全部由消费线程在 Capture() 内按需完成,
|
||||
// 从根上消除"回调线程持设备锁阻塞、冻结其他线程"的通路
|
||||
if (!IsCapturing)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 到达即取(Sunshine on_frame_arrived / 官方 sample BasicCapture 同款):
|
||||
// 立即排干帧池、只保留最新一帧,被替换的旧帧立即检入归还——
|
||||
// DWM 以合成节拍(~60fps)连续推帧且与内容变化无关(实测到达间隔恒定 ~16.7ms),
|
||||
// 攒帧会让小容量池打满、DWM 等空闲 buffer,消费方读到的永远是几帧前的画面
|
||||
// (三方同屏实测:取最旧 p50 122ms/p95 147ms,到达即取 p50 40ms/p95 65ms)。
|
||||
// 此处只做帧检出/检入(WinRT 轻量操作),不触碰 D3D11 设备上下文;
|
||||
// Recreate、绘制、回读仍由消费线程/泵线程完成,不重开"回调线程持设备锁冻结"的通路
|
||||
Interlocked.Increment(ref _arrivalSeq);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
// 代数必须在取帧前读:Recreate 与本回调并发时,横跨 Recreate 的取帧
|
||||
// 会盖上旧代数而被消费侧丢弃(至多损失一帧,下一帧即恢复),不会反向 Recreate
|
||||
var generation = Interlocked.Read(ref _poolGeneration);
|
||||
var next = sender.TryGetNextFrame();
|
||||
if (next == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
Direct3D11CaptureFrame? replaced;
|
||||
lock (_frameLock)
|
||||
{
|
||||
replaced = _stashedFrame;
|
||||
_stashedFrame = next;
|
||||
_stashedFrameGeneration = generation;
|
||||
}
|
||||
|
||||
replaced?.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 会话/池关闭瞬间 TryGetNextFrame 可能抛异常:stash 保留上一帧,消费侧照常工作
|
||||
Debug.WriteLine($"[WGC V2] 到达取帧异常(保留已有 stash): {e.GetType().Name}: {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主动取出一帧并绘制到广播纹理(消费线程调用,必须持 <see cref="_lock"/>)。
|
||||
/// 把 stash 中的最新帧绘制到广播纹理(消费线程调用,必须持 <see cref="_lock"/>)。
|
||||
/// stash 由到达回调排干帧池维持恒为最新(到达即取模型);帧的检入归还在调用方完成。
|
||||
/// 返回 false 表示无新帧或本帧被跳过(缓存帧仍有效);true 表示已绘制并更新 <see cref="_gpuFrameTs"/>。
|
||||
/// </summary>
|
||||
private bool TryRenderNewFrameLocked()
|
||||
private bool TryRenderNewFrameLocked(Direct3D11CaptureFrame frame, long frameGeneration)
|
||||
{
|
||||
using var frame = _captureFramePool?.TryGetNextFrame();
|
||||
if (frame == null)
|
||||
// Recreate 竞态守卫:旧帧池(Recreate 前)的遗留帧直接丢弃——
|
||||
// 新生代帧随后续到达补上,避免旧尺寸帧触发反向 Recreate 把新池建回旧尺寸
|
||||
if (frameGeneration != Interlocked.Read(ref _poolGeneration))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -616,11 +674,16 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
|
||||
// Recreate 必须在帧池的创建线程上执行(跨线程抛 RPC_E_WRONG_THREAD);
|
||||
// 失败异常交由 Capture() 的阶段0兜底记录并跳过本帧
|
||||
// 此处池必然存在:上方 TryGetNextFrame 即在其上成功取帧(且与 Stop 持 _lock 互斥)
|
||||
// 此处池必然存在:本帧即从当前池取出(且与 Stop 持 _lock 互斥)
|
||||
var framePool = _captureFramePool!;
|
||||
try
|
||||
{
|
||||
RunOnWgcThread(() => framePool.Recreate(_d3dDevice, _pixelFormat, 2, contentSize));
|
||||
RunOnWgcThread(() =>
|
||||
{
|
||||
framePool.Recreate(_d3dDevice, _pixelFormat, FramePoolCapacity, contentSize);
|
||||
// 池代数自增:此后到达的帧属于新池;stash 中旧池遗留帧由消费侧按代数丢弃
|
||||
Interlocked.Increment(ref _poolGeneration);
|
||||
});
|
||||
_recreateFailures = 0;
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -692,7 +755,7 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
drawStage = "MapConstantBuffer";
|
||||
// 必须 WriteDiscard:cb 仍绑定在上一帧 draw 的 PS 槽上,普通 Write 会 E_INVALIDARG。
|
||||
// 注意 WriteDiscard 不能与 DoNotWait 组合(运行时校验直接 E_INVALIDARG);
|
||||
// GPU 积压时的阻塞由需求驱动模型收束在消费线程自身,无跨线程冻结
|
||||
// GPU 积压时的阻塞只落在消费线程自身(回调线程不碰设备),无跨线程冻结
|
||||
var cbMap = context.MapSubresource(_drawCb, 0, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None);
|
||||
Marshal.WriteInt32(cbMap.DataPointer, 0, BitConverter.SingleToInt32Bits(uvMinX));
|
||||
Marshal.WriteInt32(cbMap.DataPointer, 4, BitConverter.SingleToInt32Bits(uvMinY));
|
||||
@@ -790,11 +853,24 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
return null;
|
||||
}
|
||||
|
||||
// 阶段0(需求驱动):消费线程主动取帧并绘制,回调线程只做信号计数。
|
||||
// 阶段0(到达驱动):从到达线程的 stash 取最新帧渲染,渲染完立即检入归还池——
|
||||
// buffer 归还与消费节拍解耦,DWM 永远有空闲 buffer 写下一帧合成
|
||||
// 任何异常都不允许逃出 Capture——触发器线程会因此整个停摆
|
||||
Direct3D11CaptureFrame? stashedFrame = null;
|
||||
long stashedGeneration = 0;
|
||||
lock (_frameLock)
|
||||
{
|
||||
stashedFrame = _stashedFrame;
|
||||
_stashedFrame = null;
|
||||
stashedGeneration = _stashedFrameGeneration;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
TryRenderNewFrameLocked();
|
||||
if (stashedFrame != null)
|
||||
{
|
||||
TryRenderNewFrameLocked(stashedFrame, stashedGeneration);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -805,6 +881,10 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
Debug.WriteLine($"[WGC V2] 取帧/绘制异常: {e.GetType().Name}: {e.Message}");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
stashedFrame?.Dispose(); // 检入归还池(渲染已完成,buffer 交还 DWM)
|
||||
}
|
||||
|
||||
if (_gpuTexture == null || _gpuFrameTs == 0)
|
||||
{
|
||||
@@ -1108,6 +1188,13 @@ public class GraphicsCaptureV2(bool captureHdr = false) : IGameCapture
|
||||
Debug.WriteLine($"[WGC V2] Stop 时泵线程清理失败(继续本地清理): {e.GetType().Name}: {e.Message}");
|
||||
}
|
||||
|
||||
// 清空 stash(池已销毁,帧对象只剩 COM 释放;IsCapturing=false 已挡住新 stash 写入)
|
||||
lock (_frameLock)
|
||||
{
|
||||
_stashedFrame?.Dispose();
|
||||
_stashedFrame = null;
|
||||
}
|
||||
|
||||
// IsCapturing=false 已挡住新的 Capture();等待在途捕获(正锁外 Map/CvtColor)退出,
|
||||
// 才能销毁其正在使用的 staging/纹理/设备。Monitor.Wait 原子放锁,捕获 finally 归零时唤醒
|
||||
while (_activeCaptures > 0)
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
using System.Globalization;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
|
||||
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFightTests;
|
||||
|
||||
public class CombatCommandCultureTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 小数点为 ',' 的区域(pt-BR、de-DE 等)下,"0.85" 也必须按 0.85 秒解析,
|
||||
/// 而不是把 '.' 当千分位读成 85 秒。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("pt-BR")]
|
||||
[InlineData("de-DE")]
|
||||
[InlineData("zh-CN")]
|
||||
[InlineData("en-US")]
|
||||
public void ParseSeconds_IgnoresCurrentCulture(string cultureName)
|
||||
{
|
||||
var original = CultureInfo.CurrentCulture;
|
||||
try
|
||||
{
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
|
||||
Assert.Equal(0.85, CombatCommand.ParseSeconds("0.85"));
|
||||
Assert.Equal(0.5, CombatCommand.ParseSeconds("0.5"));
|
||||
Assert.Equal(0.2, CombatCommand.ParseSeconds("0.2"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = original;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构造函数是不依赖游戏即可触达的调用点:walk(s, 0.2) 在 fr-FR / ru-RU 下,
|
||||
/// 旧的 double.Parse(Args[1]) 会因 '.' 不是小数点也不是千分位而抛 FormatException。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("fr-FR")]
|
||||
[InlineData("ru-RU")]
|
||||
[InlineData("pt-BR")]
|
||||
[InlineData("en-US")]
|
||||
public void WalkConstructor_ParsesDecimalSecondsInAnyCulture(string cultureName)
|
||||
{
|
||||
var original = CultureInfo.CurrentCulture;
|
||||
try
|
||||
{
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
|
||||
var command = new CombatCommand("芙宁娜", "walk(s, 0.2)");
|
||||
Assert.Equal("0.2", command.Args![1]);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = original;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 端到端:解析 issue 里的整行策略,参数文本保持原样,换算出的时长在 pt-BR 下仍是 850 毫秒。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void AttackArg_FromScriptLine_IsMillisecondsInPtBr()
|
||||
{
|
||||
var original = CultureInfo.CurrentCulture;
|
||||
try
|
||||
{
|
||||
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("pt-BR");
|
||||
var script = CombatScriptParser.ParseContext("芙宁娜 e, attack(0.85), check, attack(0.2)", validate: false);
|
||||
var attack = script.CombatCommands[1];
|
||||
Assert.Equal("0.85", attack.Args![0]);
|
||||
Assert.Equal(850, (int)System.TimeSpan.FromSeconds(CombatCommand.ParseSeconds(attack.Args[0])).TotalMilliseconds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CultureInfo.CurrentCulture = original;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user