Compare commits

..
Author SHA1 Message Date
ema bfb83c957e 修复部分组件未随主题变更颜色 #2644 2026-01-27 00:11:32 +08:00
824 changed files with 2478 additions and 49652 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
---
name: Bug report / 错误报告
about: Create a report to help us improve / 创建报告以帮助我们改进
title: "[bug]请补充标题内容"
labels: bug
---
<!--
请提供下述完整信息以便快速定位问题 / Please provide the following information to quickly locate the problem
-->
- 系统环境 / System Environment:
- BetterGI版本号 / BetterGI Version:
- 问题描述 / Description of the issue:
- 复现步骤 / Reproduction steps:
-41
View File
@@ -1,41 +0,0 @@
name: Bug report / 错误报告
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
title: "[bug] "
labels:
- BUG
body:
- type: textarea
id: environment
attributes:
label: 系统环境
description: System Environment,例如系统版本、运行环境
placeholder: Win11 / BetterGI 0.58.0 / .NET 8
validations:
required: true
- type: input
id: version
attributes:
label: BetterGI 版本号
description: BetterGI Version
placeholder: 0.58.0
validations:
required: true
- type: textarea
id: description
attributes:
label: 问题描述
description: Description of the issue
placeholder: 请详细描述你遇到的问题,可直接粘贴日志并附带截图
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
description: Reproduction steps
placeholder: |-
1. 打开……
2. 点击……
3. 出现……
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have feature requesting / 我有新功能请求
about: Your request may come as a surprise. / 你的请求也许成为惊喜
title: "[feature] "
labels: feature 功能请求
---
- Your feature requesting / 你的新功能请求
-30
View File
@@ -1,30 +0,0 @@
name: I have feature requesting / 我有功能需求
description: 提出新的功能想法 / Share a feature request
title: "[feature] "
labels:
- 功能建议
body:
- type: textarea
id: request
attributes:
label: 功能请求
description: Feature Request
placeholder: 请简要说明你希望新增什么能力
validations:
required: true
- type: textarea
id: scenario
attributes:
label: 使用场景
description: Use Case
placeholder: 这个功能要解决什么问题?在哪些场景下使用?
validations:
required: true
- type: textarea
id: extra
attributes:
label: 补充信息
description: Optional
placeholder: 可选,补充示意图、参考方案或限制条件
validations:
required: false
+5
View File
@@ -0,0 +1,5 @@
---
name: Feel free to express / 随便写写
about: Record something / 简单写写记录记录
---
-12
View File
@@ -1,12 +0,0 @@
name: Feel free to express / 自由描述
description: 记录你想反馈的内容 / Share general feedback
title: "[feedback] "
body:
- type: textarea
id: description
attributes:
label: 描述
description: Description
placeholder: 请描述你想反馈的内容
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have a question / 我有疑问
about: Solve your problem / 解决你的疑问
title: "[question] "
labels: question
---
- Problem Description / 问题描述
- 请尽量提供问题相关的截图/日志等内容
-22
View File
@@ -1,22 +0,0 @@
name: I have a question / 我有疑问
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
title: "[question] "
labels:
- 问题咨询
body:
- type: textarea
id: question
attributes:
label: 问题描述
description: Problem Description
placeholder: 请清楚描述你的问题
validations:
required: true
- type: textarea
id: tried
attributes:
label: 已尝试内容
description: Screenshots / logs / what you already tried
placeholder: 可附上截图、日志,以及你已经尝试过的排查过程
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have suggestions / 我有建议
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
title: "[suggestion] "
labels: suggestion
---
- Your suggestions / 你的建议
-22
View File
@@ -1,22 +0,0 @@
name: I have suggestions / 我有建议
description: 分享对项目的改进建议 / Share an improvement suggestion
title: "[suggestion] "
labels:
- 功能建议
body:
- type: textarea
id: suggestion
attributes:
label: 建议内容
description: Suggestion
placeholder: 请描述你的建议内容
validations:
required: true
- type: textarea
id: benefit
attributes:
label: 预期收益
description: Expected Benefit
placeholder: 这个建议会给用户或项目带来什么帮助?
validations:
required: true
-229
View File
@@ -1,229 +0,0 @@
runtime:
languageMode: auto
dryRun: false
providers:
openAiCompatible:
enabled: true
baseUrl: https://api.openai.com/v1
model: gpt-5.2-codex
apiStyle: responses
timeoutMs: 30000
issues:
autoProcessing:
skipCreatedBefore: auto
validation:
enabled: true
fallbackTemplateKey: normal
commentAnchor: issue-bot:validation
templates:
- key: bug
detect:
markers:
- bug
titlePrefixes:
- "[bug]"
requiredSections:
- id: environment
aliases:
- 系统环境
- System Environment
- id: version
aliases:
- BetterGI 版本号
- BetterGI Version
- id: description
aliases:
- 问题描述
- Description of the issue
- id: steps
aliases:
- 复现步骤
- Reproduction steps
labels:
whenValid:
- BUG
whenInvalid:
- 需要更多信息
- key: feature
detect:
markers:
- feature
titlePrefixes:
- "[feature]"
requiredSections:
- id: request
aliases:
- 功能请求
- Feature Request
- id: scenario
aliases:
- 使用场景
- Use Case
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: suggestion
detect:
markers:
- suggestion
titlePrefixes:
- "[suggestion]"
requiredSections:
- id: suggestion
aliases:
- 建议内容
- Suggestion
- id: benefit
aliases:
- 预期收益
- Expected Benefit
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: question
detect:
markers:
- question
titlePrefixes:
- "[question]"
requiredSections:
- id: question
aliases:
- 问题描述
- Problem Description
- id: tried
aliases:
- 已尝试内容
- What I Tried
labels:
whenValid:
- 问题咨询
whenInvalid:
- 需要更多信息
- key: normal
detect:
markers:
- normal
titlePrefixes:
- "[feedback]"
- "[normal]"
requiredSections:
- id: description
aliases:
- 描述
- Description
labels:
whenValid: []
whenInvalid:
- 需要更多信息
duplicateDetection:
enabled: true
bypassLabels:
- 跳过重复检测
duplicateLabel: 重复
searchResultLimit: 50
candidateLimit: 20
aiReviewMaxCandidates: 3
thresholds:
exact: 0.995
highConfidence: 0.93
reviewMin: 0.82
similarityComment:
enabled: true
commentAnchor: issue-bot:similar-issues
minScore: 0.3
maxCandidates: 3
labeling:
enabled: true
autoCreateMissing: true
managed:
- BUG
- 功能建议
- 问题咨询
- 需要更多信息
- 重复
definitions:
BUG:
color: d73a4a
description: 程序存在缺陷或异常行为。
功能建议:
color: a2eeef
description: 新功能建议或现有功能改进。
问题咨询:
color: d876e3
description: 使用问题、求助或咨询。
# 需要更多信息:
# color: fbca04
# description: 当前 Issue 缺少必要信息。
重复:
color: cfd3d7
description: 已存在相同或高度相似的问题。
keywordRules: []
aiClassification:
enabled: false
maxLabels: 3
minConfidence: 0.65
include: []
exclude:
- BUG
- 功能请求
- 重复
- 不会修复
- 使用问题
- 需要帮助
- 已完成
- 未解决
- 待确认
- P0
- P1
- 需要文档
- 优化点
- 急急急
prompt: 优先给 BetterGI Issue 选择能反映具体功能模块、子系统或使用场景的标签,例如一条龙、调度器、脚本、设置项、地图追踪;避免只选择宽泛的流程或状态标签。
sourceRepository:
owner: babalae
repo: better-genshin-impact
aiHelp:
enabled: true
triggerLabels: []
commentAnchor: issue-bot:ai
projectContext:
enabled: true
includeRepositoryMetadata: true
includeReadme: true
readmeMaxChars: 3000
profile:
name: BetterGI
aliases:
- BGI
- Better Genshin Impact
summary: BetterGI is a desktop automation assistant for Genshin Impact.
techStack:
- C#
- WPF
- .NET
commands:
enabled: true
mentions:
- "@bot"
- "@bettergi-repo-bot"
access: collaborators
fix:
enabled: true
commentAnchor: issue-bot:fix
refresh:
enabled: true
pullRequests:
review:
enabled: false
labeling:
enabled: false
summary:
enabled: false
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan_release_note:
if: github.repository_owner == 'babalae'
runs-on: macos-latest
steps:
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan:
if: github.repository_owner == 'babalae'
runs-on: windows-latest
steps:
- name: 📥 Download release
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
repository: zaodonganqi/bettergi-script-web
repository: A-Little-AnQi/bettergi-script-web
- uses: actions/setup-node@v4
with:
node-version: 20
-55
View File
@@ -1,55 +0,0 @@
name: Repo Bot
on:
issues:
types:
- opened
- edited
- reopened
- labeled
issue_comment:
types:
- created
- edited
jobs:
repo-bot:
runs-on: ubuntu-latest
permissions:
issues: write
contents: read
steps:
- name: Detect GitHub App configuration
id: auth-mode
shell: bash
env:
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
run: |
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
echo "use_app=true" >> "$GITHUB_OUTPUT"
else
echo "use_app=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Create GitHub App token
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
- name: Run Repo Bot
uses: ddaodan/bettergi-github-bot@v1
env:
GITHUB_TOKEN: ${{ github.token }}
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
with:
config-path: .github/repo-bot.yml
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
+1 -2
View File
@@ -28,11 +28,10 @@ github_actions_cache/
*.zip
# IDE & AI tools
# Rider
.idea
.trae
.claude
CLAUDE.md
AGENTS.md
__pycache__/
-2
View File
@@ -24,8 +24,6 @@
<bgivc:NotNullConverter x:Key="NotNullConverter" />
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
<bgivc:TrConverter x:Key="TrConverter" />
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
+9 -35
View File
@@ -52,7 +52,8 @@ public partial class App : Application
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureServices((context, services) =>
.ConfigureServices(
(context, services) =>
{
// 提前初始化配置
var configService = new ConfigService();
@@ -73,7 +74,7 @@ public partial class App : Application
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21))
.WriteTo.Console(outputTemplate:
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
@@ -85,25 +86,7 @@ public partial class App : Application
}
Log.Logger = loggerConfiguration.CreateLogger();
services.AddSingleton<IMissingTranslationReporter, SupabaseMissingTranslationReporter>();
services.AddSingleton<ITranslationService, JsonTranslationService>();
services.AddLogging(c => c.AddSerilog());
// if ("zh-Hans".Equals(all.OtherConfig.UiCultureInfoName, StringComparison.OrdinalIgnoreCase))
// {
// services.AddLogging(c => c.AddSerilog());
// }
// else
// {
// services.AddLogging(logging =>
// {
// logging.ClearProviders();
// logging.SetMinimumLevel(LogLevel.Debug);
// logging.AddFilter("Microsoft", LogLevel.Warning);
// logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);
// logging.Services.AddSingleton<ILoggerProvider, TranslatingSerilogLoggerProvider>();
// });
// }
services.AddLocalization();
@@ -165,13 +148,13 @@ public partial class App : Application
services.AddSingleton<IMihoyoMapApiService, MihoyoMapApiService>();
services.AddSingleton<IKongyingTavernApiService, KongyingTavernApiService>();
services.AddSingleton<IMaskMapPointService, MaskMapPointService>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
I18N.Culture = new CultureInfo("zh-Hans"); // #1846
}
)
@@ -224,19 +207,10 @@ public partial class App : Application
}
catch (Exception ex)
{
// DEBUG only, no overhead
Debug.WriteLine(ex);
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
try
{
HandleException(ex);
}
catch (Exception ex2)
{
Debug.WriteLine(ex2);
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
}
if (Debugger.IsAttached)
{
Debugger.Break();
@@ -252,12 +226,12 @@ public partial class App : Application
base.OnExit(e);
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
// 释放控制台窗口
ConsoleHelper.FreeConsoleWindow();
}
@@ -359,4 +333,4 @@ public partial class App : Application
// log
GetLogger<App>().LogDebug(e, "UnHandle Exception");
}
}
}
+3 -13
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.59.0</Version>
<Version>0.55.2-alpha.1</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -44,8 +44,8 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.15" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.10" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="DeviceId" Version="6.9.0" />
@@ -84,7 +84,6 @@
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<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.IO.Hashing" Version="9.0.4" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
@@ -129,9 +128,6 @@
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\LogParse\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -198,12 +194,6 @@
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\I18n\en.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
+1 -55
View File
@@ -2,9 +2,7 @@ using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model.Area;
using Fischless.WindowsInput;
@@ -120,56 +118,4 @@ public class BvPage
{
GameCaptureRegion.GameRegion1080PPosClick(x, y);
}
/// <summary>
/// 使用模糊匹配判断截图中是否包含目标文字。
/// 通过 <see cref="OcrFactory.PaddleMatch"/> 自动选择最佳实现(DP 模糊匹配或普通 OCR + 字符串比较)。
/// </summary>
/// <param name="target">目标字符串</param>
/// <param name="rect">感兴趣区域,default 表示全屏</param>
/// <param name="threshold">匹配阈值 (0~1),null 使用配置中的默认阈值</param>
/// <returns>是否匹配成功</returns>
public bool OcrMatch(string target, Rect rect = default, double? threshold = null)
{
var matchService = OcrFactory.PaddleMatch;
var actualThreshold = threshold
?? TaskContext.Instance().Config.OtherConfig.OcrConfig.OcrMatchDefaultThreshold;
var screen = TaskControl.CaptureToRectArea();
try
{
var roi = rect == default ? null : screen.DeriveCrop(rect);
try
{
var score = matchService.OcrMatch((roi ?? screen).SrcMat, target);
return score >= actualThreshold;
}
finally
{
roi?.Dispose();
}
}
finally
{
screen.Dispose();
}
}
/// <summary>
/// 重复截图并使用模糊匹配,等待目标文字出现。
/// 超时返回 false 而非抛异常。
/// </summary>
/// <param name="target">目标字符串</param>
/// <param name="rect">感兴趣区域,default 表示全屏</param>
/// <param name="threshold">匹配阈值 (0~1),null 使用配置中的默认阈值</param>
/// <param name="timeout">超时时间(毫秒),null 使用 DefaultTimeout</param>
/// <returns>是否在超时前匹配成功</returns>
public async Task<bool> WaitForOcrMatch(string target, Rect rect = default, double? threshold = null, int? timeout = null)
{
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = DefaultRetryInterval > 0 ? actualTimeout / DefaultRetryInterval : 1;
return await NewRetry.WaitForAction(() => OcrMatch(target, rect, threshold),
_cancellationToken, retryCount, DefaultRetryInterval);
}
}
}
+9 -20
View File
@@ -1,4 +1,5 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
@@ -21,10 +22,7 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.GetGridIcons;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.MapMask;
using BetterGenshinImpact.GameTask.SkillCd;
using BetterGenshinImpact.GameTask.UseRedeemCode;
namespace BetterGenshinImpact.Core.Config;
@@ -129,6 +127,11 @@ public partial class AllConfig : ObservableObject
/// </summary>
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
/// <summary>
/// 自动烹饪配置
/// </summary>
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 自动打牌配置
/// </summary>
@@ -169,24 +172,12 @@ public partial class AllConfig : ObservableObject
/// 自动吃药配置
/// </summary>
public AutoEatConfig AutoEatConfig { get; set; } = new();
/// <summary>
/// 自动地脉花配置
/// </summary>
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 地图遮罩
/// </summary>
public MapMaskConfig MapMaskConfig { get; set; } = new();
/// <summary>
/// 技能 CD 提示
/// </summary>
public SkillCdConfig SkillCdConfig { get; set; } = new();
/// <summary>
/// 自动使用
/// </summary>
@@ -266,6 +257,7 @@ public partial class AllConfig : ObservableObject
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -275,8 +267,6 @@ public partial class AllConfig : ObservableObject
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
TpConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -284,7 +274,6 @@ public partial class AllConfig : ObservableObject
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
DevConfig.PropertyChanged += OnAnyPropertyChanged;
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -297,4 +286,4 @@ public partial class AllConfig : ObservableObject
{
NotificationService.Instance().RefreshNotifiers();
}
}
}
@@ -14,10 +14,10 @@ public partial class HardwareAccelerationConfig : ObservableObject
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
/// <summary>
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
/// </summary>
[ObservableProperty]
private bool _cpuOcr = true;
private bool _cpuOcr = false;
#region 一般GPU加速设置
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -100,13 +100,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 技能CD提示开关
[ObservableProperty]
private string _skillCdEnabledHotkey = "";
[ObservableProperty]
private string _skillCdEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 截图
[ObservableProperty]
@@ -163,13 +156,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _autoFishingGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动烹饪开始/停止
[ObservableProperty]
private string _autoCookGameHotkey = "";
[ObservableProperty]
private string _autoCookGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动寻路
[ObservableProperty]
private string _autoTrackPathHotkey = "";
@@ -251,11 +237,4 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 地图遮罩开关
[ObservableProperty]
private string _mapMaskEnabledHotkey = "";
[ObservableProperty]
private string _mapMaskEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -63,6 +63,13 @@ public partial class MaskWindowConfig : ObservableObject
[ObservableProperty]
private bool _showFps = false;
/// <summary>
/// 作为原神子窗体
/// 有些bug没解决
/// </summary>
[ObservableProperty]
private bool _useSubform = false;
/// <summary>
/// 遮罩文本透明度 (0.0-1.0)
/// </summary>
@@ -76,10 +83,10 @@ public partial class MaskWindowConfig : ObservableObject
private double _logTextBoxLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _logTextBoxTopRatio = 822.0 / 1080;
private double _logTextBoxTopRatio = 832.0 / 1080;
[ObservableProperty]
private double _logTextBoxWidthRatio = 480.0 / 1920;
private double _logTextBoxWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _logTextBoxHeightRatio = 188.0 / 1080;
@@ -88,10 +95,10 @@ public partial class MaskWindowConfig : ObservableObject
private double _statusListLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _statusListTopRatio = 790.0 / 1080;
private double _statusListTopRatio = 807.0 / 1080;
[ObservableProperty]
private double _statusListWidthRatio = 480.0 / 1920;
private double _statusListWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _statusListHeightRatio = 24.0 / 1080;
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.Helpers;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -62,87 +61,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private List<string> _secretTreasureObjects = new();
// 地脉花一条龙模式(跳过部分准备流程)
[ObservableProperty]
private bool _leyLineOneDragonMode = false;
// 地脉花运行日期设置
[ObservableProperty]
private bool _leyLineRunMonday = true;
[ObservableProperty]
private bool _leyLineRunTuesday = true;
[ObservableProperty]
private bool _leyLineRunWednesday = true;
[ObservableProperty]
private bool _leyLineRunThursday = true;
[ObservableProperty]
private bool _leyLineRunFriday = true;
[ObservableProperty]
private bool _leyLineRunSaturday = true;
[ObservableProperty]
private bool _leyLineRunSunday = true;
// 地脉花每日类型与国家配置(为空则使用独立任务配置)
[ObservableProperty]
private string _leyLineMondayType = string.Empty;
[ObservableProperty]
private string _leyLineMondayCountry = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayType = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayType = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineThursdayType = string.Empty;
[ObservableProperty]
private string _leyLineThursdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineFridayType = string.Empty;
[ObservableProperty]
private string _leyLineFridayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayType = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSundayType = string.Empty;
[ObservableProperty]
private string _leyLineSundayCountry = string.Empty;
// 地脉花刷取次数(0 表示使用独立任务配置)
[ObservableProperty]
private int _leyLineRunCount = 0;
// 地脉花树脂耗尽模式
[ObservableProperty]
private bool _leyLineResinExhaustionMode = false;
// 地脉花刷取次数取小值(仅耗尽模式生效)
[ObservableProperty]
private bool _leyLineOpenModeCountMin = false;
#region 每周秘境配置
//周一
@@ -224,62 +142,5 @@ public partial class OneDragonFlowConfig : ObservableObject
}
}
public bool ShouldRunLeyLineToday()
{
if (!LeyLineRunMonday
&& !LeyLineRunTuesday
&& !LeyLineRunWednesday
&& !LeyLineRunThursday
&& !LeyLineRunFriday
&& !LeyLineRunSaturday
&& !LeyLineRunSunday)
{
return true;
}
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => LeyLineRunMonday,
DayOfWeek.Tuesday => LeyLineRunTuesday,
DayOfWeek.Wednesday => LeyLineRunWednesday,
DayOfWeek.Thursday => LeyLineRunThursday,
DayOfWeek.Friday => LeyLineRunFriday,
DayOfWeek.Saturday => LeyLineRunSaturday,
DayOfWeek.Sunday => LeyLineRunSunday,
_ => true
};
}
public (string type, string country) GetLeyLineConfigForToday(AutoLeyLineOutcropConfig fallback)
{
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
var (type, country) = dayOfWeek switch
{
DayOfWeek.Monday => (LeyLineMondayType, LeyLineMondayCountry),
DayOfWeek.Tuesday => (LeyLineTuesdayType, LeyLineTuesdayCountry),
DayOfWeek.Wednesday => (LeyLineWednesdayType, LeyLineWednesdayCountry),
DayOfWeek.Thursday => (LeyLineThursdayType, LeyLineThursdayCountry),
DayOfWeek.Friday => (LeyLineFridayType, LeyLineFridayCountry),
DayOfWeek.Saturday => (LeyLineSaturdayType, LeyLineSaturdayCountry),
DayOfWeek.Sunday => (LeyLineSundayType, LeyLineSundayCountry),
_ => (string.Empty, string.Empty)
};
if (string.IsNullOrWhiteSpace(type))
{
type = fallback.LeyLineOutcropType;
}
if (string.IsNullOrWhiteSpace(country))
{
country = fallback.Country;
}
return (type, country);
}
#endregion
}
}
+2 -42
View File
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -106,46 +106,6 @@ public partial class OtherConfig : ObservableObject
/// </summary>
[ObservableProperty]
private PaddleOcrModelConfig _paddleOcrModelConfig = PaddleOcrModelConfig.V4Auto;
/// <summary>
/// 允许OCR结果中出现连续重复字符(关闭CTC重复字符折叠)
/// </summary>
[ObservableProperty]
private bool _allowDuplicateChar;
/// <summary>
/// 切换队伍时使用 OcrMatch 模糊匹配代替正则表达式匹配
/// </summary>
[ObservableProperty]
private bool _useOcrMatchForPartySwitch = true;
/// <summary>
/// OcrMatch 模糊匹配的默认阈值 (0~1),分数 ≥ 阈值视为匹配成功
/// </summary>
[ObservableProperty]
private double _ocrMatchDefaultThreshold = 0.8;
partial void OnOcrMatchDefaultThresholdChanged(double value)
{
if (value is <= 0 or > 1)
{
OcrMatchDefaultThreshold = Math.Clamp(value, 0.01, 1);
}
}
/// <summary>
/// PaddleOCR 识别置信度阈值 (0~1),低于此阈值的字符将被过滤
/// </summary>
[ObservableProperty]
private double _paddleOcrThreshold = 0.5;
partial void OnPaddleOcrThresholdChanged(double value)
{
if (value is < 0 or >= 1)
{
PaddleOcrThreshold = Math.Clamp(value, 0, 0.99);
}
}
}
//public partial class OtherConfig : ObservableObject
@@ -161,4 +121,4 @@ public partial class OtherConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _uiCultureInfoName = "zh-Hans";
}
}
@@ -50,10 +50,4 @@ public partial class ScriptConfig : ObservableObject
// 仓库新手教程是否已阅读
[ObservableProperty] private bool _guideStatus = false;
// 是否在启动时自动更新已订阅的脚本
[ObservableProperty] private bool _autoUpdateSubscribedScripts = false;
// 命令行启动时是否先自动更新已订阅脚本再执行命令
[ObservableProperty] private bool _autoUpdateBeforeCommandLineRun = false;
}
@@ -16,9 +16,9 @@ public static class OcrUtils
/// 预处理速度比unsafe快5倍以上,且吃的资源还少
/// </summary>
/// <param name="inputImage">输入图像,若不是灰度图会转换</param>
/// <param name="tensorMemoryOwner">tensor的Memory,用完需要释放</param>
/// <param name="tensorMemoryOwnser">tensor的Memory,用完需要释放</param>
/// <returns></returns>
public static Tensor<float> ToTensorYapDnn(Mat inputImage, out IMemoryOwner<float> tensorMemoryOwner)
public static Tensor<float> ToTensorYapDnn(Mat inputImage, out IMemoryOwner<float> tensorMemoryOwnser)
{
using var rt = new ResourcesTracker();
Mat dst;
@@ -40,10 +40,10 @@ public static class OcrUtils
// 使用向量运算代替循环
var blob = rt.T(CvDnn.BlobFromImage(padded, 1.0 / 255.0, default, default, false, false));
var nCols = padded.Cols * padded.Rows;
tensorMemoryOwner = MemoryPool<float>.Shared.Rent(nCols);
tensorMemoryOwnser = MemoryPool<float>.Shared.Rent(nCols);
// 内存复制,如果直接传指针构建的话速度还不如多复制一份
blob.AsSpan<float>().CopyTo(tensorMemoryOwner.Memory.Span);
return new DenseTensor<float>(tensorMemoryOwner.Memory[..nCols], [1, 1, 32, 384]);
blob.AsSpan<float>().CopyTo(tensorMemoryOwnser.Memory.Span);
return new DenseTensor<float>(tensorMemoryOwnser.Memory[..nCols], [1, 1, 32, 384]);
}
/// <summary>
@@ -180,119 +180,6 @@ public static class OcrUtils
};
}
/// <summary>
/// 从标签列表构建字符串→索引字典,供 Rec 模糊匹配使用。
/// 索引从1开始(0为CTC空白符),空格字符为 labels.Count+1。
/// </summary>
/// <param name="labels">识别模型的标签列表</param>
/// <param name="labelLengths">各标签的字符长度集合(降序排列,用于从长到短贪心匹配)</param>
public static IReadOnlyDictionary<string, int> CreateLabelDict(
IReadOnlyList<string> labels, out int[] labelLengths)
{
var dict = new Dictionary<string, int>();
var lengths = new HashSet<int>();
for (var i = 0; i < labels.Count; i++)
{
if (labels[i] == " ") continue;
var len = labels[i].Length;
if (len > 0) lengths.Add(len);
dict[labels[i]] = i + 1;
}
// 空格字符对应索引 labels.Count + 1
dict[" "] = labels.Count + 1;
lengths.Add(1);
// 降序:先尝试更长的标签
labelLengths = lengths.OrderByDescending(x => x).ToArray();
return dict;
}
/// <summary>
/// 根据额外权重字典,创建与标签列表等长的权重数组(用于加权推理分数)。
/// 未指定权重的标签默认为 1.0。
/// </summary>
public static float[] CreateWeights(
Dictionary<string, float> extraWeights, IReadOnlyDictionary<string, int> labelDict, int labelCount)
{
var result = new float[labelCount + 2];
Array.Fill(result, 1.0f);
foreach (var (key, value) in extraWeights)
{
if (!labelDict.TryGetValue(key, out var index)) continue;
if (index >= 0 && index < result.Length)
{
result[index] = value;
}
}
return result;
}
/// <summary>
/// 将目标字符串映射为标签索引序列。
/// 使用贪心从长到短匹配,无法映射的字符会被跳过。
/// </summary>
/// <param name="target">目标字符串</param>
/// <param name="labelDict">标签→索引字典(由 CreateLabelDict 生成)</param>
/// <param name="labelLengths">标签长度集合,降序排列(由 CreateLabelDict 生成)</param>
public static int[] MapStringToLabelIndices(
string target,
IReadOnlyDictionary<string, int> labelDict,
int[] labelLengths)
{
var chars = target.ToCharArray();
var targetIndices = new int[chars.Length];
Array.Fill(targetIndices, -1);
var index = 0;
while (index < chars.Length)
{
var found = false;
foreach (var labelLength in labelLengths)
{
if (index + labelLength > chars.Length) continue;
var subStr = new string(chars, index, labelLength);
if (!labelDict.TryGetValue(subStr, out var labelIndex)) continue;
targetIndices[index] = labelIndex;
index += labelLength;
found = true;
break;
}
if (!found) index++;
}
return targetIndices.Where(x => x != -1).ToArray();
}
/// <summary>
/// 动态规划最大子序列匹配。
/// 在 result 序列中找到 target 的最大置信度子序列匹配,返回归一化分数 (0~1)。
/// </summary>
/// <param name="result">OCR 输出的 (labelIndex, confidence) 序列</param>
/// <param name="target">目标标签索引序列</param>
/// <param name="availableCount">归一化分母(通常为 target.Length,得到每个目标字符的平均置信度)</param>
public static double GetMaxScoreDp((int, float)[] result, int[] target, int availableCount)
{
if (target.Length == 0 || availableCount <= 0) return 0;
var dp = new double[target.Length + 1];
dp[0] = 0;
for (var j = 1; j <= target.Length; j++)
dp[j] = -255d; // 不可达
foreach (var (index, confidence) in result)
{
// 逆序更新,避免同一 result 元素被多次使用
for (var j = target.Length; j >= 1; j--)
{
if (index != target[j - 1]) continue;
if (!(dp[j - 1] > -200)) continue; // 前序不可达
var newSum = dp[j - 1] + confidence;
if (newSum > dp[j]) dp[j] = newSum;
}
}
if (dp[target.Length] <= -200) return 0; // 无法完整匹配
return dp[target.Length] / availableCount;
}
public static Mat Tensor2Mat(Tensor<float> tensor)
{
var dimensions = tensor.Dimensions;
@@ -1,26 +0,0 @@
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition.OCR;
/// <summary>
/// 基于 DP 模糊匹配的 OCR 服务接口,返回匹配置信度分数 (0~1)。
/// 独立于 IOcrService,仅由支持模糊匹配的引擎实现。
/// </summary>
public interface IOcrMatchService
{
/// <summary>
/// 使用检测器定位文字区域后,对每个区域进行模糊匹配,返回最高置信度 (0~1)。
/// </summary>
/// <param name="mat">输入图像(推荐三通道 BGR)</param>
/// <param name="target">目标字符串</param>
/// <returns>匹配置信度,0 表示完全不匹配,1 表示完全匹配</returns>
double OcrMatch(Mat mat, string target);
/// <summary>
/// 不使用检测器,直接对整张图像进行模糊匹配,返回置信度 (0~1)。
/// </summary>
/// <param name="mat">输入图像(推荐三通道 BGR)</param>
/// <param name="target">目标字符串</param>
/// <returns>匹配置信度,0 表示完全不匹配,1 表示完全匹配</returns>
double OcrMatchDirect(Mat mat, string target);
}
@@ -1,6 +1,5 @@
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR.Paddle;
@@ -19,27 +18,7 @@ public class OcrFactory : IDisposable
public static IOcrService Paddle => App.ServiceProvider.GetRequiredService<OcrFactory>().PaddleOcr;
private IOcrService PaddleOcr => _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
/// <summary>
/// 获取支持模糊匹配的 OCR 服务。
/// 若引擎原生支持 IOcrMatchService 则直接返回,否则回退到普通 OCR + 字符串相似度。
/// 访问此属性会触发 Paddle 引擎的懒加载。
/// </summary>
public static IOcrMatchService PaddleMatch
{
get
{
var factory = App.ServiceProvider.GetRequiredService<OcrFactory>();
var service = factory.PaddleOcr;
if (service is IOcrMatchService matchService)
return matchService;
var fallback = new OcrMatchFallbackService(service);
return Interlocked.CompareExchange(ref factory._paddleOcrMatchFallback, fallback, null)
?? fallback;
}
}
private IOcrService? _paddleOcrService;
private IOcrMatchService? _paddleOcrMatchFallback;
private readonly ILogger<BgiOnnxFactory> _logger;
private readonly OtherConfig.Ocr _config;
@@ -108,33 +87,34 @@ public class OcrFactory : IDisposable
private PaddleOcrService CreatePaddleOcrInstance()
{
var allowDuplicateChar = _config.AllowDuplicateChar;
var threshold = (float)_config.PaddleOcrThreshold;
var factory = App.ServiceProvider.GetRequiredService<BgiOnnxFactory>();
return _config.PaddleOcrModelConfig switch
{
PaddleOcrModelConfig.V4Auto =>
new PaddleOcrService(factory,
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
PaddleOcrService.PaddleOcrModelType.V4,
allowDuplicateChar, threshold),
PaddleOcrService.PaddleOcrModelType.V4),
PaddleOcrModelConfig.V5Auto =>
new PaddleOcrService(factory,
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
PaddleOcrService.PaddleOcrModelType.V5,
allowDuplicateChar, threshold),
PaddleOcrService.PaddleOcrModelType.V5),
PaddleOcrModelConfig.V5 =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5),
PaddleOcrModelConfig.V4 =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V4, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V4),
PaddleOcrModelConfig.V4En =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V4En, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V4En),
PaddleOcrModelConfig.V5Korean =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Korean, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5Korean),
PaddleOcrModelConfig.V5Latin =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Latin, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5Latin),
PaddleOcrModelConfig.V5Eslav =>
new PaddleOcrService(factory, PaddleOcrService.PaddleOcrModelType.V5Eslav, allowDuplicateChar, threshold),
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5Eslav),
_ => throw new ArgumentOutOfRangeException(nameof(_config.PaddleOcrModelConfig),
_config.PaddleOcrModelConfig, "不支持的 Paddle OCR 模型配置")
};
@@ -143,7 +123,6 @@ public class OcrFactory : IDisposable
public Task Unload()
{
_paddleOcrMatchFallback = null;
if (_paddleOcrService is not IDisposable disposable)
{
_paddleOcrService = null;
@@ -1,99 +0,0 @@
using System;
using System.Diagnostics;
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition.OCR;
/// <summary>
/// 当 OCR 引擎不支持 IOcrMatchService 时的回退实现。
/// 使用普通 OCR 识别文字后,通过字符串相似度进行匹配。
/// </summary>
public class OcrMatchFallbackService : IOcrMatchService
{
private readonly IOcrService _ocrService;
public OcrMatchFallbackService(IOcrService ocrService)
{
_ocrService = ocrService;
}
public double OcrMatch(Mat mat, string target)
{
var startTime = Stopwatch.GetTimestamp();
var ocrResult = _ocrService.OcrResult(mat);
var score = ComputeBestTextSimilarity(ocrResult, target);
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"OcrMatchFallback 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
return score;
}
public double OcrMatchDirect(Mat mat, string target)
{
var startTime = Stopwatch.GetTimestamp();
var text = _ocrService.OcrWithoutDetector(mat);
var score = ComputeTextSimilarity(text, target);
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"OcrMatchDirectFallback 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
return score;
}
/// <summary>
/// 在 OCR 结果的所有区域中找到与目标字符串最相似的分数。
/// </summary>
private static double ComputeBestTextSimilarity(OcrResult ocrResult, string target)
{
double bestScore = 0;
foreach (var region in ocrResult.Regions)
{
var score = ComputeTextSimilarity(region.Text, target);
if (score > bestScore) bestScore = score;
if (score >= 1.0) break;
}
return bestScore;
}
/// <summary>
/// 计算两个字符串的相似度 (0~1)。
/// 优先检查子串包含关系,否则使用编辑距离计算。
/// </summary>
public static double ComputeTextSimilarity(string text, string target)
{
if (string.IsNullOrEmpty(target)) return 1.0;
if (string.IsNullOrEmpty(text)) return 0.0;
if (text.Contains(target, StringComparison.OrdinalIgnoreCase)) return 1.0;
if (target.Contains(text, StringComparison.OrdinalIgnoreCase)) return (double)text.Length / target.Length;
var distance = LevenshteinDistance(text, target);
var maxLen = Math.Max(text.Length, target.Length);
return 1.0 - (double)distance / maxLen;
}
/// <summary>
/// 计算两个字符串之间的编辑距离(Levenshtein Distance)。
/// </summary>
public static int LevenshteinDistance(string s, string t)
{
var sLen = s.Length;
var tLen = t.Length;
var prev = new int[tLen + 1];
var curr = new int[tLen + 1];
for (var j = 0; j <= tLen; j++)
prev[j] = j;
for (var i = 1; i <= sLen; i++)
{
curr[0] = i;
for (var j = 1; j <= tLen; j++)
{
var cost = s[i - 1] == t[j - 1] ? 0 : 1;
curr[j] = Math.Min(Math.Min(curr[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);
}
(prev, curr) = (curr, prev);
}
return prev[tLen];
}
}
@@ -30,7 +30,15 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
/// <summary>Gets or sets the ratio for enlarging text boxes during post-processing.</summary>
public float UnclipRatio { get; set; } = 2.0f;
~Det()
{
lock (_session)
{
_session.Dispose();
}
}
public void Dispose()
{
lock (_session)
@@ -7,7 +7,6 @@ using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using YamlDotNet.Core;
@@ -16,7 +15,7 @@ using Size = OpenCvSharp.Size;
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
public class PaddleOcrService : IOcrService, IDisposable
{
/// <summary>
/// Usage:
@@ -104,11 +103,11 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
TestImagePath);
}
public (Det, Rec) Build(BgiOnnxFactory onnxFactory, bool allowDuplicateChar = false, float threshold = 0.5f)
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
{
return (
new Det(DetectionModel, DetectionVersion, onnxFactory),
new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory, allowDuplicateChar, threshold: threshold));
new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory));
}
public static readonly PaddleOcrModelType V4 = Create(
@@ -240,15 +239,14 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
}
}
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType,
bool allowDuplicateChar = false, float threshold = 0.5f)
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType)
{
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory, allowDuplicateChar, threshold);
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory);
_localDetModel = modelsDet;
_localRecModel = modelsRec;
// 预热模型
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
// Debug输出结果
var preHeatResult = RunAll(preHeatImageMat, 1);
@@ -269,8 +267,13 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
/// </summary>
public OcrResult OcrResult(Mat mat)
{
using var converted = ConvertBgrIfNeeded(mat);
return _OcrResult(converted ?? mat);
if (mat.Channels() == 4)
{
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
return _OcrResult(mat3);
}
return _OcrResult(mat);
}
/// <summary>
@@ -335,61 +338,6 @@ public class PaddleOcrService : IOcrService, IOcrMatchService, IDisposable
Math.Clamp(rect.Bottom, 0, size.Height));
}
/// <summary>
/// 若输入为 BGRA 则转换为 BGR,否则返回 null。
/// 调用方需在使用后 Dispose 返回的 Mat(若非 null)。
/// </summary>
private static Mat? ConvertBgrIfNeeded(Mat mat)
{
return mat.Channels() == 4 ? mat.CvtColor(ColorConversionCodes.BGRA2BGR) : null;
}
/// <summary>
/// 使用检测器定位文字区域后,对每个区域进行 DP 模糊匹配,返回最高置信度 (0~1)。
/// </summary>
public double OcrMatch(Mat mat, string target)
{
var startTime = Stopwatch.GetTimestamp();
using var src = ConvertBgrIfNeeded(mat);
var bgr = src ?? mat;
var rects = _localDetModel.Run(bgr);
Mat[] mats = rects.Select(rect =>
{
var roi = bgr[GetCropedRect(rect.BoundingRect(), bgr.Size())];
return roi;
}).ToArray();
try
{
var score = _localRecModel.RunMatch(mats, target);
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"PaddleOcrMatch 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
return score;
}
finally
{
foreach (var m in mats) m.Dispose();
}
}
/// <summary>
/// 不使用检测器,直接对整张图像进行 DP 模糊匹配,返回置信度 (0~1)。
/// </summary>
public double OcrMatchDirect(Mat mat, string target)
{
var startTime = Stopwatch.GetTimestamp();
using var src = ConvertBgrIfNeeded(mat);
var bgr = src ?? mat;
var score = _localRecModel.RunMatch([bgr], target);
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"PaddleOcrMatchDirect 耗时 {time.TotalMilliseconds}ms 目标: {target} 分数: {score:F4}");
return score;
}
public void Dispose()
{
_localDetModel.Dispose();
@@ -7,66 +7,22 @@ using System.Text;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Helpers;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
/// <summary>
/// OCR 识别器,支持标准文字识别和基于动态规划的模糊匹配。
/// 模糊匹配将目标字符串与模型原始输出序列做子序列匹配,返回 0~1 的置信度分数,
/// 比先识别再字符串匹配更能容忍 OCR 噪声。
/// </summary>
public class Rec : IDisposable
public class Rec(
BgiOnnxModel model,
IReadOnlyList<string> labels,
OcrVersionConfig config,
BgiOnnxFactory bgiOnnxFactory)
: IDisposable
{
private readonly InferenceSession _session;
private readonly IReadOnlyList<string> _labels;
private readonly OcrVersionConfig _config;
private readonly bool _allowDuplicateChar;
private readonly float _threshold;
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
// 模糊匹配相关字段
/// <summary>标签长度集合(降序),用于从长到短贪心匹配目标字符串</summary>
private readonly int[] _labelLengths;
/// <summary>标签字符串→索引字典,索引从1开始(0为CTC空白符)</summary>
private readonly IReadOnlyDictionary<string, int> _labelDict;
/// <summary>按标签索引的权重数组,用于加权推理分数;为 null 时不加权</summary>
private readonly float[]? _weights;
/// <summary>目标字符串→标签索引序列的 LRU 缓存,加速重复查询</summary>
private readonly CacheHelper.LruCache<string, int[]> _targetCache = new(128);
/// <summary>
/// ONNX 推理输出的命名张量结构,替代匿名元组 (int[], float[])。
/// </summary>
private readonly record struct TensorResult(int Batch, int TimeSteps, int LabelCount, float[] Data);
public Rec(
BgiOnnxModel model,
IReadOnlyList<string> labels,
OcrVersionConfig config,
BgiOnnxFactory bgiOnnxFactory,
bool allowDuplicateChar = false,
Dictionary<string, float>? extraWeights = null,
float threshold = 0.5f)
{
_session = bgiOnnxFactory.CreateInferenceSession(model, true);
_labels = labels;
_config = config;
_allowDuplicateChar = allowDuplicateChar;
_threshold = threshold;
_labelDict = OcrUtils.CreateLabelDict(labels, out var labelLengths);
_labelLengths = labelLengths;
_weights = extraWeights is { Count: > 0 }
? OcrUtils.CreateWeights(extraWeights, _labelDict, labels.Count)
: null;
}
// _labels = File.ReadAllLines(labelFilePath);
public void Dispose()
{
@@ -77,14 +33,42 @@ public class Rec : IDisposable
GC.SuppressFinalize(this);
}
~Rec()
{
lock (_session)
{
_session.Dispose();
}
}
/// <summary>
/// 对多张图像按批次执行 OCR 识别。
/// Run OCR recognition on multiple images in batches.
/// </summary>
/// <param name="srcs">Array of images for OCR recognition.</param>
/// <param name="batchSize">Size of the batch to run OCR recognition on.</param>
/// <returns>Array of <see cref="OcrRecognizerResult" /> instances corresponding to OCR recognition results of the images.</returns>
public OcrRecognizerResult[] Run(Mat[] srcs, int batchSize = 0)
=> RunBatch(srcs, RunMulti, batchSize);
{
if (srcs.Length == 0) return [];
var chooseBatchSize = batchSize != 0 ? batchSize : Math.Min(8, Environment.ProcessorCount);
return srcs
.Select((x, i) => (mat: x, i))
.OrderBy(x => x.mat.Width)
.Chunk(chooseBatchSize)
.Select(x => (result: RunMulti(x.Select(x1 => x1.mat).ToArray()), ids: x.Select(x1 => x1.i).ToArray()))
.SelectMany(x => x.result.Zip(x.ids, (result, i) => (result, i)))
.OrderBy(x => x.i)
.Select(x => x.result)
.ToArray();
}
public OcrRecognizerResult Run(Mat src)
=> RunMulti([src]).Single();
{
return RunMulti([src]).Single();
}
private OcrRecognizerResult[] RunMulti(Mat[] srcs)
{
@@ -97,224 +81,106 @@ public class Rec : IDisposable
throw new ArgumentException($"src[{i}] size should not be 0, wrong input picture provided?");
}
var resultTensors = RunInference(srcs);
return resultTensors.SelectMany(tensor =>
{
return Enumerable.Range(0, tensor.Batch)
.Select(i =>
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
var batchOffset = i * tensor.TimeSteps * tensor.LabelCount;
for (var n = 0; n < tensor.TimeSteps; ++n)
{
var rowOffset = batchOffset + n * tensor.LabelCount;
var maxVal = float.MinValue;
var maxIndex = 0;
for (var c = 0; c < tensor.LabelCount; c++)
{
var value = tensor.Data[rowOffset + c];
if (value > maxVal)
{
maxVal = value;
maxIndex = c;
}
}
if (maxIndex > 0 && maxVal >= _threshold && (_allowDuplicateChar || !(n > 0 && maxIndex == lastIndex)))
{
score += maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIndex, _labels));
}
lastIndex = maxIndex;
}
var text = sb.ToString();
return new OcrRecognizerResult(text, text.Length > 0 ? score / text.Length : 0);
})
.ToArray();
}).ToArray();
}
/// <summary>
/// 将目标字符串转换为标签索引序列,利用 LRU 缓存加速重复查询。
/// 无法映射到标签的字符会被跳过。
/// </summary>
public int[] GetTarget(string target)
{
if (_targetCache.TryGet(target, out var cached) && cached is not null)
return cached;
var result = OcrUtils.MapStringToLabelIndices(target, _labelDict, _labelLengths);
_targetCache.Set(target, result);
return result;
}
/// <summary>
/// 对一批图像执行模糊匹配,返回与目标字符串的最大平均置信度 (0~1)。
/// </summary>
/// <param name="srcs">待匹配图像数组</param>
/// <param name="target">目标字符串</param>
/// <param name="batchSize">每批推理图像数,0表示自动</param>
public double RunMatch(Mat[] srcs, string target, int batchSize = 0)
{
if (srcs.Length == 0) return 0;
var targetIndexes = GetTarget(target);
if (targetIndexes.Length == 0) return 0;
var charLevelResults = RunBatch(srcs,
mats => ProcessForMatch(RunInference(mats), targetIndexes), batchSize);
return GetMaxScoreFlat(charLevelResults, targetIndexes);
}
/// <summary>
/// 从 ONNX 原始输出张量中提取目标字符在每个时间步的置信度。
/// <para>
/// 与 RunMulti(标准 OCR)不同,此方法不做 argmax(MinMaxIdx),
/// 而是按目标字符的 label 索引直接查找对应位置的原始置信度。
/// 这样即使目标字符不是某个时间步的最高置信度候选,DP 仍然能拿到其实际分数进行匹配。
/// </para>
/// </summary>
/// <param name="resultTensors">RunInference 返回的 (shape, data) 张量数组</param>
/// <param name="targetIndexes">目标字符串映射后的 label 索引序列</param>
/// <returns>每张图像对应一个 (labelIndex, confidence) 数组,供 DP 匹配使用</returns>
private (int, float)[][] ProcessForMatch(TensorResult[] resultTensors, int[] targetIndexes)
{
// 目标字符去重(排除 CTC 空白符 index=0)
var targetSet = new HashSet<int>(targetIndexes);
targetSet.Remove(0);
return resultTensors.Select(tensor =>
{
var chars = new List<(int, float)>();
for (var n = 0; n < tensor.TimeSteps * tensor.Batch; n++)
{
// 直接按索引查找目标字符的置信度,而非对整行取 argmax
var rowOffset = n * tensor.LabelCount;
foreach (var labelIdx in targetSet)
{
if (labelIdx >= tensor.LabelCount) continue;
var raw = tensor.Data[rowOffset + labelIdx];
var confidence = _weights is not null
? raw * _weights[labelIdx]
: raw;
if (confidence > _threshold)
chars.Add((labelIdx, confidence));
}
}
return chars.ToArray();
}).ToArray();
}
/// <summary>
/// 将多张图像的字符级别结果展平后,计算与 target 的最大匹配分数。
/// 分母使用 target.Length,得到的是每个目标字符的平均置信度 (0~1)。
/// </summary>
private static double GetMaxScoreFlat((int, float)[][] result, int[] target)
{
var flatResult = result.SelectMany(x => x).ToArray();
return OcrUtils.GetMaxScoreDp(flatResult, target, target.Length);
}
/// <summary>
/// 通用批处理:按宽度排序、分批推理、恢复原始顺序
/// </summary>
private T[] RunBatch<T>(Mat[] srcs, Func<Mat[], T[]> process, int batchSize = 0)
{
if (srcs.Length == 0) return [];
var chooseBatchSize = batchSize != 0 ? batchSize : Math.Min(8, Environment.ProcessorCount);
return srcs
.Select((x, i) => (mat: x, i))
.OrderBy(x => x.mat.Width)
.Chunk(chooseBatchSize)
.Select(chunk =>
{
var mats = chunk.Select(x => x.mat).ToArray();
var result = process(mats);
return (result, ids: chunk.Select(x => x.i).ToArray());
})
.SelectMany(x => x.result.Zip(x.ids, (r, i) => (r, i)))
.OrderBy(x => x.i)
.Select(x => x.r)
.ToArray();
}
/// <summary>
/// 执行 ONNX 推理,返回每张图像的原始 (shape, data) 张量
/// </summary>
private TensorResult[] RunInference(Mat[] srcs)
{
var modelHeight = _config.Shape.Height;
var modelHeight = config.Shape.Height;
var maxWidth = (int)Math.Ceiling(srcs.Max(src =>
{
var size = src.Size();
return 1.0 * size.Width / size.Height * modelHeight;
}));
List<IMemoryOwner<float>> owners = [];
(int[], float[])[] resultTensors;
try
{
return srcs
resultTensors = srcs
// .AsParallel()
.Select(src =>
{
Mat? channel3 = default;
try
using var channel3 = src.Channels() switch
{
channel3 = src.Channels() switch
{
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
return result;
}
finally
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
if (channel3 != null && !ReferenceEquals(channel3, src))
{
channel3.Dispose();
}
owners.Add(owner);
}
return result;
})
.Select(inputTensor =>
{
lock (_session)
{
// 多线程推理会出现问题,加锁解决。
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
]);
var output = results[0];
if (output.ElementType is not TensorElementType.Float)
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
lock (_session)
{
// 多线程推理会出现问题,加锁解决。
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
]);
var output = results[0];
if (output.ElementType is not TensorElementType.Float)
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
var tensor = output.AsTensor<float>();
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
var dims = tensor.Dimensions;
return new TensorResult(dims[0], dims[1], dims[2], tensor.ToArray());
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
var tensor = output.AsTensor<float>();
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
return (tensor.Dimensions.ToArray(), tensor.ToArray());
}
}
}).ToArray();
).ToArray();
}
finally
{
owners.ForEach(x => { x.Dispose(); });
}
return resultTensors.SelectMany(resultTensor =>
{
var resultArray = resultTensor.Item2;
var resultShape = resultTensor.Item1;
GCHandle dataHandle = default;
try
{
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
var dataPtr = dataHandle.AddrOfPinnedObject();
var labelCount = resultShape[2];
var charCount = resultShape[1];
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
for (var n = 0; n < charCount; ++n)
{
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
var maxIdx = new int[2];
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
{
score += (float)maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
}
lastIndex = maxIdx[1];
}
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
})
.ToArray();
}
finally
{
dataHandle.Free();
}
}).ToArray();
}
public string GetConfigName => _config.Name;
}
public string GetConfigName => config.Name;
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
@@ -8,9 +8,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
@@ -31,7 +31,7 @@ public class PickTextInference : ITextInference
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
_wordDictionary = JsonConvert.DeserializeObject<Dictionary<int, string>>(json) ??
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ??
throw new Exception("index_2_word.json deserialize failed");
}
@@ -116,4 +116,4 @@ public class PickTextInference : ITextInference
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
}
}
}
@@ -6,7 +6,7 @@ namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
public class TextInferenceFactory
{
public static readonly Lazy<ITextInference> Pick = new(() => Create(OcrEngineTypes.YapModel));
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
public static ITextInference Create(OcrEngineTypes type)
{
@@ -87,24 +87,4 @@ public static class CommonExtension
{
return list.ConvertAll(ToPoint2d);
}
/// <summary>
/// 将矩形钳位到指定尺寸范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, int maxWidth, int maxHeight)
{
int x1 = Math.Clamp(rect.X, 0, maxWidth);
int y1 = Math.Clamp(rect.Y, 0, maxHeight);
int x2 = Math.Clamp(rect.X + rect.Width, 0, maxWidth);
int y2 = Math.Clamp(rect.Y + rect.Height, 0, maxHeight);
return new Rect(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// 将矩形钳位到 Mat 范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, Mat mat)
{
return rect.ClampTo(mat.Cols, mat.Rows);
}
}
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
@@ -25,7 +24,7 @@ public static class Feature2DExtensions
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
{
Mat trainDescriptors = new();
var img = Bv.ImRead(trainImagePath, ImreadModes.Grayscale);
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
@@ -12,13 +12,11 @@ public class AutoPathingScript
{
private object? _config = null;
private string _rootPath;
private readonly LimitedFile _autoPathingFile;
public AutoPathingScript(string rootPath, object? config)
{
_config = config;
_rootPath = rootPath;
_autoPathingFile = new LimitedFile(Global.Absolute(@"User\AutoPathing"));
}
public async Task Run(string json)
@@ -61,40 +59,7 @@ public class AutoPathingScript
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
public async Task RunFileFromUser(string path)
{
var json = await AutoPathingFile.ReadText(path);
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
await Run(json);
}
/// <summary>
/// 判断 AutoPathing 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => AutoPathingFile.IsExists(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => AutoPathingFile.IsFile(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => AutoPathingFile.IsFolder(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => AutoPathingFile.ReadPathSync(subPath);
/// <summary>
/// LimitedFile 实例,用于操作 AutoPathing 目录
/// </summary>
private LimitedFile AutoPathingFile => _autoPathingFile;
}
@@ -1,34 +0,0 @@
using Microsoft.ClearScript;
using System;
using System.Reflection;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class CustomHostFunctions : HostFunctions
{
/// <summary>
/// 创建指定维度的交错数组变量
/// </summary>
/// <typeparam name="T">数组元素类型</typeparam>
/// <param name="dimensions">数组维度</param>
/// <returns>交错数组变量</returns>
public object NewVarOfArr<T>(int dimensions)
{
try
{
Type arrayType = typeof(T);
for (int i = 0; i < dimensions; i++)
{
arrayType = arrayType.MakeArrayType();
}
MethodInfo newVarMethod = typeof(HostFunctions).GetMethod(nameof(newVar))!;
MethodInfo genericMethod = newVarMethod.MakeGenericMethod(arrayType);
return genericMethod.Invoke(this, new object?[] { null })!;
}
catch (Exception ex)
{
throw new InvalidOperationException($"创建维度为 {dimensions} 的数组失败: {ex.Message}", ex);
}
}
}
@@ -4,7 +4,6 @@ using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoWood;
@@ -20,8 +19,6 @@ using System.Dynamic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -196,9 +193,6 @@ public class Dispatcher
await new AutoFishingTask(AutoFishingTaskParam.BuildFromSoloTaskConfig(soloTask.Config)).Start(
cancellationToken);
return null;
case "AutoCook":
await new AutoCookTask().Start(cancellationToken);
return null;
case "AutoEat":
{
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodName", (string?)null);
@@ -345,39 +339,4 @@ public class Dispatcher
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoFightTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动地脉花任务
/// </summary>
/// <param name="param">自动地脉花任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoLeyLineOutcropTask(AutoLeyLineOutcropParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动地脉花任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoLeyLineOutcropTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动幽境危战任务
/// </summary>
/// <param name="param">自动幽境危战任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoStygianOnslaughtTask(AutoStygianOnslaughtParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动幽境危战任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoStygianOnslaughtTask(param).Start(cancellationToken);
}
}
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
@@ -42,9 +40,6 @@ public class KeyMouseHook: IDisposable
private EventHandler<MouseEventExtArgs>? _mouseMoveExtHandler;
private EventHandler<MouseEventExtArgs>? _mouseWheelExtHandler;
private readonly object _mouseMoveLock = new();
private DateTime _lastProcessMouseMoveTime = DateTime.MinValue;
private readonly ILogger<KeyMouseHook> _logger = App.GetLogger<KeyMouseHook>();
/// <summary>
@@ -115,259 +110,182 @@ public class KeyMouseHook: IDisposable
}
}
private readonly System.Threading.Channels.Channel<Action> _eventChannel =
System.Threading.Channels.Channel.CreateBounded<Action>(
new System.Threading.Channels.BoundedChannelOptions(2048)
{
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
private readonly CancellationTokenSource _cts = new();
public KeyMouseHook()
{
// 启动后台事件处理器,确保不阻塞钩子线程
_ = Task.Run(async () =>
{
try
{
var reader = _eventChannel.Reader;
while (await reader.WaitToReadAsync(_cts.Token))
{
while (reader.TryRead(out var action))
{
try
{
action();
}
catch (Exception ex)
{
// 内部错误已在 action 闭包中通过 HandleCallbackException 处理
}
}
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex, "键鼠钩子后台处理器发生异常");
}
});
// 初始化事件处理程序
_keyDownHandler = (_, args) =>
{
if (_keyDownDataCallbacks.Count == 0 && _keyDownCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyDownDataCallbacksCopy = new List<ScriptObject>(_keyDownDataCallbacks);
var keyDownCodeCallbacksCopy = new List<ScriptObject>(_keyDownCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘按下回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
};
_keyUpHandler = (_, args) =>
{
if (_keyUpDataCallbacks.Count == 0 && _keyUpCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyUpDataCallbacksCopy = new List<ScriptObject>(_keyUpDataCallbacks);
var keyUpCodeCallbacksCopy = new List<ScriptObject>(_keyUpCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘释放回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
};
_mouseDownExtHandler = (_, args) =>
{
if (_mouseDownCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseDownCallbacksCopy = new List<ScriptObject>(_mouseDownCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标按下回调");
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
};
_mouseUpExtHandler = (_, args) =>
{
if (_mouseUpCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseUpCallbacksCopy = new List<ScriptObject>(_mouseUpCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseUpCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
}))
foreach (var callback in mouseUpCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标释放回调");
try
{
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
};
_mouseMoveExtHandler = (_, args) =>
{
if (_mouseMoveCallbacks.Count == 0) return;
var now = DateTime.Now;
if ((now - _lastProcessMouseMoveTime).TotalMilliseconds < 10) return;
_lastProcessMouseMoveTime = now;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseMoveCallbacksCopy = new List<ScriptObject>(_mouseMoveCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseMoveCallbacksCopy)
{
try
{
foreach (var callback in mouseMoveCallbacksCopy)
// 获取回调的间隔时间
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval))
{
try
// 获取上次调用时间
if (_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
lock (_mouseMoveLock)
// 计算时间差
var timeSpan = now - lastTime;
// 如果时间差大于等于间隔时间,则执行回调
if (timeSpan.TotalMilliseconds >= interval)
{
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval) &&
_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
var timeSpan = now - lastTime;
if (timeSpan.TotalMilliseconds >= interval)
{
callback.InvokeAsFunction(localX, localY);
_lastMouseMoveCallbackTimes[callback] = now;
}
}
callback.InvokeAsFunction(localX, localY);
// 更新上次调用时间
_lastMouseMoveCallbackTimes[callback] = now;
}
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标移动回调");
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
};
_mouseWheelExtHandler = (_, args) =>
{
if (_mouseWheelCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseWheelCallbacksCopy = new List<ScriptObject>(_mouseWheelCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var delta = args.Delta;
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseWheelCallbacksCopy)
{
try
{
callback.InvokeAsFunction(delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
}))
foreach (var callback in mouseWheelCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标滚轮回调");
try
{
callback.InvokeAsFunction(args.Delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
};
@@ -458,8 +376,6 @@ public class KeyMouseHook: IDisposable
{
if (disposing)
{
_cts.Cancel();
_eventChannel.Writer.TryComplete();
// 移除所有事件监听器
if (_keyDownHandler != null)
{
@@ -1,7 +1,5 @@
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.Core.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenCvSharp;
@@ -74,44 +72,6 @@ public class LimitedFile(string rootPath)
}
}
/// <summary>
/// 判断指定路径是否为文件
/// </summary>
/// <param name="path">文件路径(相对于根目录)</param>
/// <returns>如果是文件则返回 true,否则返回 false</returns>
public bool IsFile(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsFile 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定的文件或目录是否存在
/// </summary>
/// <param name="path">文件或目录路径(相对于根目录)</param>
/// <returns>如果存在返回 true,否则返回 false</returns>
public bool IsExists(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath) || Directory.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsExists 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// Normalize and validate a path.
/// </summary>
@@ -5,7 +5,6 @@ using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.BgiVision;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
@@ -13,9 +12,7 @@ using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
namespace BetterGenshinImpact.Core.Script;
@@ -75,19 +72,10 @@ public class EngineExtend
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
engine.AddHostType("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
//鼠标回调
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
// 添加C#的类型
engine.AddHostType(typeof(Task));
// 新的BvPage类
engine.AddHostType("BvPage", typeof(BvPage));
engine.AddHostType("BvLocator", typeof(BvLocator));
engine.AddHostType("BvImage", typeof(BvImage));
engine.AddHostObject("host", new CustomHostFunctions());
// 导入 JavaScript 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
@@ -216,9 +216,6 @@ public partial class ScriptGroupProject : ObservableObject
}
JsScriptSettingsObject ??= new ExpandoObject();
// 清理配置中的无效值
CleanInvalidSettingsValues();
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
await Project.ExecuteAsync(JsScriptSettingsObject, pathingPartyConfig);
}
@@ -339,67 +336,6 @@ public partial class ScriptGroupProject : ObservableObject
{
OnPropertyChanged(nameof(ScheduleDesc));
}
/// <summary>
/// 清理 JsScriptSettingsObject 中不在 settings.json 定义的 Options 列表中的无效值
/// </summary>
private void CleanInvalidSettingsValues()
{
if (Project == null || JsScriptSettingsObject == null)
{
return;
}
try
{
// 加载 settings.json 中定义的配置项
var settingItems = Project.Manifest.LoadSettingItems(Project.ProjectPath);
if (settingItems.Count == 0)
{
return;
}
var settingsDict = JsScriptSettingsObject as IDictionary<string, object?>;
if (settingsDict == null)
{
return;
}
// 遍历所有 multi-checkbox 类型的配置项
foreach (var item in settingItems.Where(i => i.Type == "multi-checkbox"))
{
if (!settingsDict.ContainsKey(item.Name))
{
continue;
}
// 获取当前保存的值
var savedValue = settingsDict[item.Name];
List<string>? checkedValues = null;
if (savedValue is List<string> stringList)
{
checkedValues = stringList;
}
else if (savedValue is List<object> objectList)
{
checkedValues = objectList.Select(i => (string)i).ToList();
settingsDict[item.Name] = checkedValues;
}
// 清理不在 Options 列表中的无效值
if (checkedValues != null && item.Options != null)
{
checkedValues.RemoveAll(value => !item.Options.Contains(value));
}
}
}
catch (Exception ex)
{
// 清理失败不影响脚本执行,只记录日志
TaskControl.Logger.LogDebug(ex, "清理JS脚本配置中的无效值时发生异常");
}
}
}
public class ScriptGroupProjectExtensions
@@ -1,145 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DocumentLoader
{
private readonly string _scriptRootPath;
public PackageDocumentLoader(string scriptRootPath)
{
_scriptRootPath = Path.GetFullPath(scriptRootPath);
}
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
if (targetPath == null || !File.Exists(targetPath))
{
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
}
// 处理 JS 文件的重写
if (Path.GetExtension(targetPath).ToLower() == ".js")
{
string content = await File.ReadAllTextAsync(targetPath);
string processedCode = RewriteScriptCode(content, targetPath);
return new StringDocument(new DocumentInfo(targetPath) { Category = ModuleCategory.Standard }, processedCode);
}
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
}
/// <summary>
/// js重写
/// </summary>
public string RewriteScriptCode(string code, string currentFilePath)
{
if (string.IsNullOrEmpty(code)) return code;
string result = code.Replace("../../../packages", "packages");
// 拦截资源导入
var resourceRegex = new Regex(@"import\s+([\w\d_*$]+|[\s\S]*?)\s+from\s+(['""])([^'""\n]+)(['""])");
result = resourceRegex.Replace(result, match =>
{
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? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
if (resourceFullPath != null && File.Exists(resourceFullPath))
{
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
bool isJs = resourceFullPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase);
bool isImage = IsImageFile(resourceFullPath);
// 图片 -> Mat
if (isImage)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadImageMatSync({quote}{normalizedPath}{quote});";
}
// 非 JS 资源 -> 文本内容
if (!isJs)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadTextSync({quote}{normalizedPath}{quote});";
}
}
return match.Value;
});
return result;
}
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
return ResolvePathInternal(settings.SearchPath, sourceInfo?.Name, specifier);
}
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
{
if (specifier.StartsWith("packages/", StringComparison.OrdinalIgnoreCase))
{
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
if (specifier.StartsWith("."))
{
if (!string.IsNullOrEmpty(referrer))
{
string? dir = Path.GetDirectoryName(referrer);
if (dir != null)
{
return ProbeFile(Path.GetFullPath(Path.Combine(dir, specifier)));
}
}
}
if (!string.IsNullOrEmpty(searchPath))
{
var paths = searchPath.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var p in paths)
{
string combined = Path.Combine(p, specifier);
string? found = ProbeFile(combined);
if (found != null) return found;
}
}
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
private string? ProbeFile(string path)
{
try
{
if (File.Exists(path)) return path;
if (File.Exists(path + ".js")) return path + ".js";
}
catch { }
return null;
}
private static bool IsImageFile(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string ext = Path.GetExtension(path).ToLower();
string[] imageExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp" };
return imageExtensions.Contains(ext);
}
}
}
@@ -2,10 +2,8 @@ using BetterGenshinImpact.Core.Config;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
@@ -71,24 +69,10 @@ public class ScriptProject
return scrollViewer;
}
private IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig)
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
{
V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
// packages 依赖和资源重载
var loader = new PackageDocumentLoader(ProjectPath);
engine.DocumentSettings.Loader = loader;
// 添加 packages 到搜索路径
var libraries = new HashSet<string>(Manifest.Library ?? Array.Empty<string>())
{
".",
"./packages"
};
var libraryList = libraries.ToList();
EngineExtend.InitHost(engine, ProjectPath, libraryList.ToArray(), partyConfig);
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
return engine;
}
@@ -99,10 +83,6 @@ public class ScriptProject
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine(partyConfig);
// 使用自定义加载器解析脚本文件
var loader = (PackageDocumentLoader)engine.DocumentSettings.Loader;
if (context != null)
{
// 写入配置的内容
@@ -110,19 +90,12 @@ public class ScriptProject
}
try
{
bool useModule = Manifest.Library.Length != 0 ||
code.Contains("import ", StringComparison.Ordinal) ||
code.Contains("export ", StringComparison.Ordinal);
if (useModule)
if (Manifest.Library.Length != 0)
{
// 清除Document缓存
DocumentLoader.Default.DiscardCachedDocuments();
string mainScriptPath = Path.Combine(ProjectPath, Manifest.Main);
string runtimeCode = loader.RewriteScriptCode(code, mainScriptPath);
var evaluation = engine.Evaluate(new DocumentInfo(mainScriptPath) { Category = ModuleCategory.Standard }, runtimeCode);
var evaluation = engine.Evaluate(new DocumentInfo { Category = ModuleCategory.Standard }, code);
if (evaluation is Task task) await task;
}
else
File diff suppressed because it is too large. Load diff
@@ -78,28 +78,6 @@ public sealed class RepoWebBridge
return await File.ReadAllTextAsync(userConfigPath);
}
/// <summary>
/// 获取当前仓库的已订阅脚本路径列表(JSON 数组)。
/// 相比 GetUserConfigJson() 更轻量,仅返回当前仓库的订阅路径。
/// </summary>
public string GetSubscribedScriptPaths()
{
try
{
var paths = ScriptRepoUpdater.GetSubscribedPathsForCurrentRepo();
if (paths.Count > 0)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(paths);
}
return "[]";
}
catch
{
return "[]";
}
}
public Task<string> GetFile(string relPath)
{
try
@@ -205,7 +183,7 @@ public sealed class RepoWebBridge
throw new FileNotFoundException("找不到原始 repo.json 文件");
}
string targetPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string targetPath = Path.Combine(ScriptRepoUpdater.ReposPath, "repo_updated.json");
File.Copy(repoJsonPath, targetPath, overwrite: true);
@@ -250,7 +228,10 @@ public sealed class RepoWebBridge
private static string GetRepoJsonPath()
{
string updatedRepoJsonPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string updatedRepoJsonPath = Path.Combine(
Path.GetDirectoryName(Path.Combine(ScriptRepoUpdater.ReposPath, "bettergi-scripts-list-git"))!,
"repo_updated.json"
);
if (File.Exists(updatedRepoJsonPath))
{
@@ -264,7 +245,7 @@ public sealed class RepoWebBridge
return repoJson ?? throw new FileNotFoundException("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
}
internal static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
private static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
{
foreach (JObject item in array.OfType<JObject>())
{
@@ -282,7 +263,7 @@ public sealed class RepoWebBridge
}
}
internal static void ResetHasUpdateFlag(JObject node)
private static void ResetHasUpdateFlag(JObject node)
{
if (node["hasUpdate"] is { Type: JTokenType.Boolean } hasUpdate &&
(bool)hasUpdate)
@@ -1,11 +1,17 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
namespace BetterGenshinImpact.GameTask.AutoCook;
/// <summary>
///自动烹饪配置
/// </summary>
[Serializable]
public partial class AutoCookConfig : ObservableObject
{
/// <summary>
/// 触发器是否启用
/// </summary>
[ObservableProperty]
private int _checkIntervalMs = 10;
private bool _enabled = false;
}
@@ -1,161 +0,0 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoCook;
public class AutoCookTask : ISoloTask
{
private readonly ILogger<AutoCookTask> _logger = App.GetLogger<AutoCookTask>();
private const int UiCheckIntervalMs = 400;
private const int PeakMinCount = 600; // 最小仙跳墙 700 多
private const int PeakTolerance = 20;
private const int PeakStableFrameCount = 3;
private const int TriggerDropCount = 300; // 正常是 400多
private static readonly Rect CookColorRect1080P = new(600, 660, 730, 190);
private static readonly Scalar TargetCookColor = new(255, 192, 64);
public string Name => "自动烹饪";
public async Task Start(CancellationToken ct)
{
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var checkIntervalMs = Math.Max(1, TaskContext.Instance().Config.AutoCookConfig.CheckIntervalMs);
var peakMinCount = (int)(PeakMinCount * assetScale);
var triggerDropCount = (int)(TriggerDropCount * assetScale);
var cookColorRect = ScaleRect(CookColorRect1080P, assetScale);
_logger.LogInformation("自动烹饪任务启动");
var lastUiCheckTime = DateTime.MinValue;
var inCookUi = false;
int? peakColorCount = null;
int? peakCandidate = null;
var peakCandidateStableFrames = 0;
while (!ct.IsCancellationRequested)
{
using var captureRegion = CaptureToRectArea();
var now = DateTime.UtcNow;
if (!inCookUi || (now - lastUiCheckTime).TotalMilliseconds >= UiCheckIntervalMs)
{
var currentInCookUi = IsInCookUi(captureRegion);
if (currentInCookUi != inCookUi)
{
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
}
inCookUi = currentInCookUi;
lastUiCheckTime = now;
if (!inCookUi)
{
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
}
else
{
if (Bv.ClickWhiteConfirmButton(captureRegion))
{
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
_logger.LogInformation("自动烹饪:{Text}", "自动点击确认");
}
}
}
if (inCookUi)
{
var currentColorCount = CountTargetColor(captureRegion, cookColorRect);
if (peakColorCount.HasValue)
{
if (currentColorCount <= peakColorCount.Value - triggerDropCount)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
_logger.LogInformation("自动烹饪:{Text}", $"烹饪条像素数量较峰值下降超过{triggerDropCount},按下空格。峰值:{peakColorCount.Value} 当前:{currentColorCount}");
ResetPeakState(ref peakColorCount, ref peakCandidate, ref peakCandidateStableFrames);
}
}
else if (TryBuildPeak(currentColorCount, peakMinCount, ref peakCandidate, ref peakCandidateStableFrames, out var builtPeak))
{
peakColorCount = builtPeak;
_logger.LogInformation("自动烹饪:{Text}", $"识别到完美烹饪条峰值像素数:{builtPeak}");
}
}
await Delay(checkIntervalMs, ct);
}
}
private static void ResetPeakState(ref int? peakColorCount, ref int? peakCandidate, ref int peakCandidateStableFrames)
{
peakColorCount = null;
peakCandidate = null;
peakCandidateStableFrames = 0;
}
private static bool TryBuildPeak(int currentColorCount, int peakMinCount, ref int? peakCandidate, ref int peakCandidateStableFrames, out int builtPeak)
{
builtPeak = 0;
if (currentColorCount <= peakMinCount)
{
peakCandidate = null;
peakCandidateStableFrames = 0;
return false;
}
if (!peakCandidate.HasValue)
{
peakCandidate = currentColorCount;
peakCandidateStableFrames = 1;
return false;
}
if (Math.Abs(currentColorCount - peakCandidate.Value) <= PeakTolerance)
{
peakCandidate = Math.Max(peakCandidate.Value, currentColorCount);
peakCandidateStableFrames++;
if (peakCandidateStableFrames >= PeakStableFrameCount && peakCandidate.Value > peakMinCount)
{
builtPeak = peakCandidate.Value;
peakCandidate = null;
peakCandidateStableFrames = 0;
return true;
}
return false;
}
peakCandidate = currentColorCount;
peakCandidateStableFrames = 1;
return false;
}
private static Rect ScaleRect(Rect rect, double scale)
{
return new Rect(
(int)(rect.X * scale),
(int)(rect.Y * scale),
(int)(rect.Width * scale),
(int)(rect.Height * scale));
}
private bool IsInCookUi(ImageRegion captureRegion)
{
using var cookIcon = captureRegion.Find(ElementAssets.Instance.UiLeftTopCookIcon);
return cookIcon.IsExist();
}
private int CountTargetColor(ImageRegion captureRegion, Rect cookColorRect)
{
using var crop = captureRegion.DeriveCrop(cookColorRect);
using var rgb = new Mat();
using var mask = new Mat();
Cv2.CvtColor(crop.SrcMat, rgb, ColorConversionCodes.BGR2RGB);
Cv2.InRange(rgb, TargetCookColor, TargetCookColor, mask);
return Cv2.CountNonZero(mask);
}
}
@@ -0,0 +1,54 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System.Linq;
namespace BetterGenshinImpact.GameTask.AutoCook;
public class AutoCookTrigger : ITaskTrigger
{
private readonly ILogger<AutoCookTrigger> _logger = App.GetLogger<AutoCookTrigger>();
public string Name => "自动烹饪";
public bool IsEnabled { get; set; }
public int Priority => 50;
public bool IsExclusive { get; set; }
public void Init()
{
IsEnabled = TaskContext.Instance().Config.AutoCookConfig.Enabled;
IsExclusive = false;
}
public void OnCapture(CaptureContent content)
{
// 判断是否处于烹饪界面
IsExclusive = false;
content.CaptureRectArea.Find(ElementAssets.Instance.UiLeftTopCookIcon, _ =>
{
IsExclusive = true;
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
using var region = content.CaptureRectArea.DeriveCrop(0, captureRect.Height / 2, captureRect.Width, captureRect.Height / 2);
var perfectBarRects = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 192, 64), 0, 8);
if (perfectBarRects.Count >= 2)
{
// 点击烹饪按钮
var btnList = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 255, 192), 12, 12);
if (btnList.Count >= 1)
{
if (btnList.Count > 1)
{
_logger.LogWarning("自动烹饪:{Text}", "识别到多个结束烹饪按钮");
btnList = [.. btnList.OrderByDescending(r => r.Width)];
}
var btn = btnList[0];
var x = btn.X + btn.Width / 2;
var y = btn.Y + btn.Height / 2;
region.ClickTo(x, y);
_logger.LogInformation("自动烹饪:{Text}", "点击结束按钮");
}
}
});
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

@@ -1,49 +0,0 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.AutoDomain.Assets;
public class AutoDomainAssets : BaseAssets<AutoDomainAssets>
{
public RecognitionObject ResinSwitchBtnRo;
public RecognitionObject ResinSwitchBtnNoActiveRo;
private AutoDomainAssets() : base()
{
Initialization(this.systemInfo);
}
protected AutoDomainAssets(ISystemInfo systemInfo) : base(systemInfo)
{
Initialization(systemInfo);
}
private void Initialization(ISystemInfo systemInfo)
{
// 可点击状态的树脂切换按钮
ResinSwitchBtnRo = new RecognitionObject
{
Name = "ResinSwitchBtn",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoDomain", "resin_switch_btn.png", this.systemInfo),
RegionOfInterest = new Rect((int)(960 * AssetScale), (int)(430 * AssetScale), (int)(400 * AssetScale), (int)(130 * AssetScale)),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
// 不可点击状态的树脂切换按钮
ResinSwitchBtnNoActiveRo = new RecognitionObject
{
Name = "ResinSwitchBtnNoActive",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoDomain", "resin_switch_btn_no_active.png", this.systemInfo),
RegionOfInterest = new Rect((int)(960 * AssetScale), (int)(430 * AssetScale), (int)(400 * AssetScale), (int)(130 * AssetScale)),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
}
}
@@ -68,13 +68,6 @@ public partial class AutoDomainConfig : ObservableObject
// 使用原粹树脂刷取副本次数
[ObservableProperty]
private int _originalResinUseCount = 0;
// 使用原粹树脂(20)刷取副本次数
[ObservableProperty]
private int _originalResin20UseCount = 0;
// 使用原粹树脂(40)刷取副本次数
[ObservableProperty]
private int _originalResin40UseCount = 0;
//使用浓缩树脂刷取副本次数
[ObservableProperty]
@@ -34,13 +34,9 @@ public class AutoDomainParam : BaseTaskParam<AutoDomainTask>
"浓缩树脂",
"原粹树脂"
];
// 使用原粹树脂刷取副本次数
public int OriginalResinUseCount { get; set; } = 0;
// 使用原粹树脂(20)刷取副本次数
public int OriginalResin20UseCount { get; set; } = 0;
// 使用原粹树脂(40)刷取副本次数
public int OriginalResin40UseCount { get; set; } = 0;
// 使用浓缩树脂刷取副本次数
public int CondensedResinUseCount { get; set; } = 0;
@@ -77,8 +73,6 @@ public class AutoDomainParam : BaseTaskParam<AutoDomainTask>
TransientResinUseCount = config.TransientResinUseCount;
FragileResinUseCount = config.FragileResinUseCount;
SpecifyResinUse = config.SpecifyResinUse;
OriginalResin20UseCount = config.OriginalResin20UseCount;
OriginalResin40UseCount = config.OriginalResin40UseCount;
}
public AutoDomainParam(int domainRoundNum = 0) : base(null, null)
@@ -41,7 +41,6 @@ using BetterGenshinImpact.GameTask.Common;
using Compunet.YoloSharp;
using Microsoft.Extensions.DependencyInjection;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoDomain.Assets;
namespace BetterGenshinImpact.GameTask.AutoDomain;
@@ -95,7 +94,7 @@ public class AutoDomainTask : ISoloTask
this.clickanywheretocloseLocalizedString = stringLocalizer.WithCultureGet(cultureInfo, "点击任意位置关闭");
this.matchingChallengeString = stringLocalizer.WithCultureGet(cultureInfo, "匹配挑战");
this.rapidformationString = stringLocalizer.WithCultureGet(cultureInfo, "快速编队");
this.limitedFullyString = stringLocalizer.WithCultureGet(cultureInfo, "限时全部开放");
this.limitedFullyString = stringLocalizer.WithCultureGet(cultureInfo, "限时全开");
this.limitedFullyAllString = stringLocalizer.WithCultureGet(cultureInfo, "限时开放");
}
@@ -382,7 +381,7 @@ public class AutoDomainTask : ISoloTask
using var limitedFullyStringRa = CaptureToRectArea();
var limitedFullyStringRaocrList =
limitedFullyStringRa.FindMulti(RecognitionObject.Ocr(0, 0, limitedFullyStringRa.Width * 0.5,
limitedFullyStringRa.Height * 0.5));
limitedFullyStringRa.Height));
var limitedFullyStringRaocrListdone = limitedFullyStringRaocrList.LastOrDefault(t =>
Regex.IsMatch(t.Text, this.limitedFullyString) || Regex.IsMatch(t.Text, this.limitedFullyAllString));
// 检测是否为限时全开秘境
@@ -457,7 +456,7 @@ public class AutoDomainTask : ISoloTask
// 点击单人挑战确认并等待队伍界面--使用图像模版匹配的方法,也可以使用文字OCR的方法识别“单人挑战”直到消失
await NewRetry.WaitForElementAppear(
ElementAssets.Instance.PartyBtnChooseView,
() =>
async void () =>
{
using var ra = CaptureToRectArea();
var ra2 = ra.Find(fightAssets.ConfirmRa);
@@ -1152,26 +1151,6 @@ public class AutoDomainTask : ISoloTask
{
if (record.RemainCount > 0)
{
if (record.Name == "原粹树脂20" || record.Name == "原粹树脂40")
{
int expectedNum = record.Name == "原粹树脂20" ? 20 : 40;
bool switched;
try
{
switched = SwitchOriginalResinType(expectedNum, _ct);
}
catch (RetryException)
{
Logger.LogWarning("自动秘境:切换原粹树脂类型重试超时,跳过 {Name}", record.Name);
switched = false;
}
if (!switched)
{
continue;
}
}
var (success, _) = PressUseResin(textListInPrompt2, record.Name);
if (success)
{
@@ -1279,11 +1258,6 @@ public class AutoDomainTask : ISoloTask
public static (bool, int) PressUseResin(List<Region> regionList, string resinName)
{
if (resinName == "原粹树脂20" || resinName == "原粹树脂40")
{
resinName = "原粹树脂";
}
var resinKey = regionList.FirstOrDefault(t => t.Text.Contains(resinName));
if (resinKey != null)
{
@@ -1319,46 +1293,6 @@ public class AutoDomainTask : ISoloTask
return (false, 0);
}
private bool SwitchOriginalResinType(int expectedNum, CancellationToken ct)
{
return NewRetry.Do(() =>
{
using var ra0 = CaptureToRectArea();
var regionList = ra0.FindMulti(RecognitionObject.Ocr(ra0.Width * 0.25, ra0.Height * 0.2, ra0.Width * 0.5, ra0.Height * 0.6));
var has20 = regionList.Any(t => t.Text.Contains("20"));
var has40 = regionList.Any(t => t.Text.Contains("40"));
if (expectedNum == 20 && has20)
{
Logger.LogInformation("自动秘境:已切换到使用20原粹树脂");
return true;
}
if (expectedNum == 40 && has40)
{
Logger.LogInformation("自动秘境:已切换到使用40原粹树脂");
return true;
}
//切换20/40原粹树脂的按钮是亮的
var clickable = ra0.Find(AutoDomainAssets.Instance.ResinSwitchBtnRo);
if (clickable.IsExist())
{
Logger.LogDebug("自动秘境:切换原粹树脂使用数量");
clickable.Click();
}
//切换20/40原粹树脂的按钮是暗的
var disabled = ra0.Find(AutoDomainAssets.Instance.ResinSwitchBtnNoActiveRo);
if (disabled.IsExist())
{
Logger.LogWarning("自动秘境:切换原粹树脂的使用数量失败,可能是体力不足,当前目标:{Num}", expectedNum);
return false; // 不可点击
}
throw new RetryException("未检测到按钮"); // 继续重试
}, TimeSpan.FromMilliseconds(500), 10);
}
private static int GetResinNum(Region region, string resinName)
{
if (resinName == "原粹树脂")
@@ -1401,7 +1335,7 @@ public class AutoDomainTask : ISoloTask
return (region1Top <= region2Bottom && region1Bottom >= region2Top);
}
private async Task ArtifactSalvage()
private async Task ArtifactSalvage()
{
if (!_taskParam.AutoArtifactSalvage)
{
@@ -32,14 +32,6 @@ public class ResinUseRecord
{
list.Add(new ResinUseRecord("浓缩树脂", taskParam.CondensedResinUseCount));
}
if (taskParam.OriginalResin40UseCount > 0)
{
list.Add(new ResinUseRecord("原粹树脂40", taskParam.OriginalResin40UseCount));
}
if (taskParam.OriginalResin20UseCount > 0)
{
list.Add(new ResinUseRecord("原粹树脂20", taskParam.OriginalResin20UseCount));
}
if (taskParam.OriginalResinUseCount > 0)
{
list.Add(new ResinUseRecord("原粹树脂", taskParam.OriginalResinUseCount));
@@ -62,7 +54,7 @@ public class ResinUseRecord
return list;
}
public static List<ResinUseRecord> BuildFromDomainParam(AutoStygianOnslaughtParam taskParam)
public static List<ResinUseRecord> BuildFromDomainParam(AutoStygianOnslaughtConfig taskParam)
{
List<ResinUseRecord> list = [];
if (taskParam.SpecifyResinUse)
@@ -2049,19 +2049,5 @@
"nameEn": "Illuga",
"skillCD": 15,
"weapon": "10"
},
{
"alias": [
"法尔伽",
"Varka",
"团长",
"法尔加"
],
"burstCD": 16,
"id": "10000128",
"name": "法尔伽",
"nameEn": "Varka",
"skillCD": 16,
"weapon": "10"
}
]
@@ -320,8 +320,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
if (retryCount == 0)
{
await Delay(delayTime,ct);
// Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
Logger.LogInformation("打开编队界面检查战斗是否结束");
Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
await Delay(detectDelayTime, ct);
var ra3 = CaptureToRectArea();
@@ -461,7 +460,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
{
while (attempt < retryCount)
{
if (guardianAvatar.TrySwitch(10))
if (guardianAvatar.TrySwitch(10, false))
{
guardianAvatar.ManualSkillCd = -1;
if (await AvatarSkillAsync(Logger, guardianAvatar, false, 1, ct))
@@ -550,7 +549,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight
Logger.LogInformation("优先第 {text} 盾奶位 {GuardianAvatar} 元素爆发状态:{attempt},尝试释放",
guardianAvatarName, guardianAvatar.Name, "就绪");
if (guardianAvatar.TrySwitch(8))
if (guardianAvatar.TrySwitch(8, false))
{
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
Sleep(500, ct);
@@ -418,7 +418,7 @@ public class AutoFightTask : ISoloTask
fightEndFlag = await CheckFightFinish(delayTime, detectDelayTime);
}
#endregion
command.Execute(combatScenes, lastCommand);
//统计战斗人次
if (i == combatCommands.Count - 1 || command.Name != combatCommands[i + 1].Name)
@@ -426,13 +426,6 @@ public class AutoFightTask : ISoloTask
countFight++;
}
#region check动作触发战斗结束检测
if (command.Method == Method.Check)
{
fightEndFlag = await CheckFightFinish(delayTime, detectDelayTime);
}
#endregion
lastFightName = command.Name;
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true })
{
@@ -451,7 +444,7 @@ public class AutoFightTask : ISoloTask
if (_finishDetectConfig.DelayTimes.TryGetValue(command.Name, out var time))
{
delayTime = time;
// Logger.LogInformation($"{command.Name}结束后,延时检查为{delayTime}毫秒");
Logger.LogInformation($"{command.Name}结束后,延时检查为{delayTime}毫秒");
}
else
{
@@ -505,13 +498,13 @@ public class AutoFightTask : ISoloTask
{
oldPartyName = RunnerContext.Instance.PartyName;
}
else if(picker is null && !string.IsNullOrEmpty(_taskParam.KazuhaPartyName))
else if (picker is null)
{
Logger.LogWarning("换队拾取:当前队伍名称为空,尝试读取!");
await Delay(1000, ct);
await _returnMainUiTask.Start(ct);
for (int attempt = 0; attempt < 6; attempt++)
for (int attempt = 0; attempt < 3; attempt++)
{
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
var enterGameAppear = await NewRetry.WaitForElementAppear(
@@ -521,68 +514,35 @@ public class AutoFightTask : ISoloTask
15,
500
);
if(attempt == 5 && !enterGameAppear)
if (attempt == 2)
{
Logger.LogWarning("换队拾取:读取队伍名称失败,跳过换队拾取步骤");
Logger.LogWarning("换队拾取:读取队伍名称失败!");
}
}
}
if (!string.IsNullOrEmpty(_taskParam.KazuhaPartyName)){
await Delay(1000, ct);
//等待寻找2秒队伍按钮出现
var timeWaitStart = 0;
while(timeWaitStart < 6000)
//等待寻找2秒队伍按钮出现
var timeWaitStart = 0;
while(timeWaitStart < 6000)
{
using var ra = CaptureToRectArea();
var partyViewBtn = ra.Find(ElementAssets.Instance.PartyBtnChooseView);
if (partyViewBtn.IsExist())
{
using var ra = CaptureToRectArea();
var partyViewBtn = ra.Find(ElementAssets.Instance.PartyBtnChooseView);
if (partyViewBtn.IsExist())
{
// OCR 当前队伍名称(无法单字,中间禁止空格)
// 读取OCR原始识别文本
var rawPartyName = ra.Find(new RecognitionObject
// OCR 当前队伍名称(无法单字,中间禁止空格)
oldPartyName = ra.Find(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect(partyViewBtn.Right, partyViewBtn.Top, (int)(350 * _assetScale),
partyViewBtn.Height)
}).Text;
// 核心处理逻辑:1.空值兜底 2.去首尾空白 3.移除末尾的“口”字(仅最后一个是口才删)
if (string.IsNullOrWhiteSpace(rawPartyName))
{
oldPartyName = string.Empty;
}
else
{
//有概率把编辑图标识别为字符,并且含有空格或换行符,需要过滤
var tempName = rawPartyName
.Replace("\"", "") // 移除所有双引号(核心新增,解决日志里的""问题)
.Replace("\r\n", "") // 清理Windows换行符
.Replace("\r", ""); // 先清理所有双引号,避免引号干扰后续处理
// 核心逻辑:找到第一个换行符(\n)的位置,截断并删除换行+后面所有字符
int firstNewLineIndex = tempName.IndexOf('\n');
if (firstNewLineIndex != -1) // 存在换行符,截取到换行符前
{
tempName = tempName.Substring(0, firstNewLineIndex);
}
// 最后统一去首尾所有空白(空格、制表符、回车符\r等),得到纯净队伍名
oldPartyName = tempName.Trim();
}
// 后续原有逻辑不变
Logger.LogInformation("换队拾取:当前队伍名称读取为:{oldPartyName}", oldPartyName);
// 加在rawPartyName赋值后,打印原始文本的“原始形态”(转义符会显示)
Logger.LogDebug("OCR原始识别文本(含转义):{rawPartyName}", rawPartyName);
Logger.LogInformation("换队拾取:当前队伍名称读取为:{oldPartyName}",oldPartyName);
RunnerContext.Instance.PartyName = oldPartyName;
// await _returnMainUiTask.Start(ct);
break;
}
await Delay(200, ct);
timeWaitStart += 200;
// await _returnMainUiTask.Start(ct);
break;
}
await Delay(200, ct);
timeWaitStart += 200;
}
var switchPartyFlag = false;
@@ -614,12 +574,7 @@ public class AutoFightTask : ISoloTask
if (picker.Name == "枫原万叶")
{
var time = TimeSpan.FromSeconds(picker.GetSkillCdSeconds());
// 如果配置了二次拾取,或者不满足跳过条件(上次是万叶且冷却时间>3秒),则执行拾取
bool shouldSkip = lastFightName == picker.Name && time.TotalSeconds > 3;
bool forcePickup = _taskParam.QinDoublePickUp;
if (forcePickup || !shouldSkip)
if (!(lastFightName == picker.Name && time.TotalSeconds > 3))
{
Logger.LogInformation("使用 枫原万叶-长E 拾取掉落物");
await Delay(200, ct);
@@ -736,7 +691,7 @@ public class AutoFightTask : ISoloTask
if (_taskParam is { PickDropsAfterFightEnabled: true } )
{
// 执行扫描掉落物光柱并靠近的功能
// 执行自动拾取掉落物的功能
await new ScanPickTask().Start(ct);
}
}
@@ -780,8 +735,7 @@ public class AutoFightTask : ISoloTask
if (!_finishDetectConfig.RotateFindEnemyEnabled)await Delay(delayTime, _ct);
// Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
Logger.LogInformation("打开编队界面检查战斗是否结束");
Logger.LogInformation("打开编队界面检查战斗是否结束,延时{detectDelayTime}毫秒检查", detectDelayTime);
// 最终方案确认战斗结束
Simulation.SendInput.SimulateAction(GIActions.OpenPartySetupScreen);
await Delay(detectDelayTime, _ct);
@@ -804,9 +758,8 @@ public class AutoFightTask : ISoloTask
return true;
}
// Logger.LogInformation($"未识别到战斗结束yellow{b3.Item0},{b3.Item1},{b3.Item2}");
// Logger.LogInformation($"未识别到战斗结束white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
Logger.LogInformation($"未识别到战斗结束: yellow{b3.Item0},{b3.Item1},{b3.Item2};white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
Logger.LogInformation($"未识别到战斗结束yellow{b3.Item0},{b3.Item1},{b3.Item2}");
Logger.LogInformation($"未识别到战斗结束white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
if (_finishDetectConfig.RotateFindEnemyEnabled)
{
@@ -909,4 +862,4 @@ public class AutoFightTask : ISoloTask
// // 要大于 gadgetMat 的 1/2
// return list.Any(r => r.Width > gadgetMat.Width / 2 && r.Height > gadgetMat.Height / 2);
// }
}
}
@@ -175,9 +175,8 @@ public class Avatar
/// </summary>
private static bool SwimmingConfirm(Region region)
{
using var imageRegion = region.ToImageRegion();
using var cropped = imageRegion.DeriveCrop(1819, 1025, 9, 11);
using var mask = OpenCvCommonHelper.Threshold(cropped.SrcMat, new Scalar(242, 223, 39), new Scalar(255, 233, 44));
using var mask = OpenCvCommonHelper.Threshold(region.ToImageRegion().DeriveCrop(1819, 1025, 9, 11).SrcMat,
new Scalar(242, 223, 39),new Scalar(255, 233, 44));
using var labels = new Mat();
using var stats = new Mat();
using var centroids = new Mat();
@@ -239,7 +238,7 @@ public class Avatar
/// <param name="tryTimes"></param>
/// <param name="needLog"></param>
/// <returns></returns>
public bool TrySwitch(int tryTimes = 4)
public bool TrySwitch(int tryTimes = 4, bool needLog = true)
{
var context = new AvatarActiveCheckContext();
for (var i = 0; i < tryTimes; i++)
@@ -255,15 +254,12 @@ public class Avatar
// 切换成功
if (CombatScenes.GetActiveAvatarIndex(region, context) == Index)
{
return true;
}
else
{
if (i == tryTimes - 1)
if (needLog && i > 0)
{
Logger.LogWarning("切换角色失败,最后一次尝试,当前角色编号:{CurrentIndex},期望角色编号:{ExpectedIndex}", CombatScenes.GetActiveAvatarIndex(region, context), Index);
region.SrcMat.SaveImage($"log/{Name}_切换失败.png");
Logger.LogInformation("成功切换角色:{Name}", Name);
}
return true;
}
@@ -271,8 +267,6 @@ public class Avatar
Sleep(250, Ct);
}
Logger.LogWarning("切换角色失败:{Name}", Name);
return false;
}
@@ -478,8 +472,8 @@ public class Avatar
var cd = AfterUseSkill(region);
if (cd > 0)
{
// Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd} 秒" : "{Name} 点按元素战技,cd:{Cd} 秒", Name,
// Math.Round(cd, 2));
Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd} 秒" : "{Name} 点按元素战技,cd:{Cd} 秒", Name,
Math.Round(cd, 2));
return;
}
}
@@ -641,7 +635,7 @@ public class Avatar
/// </summary>
public void Ready()
{
Sleep(10, Ct);
Sleep(200, Ct);
for (int i = 0; i < 20; i++)
{
@@ -177,48 +177,6 @@ public class CombatScenes : IDisposable
return this;
}
/// <summary>
/// 静默模式下的队伍识别(用于后台挂件)
/// </summary>
public CombatScenes InitializeTeamSilent(ImageRegion imageRegion, AutoFightConfig? autoFightConfig = null)
{
try
{
if (autoFightConfig == null)
{
autoFightConfig = TaskContext.Instance().Config.AutoFightConfig;
}
// 优先取配置
if (!string.IsNullOrEmpty(autoFightConfig.TeamNames))
{
InitializeTeamFromConfig(autoFightConfig.TeamNames, autoFightConfig);
return this;
}
// 使用 NullLogger 彻底屏蔽底层工具类的日志输出
var nullLogger = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
CurrentMultiGameStatus = PartyAvatarSideIndexHelper.DetectedMultiGameStatus(imageRegion, _autoFightAssets, nullLogger);
var (avatarIndexRectList, avatarSideIconRectList) = PartyAvatarSideIndexHelper.GetAllIndexRects(imageRegion, CurrentMultiGameStatus, nullLogger, _elementAssets, _systemInfo);
ExpectedTeamAvatarNum = avatarIndexRectList.Count;
var names = new string[avatarSideIconRectList.Count];
for (var i = 0; i < avatarSideIconRectList.Count; i++)
{
using var ra = imageRegion.DeriveCrop(avatarSideIconRectList[i]);
var pair = ClassifyAvatarCnName(ra.CacheImage, i + 1);
names[i] = pair.Item1;
}
Avatars = BuildAvatars([.. names], null, avatarIndexRectList, autoFightConfig);
}
catch
{
// 静默模式下完全不抛出、不记录异常
}
return this;
}
/// <summary>
/// 这个个方法主要用于在切人判断有误的情况下,且能够找到预期数量的角色编号框。此时只有两种情况
@@ -108,8 +108,7 @@ public class CombatCommand
&& Method != Method.KeyDown
&& Method != Method.KeyUp
&& Method != Method.KeyPress
&& Method != Method.Scroll
&& Method != Method.Ready)
&& Method != Method.Scroll)
{
avatar.Switch();
}
@@ -203,10 +202,6 @@ public class CombatCommand
{
avatar.Ready();
}
else if (Method == Method.Check)
{
// check动作在AutoFightTask主循环中处理,此处不做任何操作
}
else if (Method == Method.Aim)
{
throw new NotImplementedException();
@@ -28,9 +28,8 @@ public class CombatScriptBag(List<CombatScript> combatScripts)
}
if (matchCount != avatars.Count) continue;
// Logger.LogInformation("匹配到战斗脚本:{Name},共{Cnt}条指令,涉及角色:{Str}",
// combatScript.Name, combatScript.CombatCommands.Count, string.Join(",", combatScript.AvatarNames));
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
Logger.LogInformation("匹配到战斗脚本:{Name},共{Cnt}条指令,涉及角色:{Str}",
combatScript.Name, combatScript.CombatCommands.Count, string.Join(",", combatScript.AvatarNames));
return combatScript.CombatCommands;
}
@@ -13,7 +13,6 @@ public class Method
public static readonly Method Charge = new(["charge", "重击"]);
public static readonly Method Wait = new(["wait", "after", "等待"]);
public static readonly Method Ready = new(["ready", "完成"]);
public static readonly Method Check = new(["check", "检测"]);
public static readonly Method Walk = new(["walk", "行走"]);
public static readonly Method W = new(["w"]);
@@ -46,7 +45,6 @@ public class Method
yield return Charge;
yield return Wait;
yield return Ready;
yield return Check;
yield return Walk;
yield return W;
@@ -391,9 +391,6 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
clickWhiteConfirmButtonWaitEndTime < timeProvider.GetLocalNow()) &&
Bv.ClickWhiteConfirmButton(imageRegion))
{
// 截取鱼饵图标区域(正方形,宽高均取 6.5% 的屏幕宽度)
// 最后一个参数有意用 Width 而非 Height,目的是保持正方形裁剪
// 经验算在 16:9 常见分辨率(720p/1080p/1440p)下 Y+H 不会超出图像高度,暂不加钳位
using Mat subMat = imageRegion.SrcMat.SubMat(new Rect((int)(0.824 * imageRegion.Width), (int)(0.669 * imageRegion.Height), (int)(0.065 * imageRegion.Width), (int)(0.065 * imageRegion.Width)));
using Mat resized = subMat.Resize(new Size(125, 125));
(string predName, _) = GridIconsAccuracyTestTask.Infer(resized, this.session, this.prototypes);
@@ -151,7 +151,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
// 寻找鱼饵
var boxAndBaits = FindBait(imageRegion);
;
foreach ((Rect box, string? predName) in boxAndBaits)
{
if (predName == blackboard.selectedBait.GetDescription())
@@ -201,7 +201,6 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
else
{
blackboard.Sleep(200);
return BehaviourStatus.Running;
}
}
@@ -858,13 +857,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
int hExtra = _cur.Height, vExtra = _cur.Height / 4;
{
int rx = _cur.X - hExtra;
int ry = _cur.Y - vExtra;
int rw = (topMat.Width / 2 - _cur.X) * 2 + hExtra * 2;
int rh = _cur.Height + vExtra * 2;
blackboard.fishBoxRect = new Rect(rx, ry, rw, rh).ClampTo(imageRegion.SrcMat);
}
blackboard.fishBoxRect = new Rect(_cur.X - hExtra, _cur.Y - vExtra,
(topMat.Width / 2 - _cur.X) * 2 + hExtra * 2, _cur.Height + vExtra * 2);
using var boxRa = imageRegion.Derive(blackboard.fishBoxRect);
boxRa.DrawSelf("FishBox", System.Drawing.Pens.LightPink);
logger.LogInformation(" 识别到钓鱼框");
@@ -1001,7 +1001,7 @@
"nameEn": "escoffier",
"type": "character",
"name": "爱可菲",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "冰元素",
"weapon": "长柄武器",
@@ -1073,154 +1073,6 @@
}
]
},
{
"id": 1116,
"nameEn": "skirk",
"type": "character",
"name": "丝柯克",
"hp": 10,
"energy": 0,
"element": "冰元素",
"weapon": "单手剑",
"skills": [
{
"nameEn": "havoc_sunder",
"name": "极恶技·断",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "havoc_warp",
"name": "极恶技·闪",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 2
}
]
},
{
"nameEn": "havoc_ruin",
"name": "极恶技·灭",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 3
}
]
},
{
"nameEn": "reason_beyond_reason",
"name": "理外之理",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1117,
"nameEn": "mika",
"type": "character",
"name": "米卡",
"hp": 10,
"energy": 2,
"element": "冰元素",
"weapon": "长柄武器",
"skills": [
{
"nameEn": "spear_of_favonius_arrows_passage",
"name": "西风枪术·镝传",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "starfrost_swirl",
"name": "星霜的流旋",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 3
}
]
},
{
"nameEn": "skyfeather_song",
"name": "苍翎的颂愿",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "suppressive_barrage",
"name": "速射牵制",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1201,
"nameEn": "barbara",
@@ -1794,7 +1646,7 @@
"nameEn": "yelan",
"type": "character",
"name": "夜兰",
"hp": 11,
"hp": 10,
"energy": 3,
"element": "水元素",
"weapon": "弓",
@@ -4447,83 +4299,6 @@
}
]
},
{
"id": 1417,
"nameEn": "ineffa",
"type": "character",
"name": "伊涅芙",
"hp": 10,
"energy": 2,
"element": "雷元素",
"weapon": "长柄武器",
"skills": [
{
"nameEn": "cyclonic_duster",
"name": "除尘旋刃",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "cleaning_mode_carrier_frequency",
"name": "涤净模式·稳态载频",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
}
]
},
{
"nameEn": "supreme_instruction_cyclonic_exterminator",
"name": "至高律令·全域扫灭",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "moonsign_benediction_assemblage_hub",
"name": "月兆祝赐·象拟中继",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1501,
"nameEn": "sucrose",
@@ -7613,7 +7388,7 @@
"nameEn": "alldevouring_narwhal",
"type": "character",
"name": "吞星之鲸",
"hp": 6,
"hp": 5,
"energy": 2,
"element": "水元素",
"weapon": "其他武器",
@@ -7759,7 +7534,7 @@
"nameEn": "hydro_tulpa",
"type": "character",
"name": "水形幻人",
"hp": 10,
"hp": 11,
"energy": 3,
"element": "水元素",
"weapon": "其他武器",
@@ -7913,7 +7688,7 @@
"nameEn": "fatui_pyro_agent",
"type": "character",
"name": "愚人众·火之债务处理人",
"hp": 11,
"hp": 9,
"energy": 2,
"element": "火元素",
"weapon": "其他武器",
@@ -8293,83 +8068,6 @@
}
]
},
{
"id": 2306,
"nameEn": "goldflame_qucusaur_tyrant",
"type": "character",
"name": "金焰绒翼龙暴君",
"hp": 11,
"energy": 2,
"element": "火元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "wingcleave",
"name": "翼斩",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "rising_scorchwind",
"name": "升腾炽风",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 3
}
]
},
{
"nameEn": "goldflame_detonation",
"name": "金焰爆轰",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "ancient_bloodline",
"name": "古老者的血脉",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 2401,
"nameEn": "electro_hypostasis",
@@ -9074,7 +8772,7 @@
"nameEn": "stonehide_lawachurl",
"type": "character",
"name": "丘丘岩盔王",
"hp": 10,
"hp": 8,
"energy": 2,
"element": "岩元素",
"weapon": "其他武器",
@@ -9374,7 +9072,7 @@
"nameEn": "jadeplume_terrorshroom",
"type": "character",
"name": "翠翎恐蕈",
"hp": 12,
"hp": 10,
"energy": 2,
"element": "草元素",
"weapon": "其他武器",
@@ -9676,5 +9374,76 @@
"cost": []
}
]
},
{
"id": 6605,
"nameEn": "skirk",
"type": "character",
"name": "丝柯克",
"hp": 10,
"energy": 0,
"element": "冰元素",
"weapon": "单手剑",
"skills": [
{
"nameEn": "havoc_sunder",
"name": "极恶技·断",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "havoc_warp",
"name": "极恶技·闪",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 2
}
]
},
{
"nameEn": "havoc_extinction",
"name": "极恶技·尽",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 1
}
]
},
{
"nameEn": "reason_beyond_reason",
"name": "理外之理",
"skillTag": [
"被动技能"
],
"cost": []
}
]
}
]
@@ -564,75 +564,6 @@ public class GeniusInvokationControl
m.LeftButtonUp();
}
/// <summary>
/// 月之五伊涅芙会导致手牌不可调和,根据传入的手牌数量,从左往右尝试
/// </summary>
private bool ActionPhaseElementalTuningAlternatives(int currentCardCount)
{
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
var info = TaskContext.Instance().SystemInfo;
var m = Simulation.SendInput.Mouse;
var startY = rect.Y + rect.Height - 50;
var endX = rect.X + rect.Width - 50;
var endY = rect.Y + rect.Height / 2d;
// 手牌数量对应的起点(中心)和间距
var table = new Dictionary<int, (double startX, double spacing)>
{
{10, (570.0, 120.0)},
{9, (570.0, 130.0)},
{8, (600.0, 145.0)},
{7, (630.0, 160.0)},
{6, (620.0, 200.0)},
{5, (720.0, 200.0)},
{4, (820.0, 200.0)},
{3, (920.0, 200.0)},
{2, (1020.0, 200.0)},
{1, (1120.0, 200.0)}
};
if (!table.ContainsKey(currentCardCount))
{
_logger.LogWarning("未找到手牌数量对应的起始位置配置: {Count}", currentCardCount);
return false;
}
var (startX, spacing) = table[currentCardCount];
// 先点中间位置,确保牌是展开状态
ClickExtension.Click(rect.X + rect.Width / 2d, rect.Y + rect.Height - 50);
Sleep(1500);
// 从左往右尝试
for (int idx = 0; idx < currentCardCount; idx++)
{
var x = rect.X + startX * info.AssetScale + idx * spacing * info.AssetScale;
ClickExtension.Click(x, startY);
Sleep(500);
m.LeftButtonDown();
Sleep(100);
m = ClickExtension.Move(endX, endY);
Sleep(100);
m.LeftButtonUp();
// 等待动画并确认
Sleep(1200);
if (ActionPhaseElementalTuningConfirm())
{
return true;
}
_logger.LogWarning("烧牌位置尝试失败,手牌数:{Count},位置索引:{Idx}", currentCardCount, idx);
ClickGameWindowCenter(); // 复位
Sleep(1000);
}
return false;
}
/// <summary>
/// 烧牌确认(元素调和按钮)
/// </summary>
@@ -761,13 +692,16 @@ public class GeniusInvokationControl
for (var i = 0; i < needSpecifyElementDiceCount; i++)
{
_logger.LogInformation("- 烧第{Count}张牌", i + 1);
// 尝试对当前手牌从左往右依次进行烧牌
var tuned = ActionPhaseElementalTuningAlternatives(duel.CurrentCardCount);
if (!tuned)
ActionPhaseElementalTuning(duel.CurrentCardCount);
Sleep(1200);
var res = ActionPhaseElementalTuningConfirm();
if (res == false)
{
_logger.LogWarning("所有手牌尝试烧牌均失败,取消释放技能");
return false;
_logger.LogWarning("烧牌失败,重试");
i--;
ClickGameWindowCenter(); // 复位
Sleep(1000);
continue;
}
Sleep(1000); // 烧牌动画
@@ -1064,10 +998,11 @@ public class GeniusInvokationControl
public void AppendCharacterStatus(Character character, Mat greyMat, int hp = -2)
{
// 截取出战角色区域扩展,钳位到图像边界防止越界
var charRect = new Rect(character.Area.X, character.Area.Y,
character.Area.Width + 40, character.Area.Height + 10).ClampTo(greyMat);
using var characterMat = new Mat(greyMat, charRect);
// 截取出战角色区域扩展
using var characterMat = new Mat(greyMat, new Rect(character.Area.X,
character.Area.Y,
character.Area.Width + 40,
character.Area.Height + 10));
// 识别角色异常状态
var pCharacterStatusFreeze = MatchTemplateHelper.MatchTemplate(characterMat, _assets.CharacterStatusFreezeMat,
TemplateMatchModes.CCoeffNormed);
@@ -1209,13 +1144,9 @@ public class GeniusInvokationControl
}
else
{
// 出战角色 HP 区域向上偏移,钳位到图像边界防止越界
var activeHpRect = new Rect(
cardRect.X + _config.CharacterCardExtendHpRect.X,
hpMat = new Mat(imageRegion.SrcMat, new Rect(cardRect.X + _config.CharacterCardExtendHpRect.X,
cardRect.Y + _config.CharacterCardExtendHpRect.Y - _config.ActiveCharacterCardSpace,
_config.CharacterCardExtendHpRect.Width,
_config.CharacterCardExtendHpRect.Height).ClampTo(imageRegion.SrcMat);
hpMat = new Mat(imageRegion.SrcMat, activeHpRect);
_config.CharacterCardExtendHpRect.Width, _config.CharacterCardExtendHpRect.Height));
text = OcrFactory.Paddle.Ocr(hpMat);
//Cv2.ImWrite($"log\\hp_active_{i}.jpg", hpMat);
Debug.WriteLine($"角色{i}出战HP位置识别结果{text}");
@@ -1,4 +1,4 @@
using System;
using System;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
{
@@ -15,11 +15,6 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
/// 目标编号(技能编号,从右往左)
/// </summary>
public int TargetIndex { get; set; }
/// <summary>
/// 灵活改变骰子的数量(因为在不同的牌局中或者角色技能中会发生骰子实际需要的数量增加或减少)
/// </summary>
public int DiceDelta { get; set; } = 0;
public override string? ToString()
{
@@ -27,11 +22,11 @@ namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model
{
if (string.IsNullOrEmpty(Character.Skills[TargetIndex].Name))
{
return $"【{Character.Name}】使用【技能{TargetIndex}】{(DiceDelta != 0 ? $"(骰子{(DiceDelta > 0 ? "增加" : "减少")}{Math.Abs(DiceDelta)})" : "")}";
return $"【{Character.Name}】使用【技能{TargetIndex}】";
}
else
{
return $"【{Character.Name}】使用【{Character.Skills[TargetIndex].Name}】{(DiceDelta != 0 ? $"(骰子{(DiceDelta > 0 ? "增加" : "减少")}{Math.Abs(DiceDelta)})" : "")}";
return $"【{Character.Name}】使用【{Character.Skills[TargetIndex].Name}】";
}
}
else if (Action == ActionEnum.SwitchLater)
@@ -203,7 +203,7 @@ public class Duel
}
// 2. 判断使用技能
if (actionCommand.GetAllDiceUseCount() + actionCommand.DiceDelta > CurrentDiceCount)// 判断条件加上 DiceDelta 骰子变化
if (actionCommand.GetAllDiceUseCount() > CurrentDiceCount)
{
_logger.LogInformation("骰子不足以进行下一步:{Action}", actionCommand);
break;
@@ -213,9 +213,7 @@ public class Duel
bool useSkillRes = actionCommand.UseSkill(this);
if (useSkillRes)
{
int realCost = actionCommand.GetAllDiceUseCount() + actionCommand.DiceDelta;
realCost = Math.Max(realCost, 0);
CurrentDiceCount -= realCost;
CurrentDiceCount -= actionCommand.GetAllDiceUseCount();
alreadyExecutedActionIndex.Add(i);
alreadyExecutedActionCommand.Add(actionCommand);
_logger.LogInformation("→指令执行完成:{Action}", actionCommand);
@@ -346,7 +344,7 @@ public class Duel
}
// 2. 判断使用技能
actionUseDiceSum += Math.Max(actionCommand.GetAllDiceUseCount() + actionCommand.DiceDelta, 0);
actionUseDiceSum += actionCommand.GetAllDiceUseCount();
if (actionUseDiceSum > CurrentDiceCount)
{
break;
@@ -60,7 +60,7 @@ public class ScriptParser
MyAssert(duel.Characters[3] != null, "角色未定义");
string[] actionParts = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
MyAssert(actionParts.Length >= 3 && actionParts.Length <= 4, "策略中的行动命令解析错误");
MyAssert(actionParts.Length == 3, "策略中的行动命令解析错误");
MyAssert(actionParts[1] == "使用", "策略中的行动命令解析错误");
var actionCommand = new ActionCommand();
@@ -83,26 +83,6 @@ public class ScriptParser
int skillNum = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(actionParts[2], ""));
MyAssert(skillNum < 5, "策略中的行动命令解析错误:技能编号错误");
actionCommand.TargetIndex = skillNum;
// 解析骰子增减
actionCommand.DiceDelta = 0;
if (actionParts.Length >= 4)
{
if (actionParts[3].StartsWith("骰子增加"))
{
int delta = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(actionParts[3], ""));
actionCommand.DiceDelta = delta;
}
else if (actionParts[3].StartsWith("骰子减少"))
{
int delta = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(actionParts[3], ""));
actionCommand.DiceDelta = -delta;
}
else
{
MyAssert(false, $"策略中的行动命令解析错误:骰子增减参数格式不正确(应为 骰子增加N 或 骰子减少N ),实际:{actionParts[3]}");
}
}
duel.ActionCommandQueue.Add(actionCommand);
}
else
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 918 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 707 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 755 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 682 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1018 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 696 B

@@ -1,98 +0,0 @@
{
"info": {
"authors": [],
"bgi_version": "0.45.0",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1757822946823,
"map_match_method": "",
"map_name": "Teyvat",
"name": "挪德卡莱3-蓝泊湖-2-rerun",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "walk",
"type": "teleport",
"x": 9099.5234375,
"y": 2296.4248046875
},
{
"action": "stop_flying",
"action_params": "",
"id": 2,
"move_mode": "fly",
"type": "path",
"x": 9094.8037109375,
"y": 2281.67529296875
},
{
"action": "",
"action_params": "",
"id": 3,
"move_mode": "dash",
"type": "path",
"x": 9068.869140625,
"y": 2268.197021484375
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "dash",
"type": "path",
"x": 9058.2861328125,
"y": 2253.7373046875
},
{
"action": "",
"action_params": "",
"id": 5,
"move_mode": "run",
"type": "path",
"x": 9041.37890625,
"y": 2250.19384765625
},
{
"action": "",
"action_params": "",
"id": 6,
"move_mode": "dash",
"type": "path",
"x": 9026.62109375,
"y": 2235.5322265625
},
{
"action": "",
"action_params": "",
"id": 7,
"move_mode": "dash",
"type": "path",
"x": 9024.693359375,
"y": 2198.438720703125
},
{
"action": "stop_flying",
"action_params": "1000",
"id": 8,
"move_mode": "fly",
"type": "path",
"x": 9018.0087890625,
"y": 2152.14990234375
},
{
"action": "",
"action_params": "",
"id": 9,
"move_mode": "walk",
"type": "target",
"x": 9018.50390625,
"y": 2146.216064453125
}
]
}
Loaded 100 of 824 files, more files were not shown because too many files have changed in this diff. Show more