Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4118e28f3d | ||
|
|
25e73e500a | ||
|
|
fd1a1a439a | ||
|
|
9a39c769fe | ||
|
|
3ec8048805 | ||
|
|
b3f90e7049 | ||
|
|
bee45ef958 | ||
|
|
4dca07d17f | ||
|
|
c9db8b8291 | ||
|
|
51c1aaea4e | ||
|
|
7a48461d7a | ||
|
|
c4f9e70eeb | ||
|
|
c163bb0cd5 | ||
|
|
704d920d6d | ||
|
|
95a6f9a059 | ||
|
|
67162cd6a2 | ||
|
|
711bbef8a2 | ||
|
|
4893fc6100 | ||
|
|
d533eab029 | ||
|
|
8a4db29436 | ||
|
|
a6ef833f00 | ||
|
|
ae72911f81 | ||
|
|
21a575086d | ||
|
|
d42e6142ad | ||
|
|
2083b11c31 | ||
|
|
a4cb735c32 | ||
|
|
d1967477d2 | ||
|
|
6180194da2 | ||
|
|
50254a6efc | ||
|
|
249a79d7be | ||
|
|
6f713ca719 | ||
|
|
10808edb21 | ||
|
|
902caf462f | ||
|
|
614f6a8abf | ||
|
|
893777b4ad | ||
|
|
6982d3ba74 | ||
|
|
a0bc552a8a | ||
|
|
1dd1e2aa16 | ||
|
|
76353f54d1 | ||
|
|
b808aa696c | ||
|
|
5bd55682d3 | ||
|
|
b9106fd994 | ||
|
|
8323ece56c | ||
|
|
d8335ff097 | ||
|
|
e761c2e01b | ||
|
|
880ac623ff | ||
|
|
86ac610bf0 | ||
|
|
efc90cb63b | ||
|
|
6a8a9a6223 | ||
|
|
810a2797c2 | ||
|
|
ac7348e427 | ||
|
|
537c5d0024 | ||
|
|
5011141a6e | ||
|
|
44510b49ef | ||
|
|
6f0caa4505 | ||
|
|
4951ce7f08 | ||
|
|
24201751c9 | ||
|
|
0af68c28f6 | ||
|
|
e0deb2049f | ||
|
|
29aff3ed75 | ||
|
|
18781460a1 | ||
|
|
92b6dda274 | ||
|
|
fd33d0657a | ||
|
|
e1afc4b552 | ||
|
|
d99d2c2c52 | ||
|
|
7849b675b3 | ||
|
|
6eef898743 | ||
|
|
3b7ea40ba9 | ||
|
|
6efd415290 | ||
|
|
e14b28ddba | ||
|
|
248e1f0e6e | ||
|
|
c5851914df | ||
|
|
bfe5f868ed | ||
|
|
f29966868c | ||
|
|
cbb49b705d | ||
|
|
459920cb3f | ||
|
|
80048ca262 | ||
|
|
5a0edf2bf4 | ||
|
|
cd4459c889 | ||
|
|
477343c6af | ||
|
|
eac0a285ac | ||
|
|
8e24879b33 | ||
|
|
42e1c0e745 | ||
|
|
de5d38a5ba | ||
|
|
f29b0828ab | ||
|
|
491b55bcb5 | ||
|
|
05b074ccd4 | ||
|
|
7519ccb9e4 | ||
|
|
fca9e5cbe7 | ||
|
|
4790db7979 | ||
|
|
6202243c8d | ||
|
|
c2943426dc | ||
|
|
fd760e6b85 | ||
|
|
5913398153 | ||
|
|
4662118f59 | ||
|
|
7eb493bc33 | ||
|
|
4f5ef08c1f | ||
|
|
9424d1f3c3 | ||
|
|
0233a19f39 | ||
|
|
4d1c1847c2 | ||
|
|
8aeb1cd7ef | ||
|
|
07c5ea5849 | ||
|
|
6e51f601f8 | ||
|
|
4e019511e2 | ||
|
|
178ae2dc96 | ||
|
|
97c90aa117 | ||
|
|
63432547cf | ||
|
|
5a584c0143 | ||
|
|
1799103e84 | ||
|
|
7de8a45dce | ||
|
|
8bd43f3918 | ||
|
|
c8dbfeb370 | ||
|
|
e33800e754 | ||
|
|
7cea971b6e | ||
|
|
ad78bf95b0 | ||
|
|
83a86c8bae | ||
|
|
325142390d | ||
|
|
7d838cd644 | ||
|
|
64defc0f02 | ||
|
|
b3e46b3004 | ||
|
|
bbd5a1b806 | ||
|
|
cca51e1f5f | ||
|
|
639ccfb123 | ||
|
|
a0f0983af7 | ||
|
|
05efd0ceef | ||
|
|
412a6c405e | ||
|
|
4f4cfc052d | ||
|
|
27017bbf4e | ||
|
|
29d93a2c6e | ||
|
|
6209e1b498 | ||
|
|
ae131ea5ce | ||
|
|
5c6a2ba9fd | ||
|
|
7d1872bda9 | ||
|
|
c7c8210df6 | ||
|
|
4a289f3f4f | ||
|
|
c97e6055fa | ||
|
|
bf0b442442 | ||
|
|
98ef0b879f | ||
|
|
e97dc4e46b | ||
|
|
2d6182233b | ||
|
|
faf84401bc | ||
|
|
4cc4e123d5 | ||
|
|
8f2bdc76ad | ||
|
|
d24023e7bf | ||
|
|
ac38d39b52 | ||
|
|
f7a2c558c5 | ||
|
|
e7c01cf70c | ||
|
|
fd80f2952a | ||
|
|
fe4e978e6f | ||
|
|
df4325bea3 | ||
|
|
cbb7171cc5 | ||
|
|
68404a63ca | ||
|
|
8abea9801a | ||
|
|
bffa587517 | ||
|
|
cab921384b | ||
|
|
8361479787 | ||
|
|
2bebe865ad | ||
|
|
08f5fe9504 | ||
|
|
1566560f80 | ||
|
|
b2631ed362 | ||
|
|
3f81331e37 | ||
|
|
3ea1c67288 | ||
|
|
41909055c7 | ||
|
|
00305aa5d2 | ||
|
|
a3c2024267 |
No files matched your search
File renamed without changes.
@@ -1,8 +1,7 @@
|
||||
name: Bug report / 错误报告
|
||||
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
|
||||
title: "[bug] "
|
||||
labels:
|
||||
- BUG
|
||||
type: Bug
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
name: I have feature requesting / 我有功能需求
|
||||
description: 提出新的功能想法 / Share a feature request
|
||||
title: "[feature] "
|
||||
labels:
|
||||
- 功能建议
|
||||
type: Feature
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
name: I have a question / 我有疑问
|
||||
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
|
||||
title: "[question] "
|
||||
labels:
|
||||
- 问题咨询
|
||||
type: Question
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
name: I have suggestions / 我有建议
|
||||
description: 分享对项目的改进建议 / Share an improvement suggestion
|
||||
title: "[suggestion] "
|
||||
labels:
|
||||
- 功能建议
|
||||
type: Suggestions
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: checks
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<!--
|
||||
感谢你的贡献!提交前请先阅读以下说明 / Thanks for contributing! Please read this before submitting:
|
||||
1. 请按模板逐项填写,请勿删除模板中的标题,否则内容无法被正确识别 / Fill in every section and do not delete the headings.
|
||||
2. 未填写关键信息(解决的需求、是否在游戏内实际运行、代码是否纯手工编写)的 PR 可能会被直接关闭 / PRs missing key information may be closed directly.
|
||||
3. 请保持改动聚焦,避免在一次 PR 中混入与需求无关的大规模改动 / Keep the change focused.
|
||||
-->
|
||||
|
||||
## 提交确认 / Checklist
|
||||
|
||||
- [ ] 我已经搜索过现有 Issue 与 PR,确认这不是重复内容 / I have searched existing issues and PRs and confirmed this is not a duplicate
|
||||
- [ ] 我已经阅读过[文档](https://www.bettergi.com/doc.html),确认改动符合项目的使用方式 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed the change matches the project's usage
|
||||
- [ ] 本次改动可以通过 `dotnet build BetterGenshinImpact.sln -c Debug` 编译 / This change compiles with `dotnet build BetterGenshinImpact.sln -c Debug`
|
||||
- [ ] 我理解未经过实际验证的改动,可能被要求补充证据后再合并 / I understand unverified changes may require more evidence before merging
|
||||
|
||||
## 关联 Issue / Related Issue
|
||||
|
||||
<!-- 例:close #1234 / Fixes #1234;没有关联 Issue 可填写“无” / Write "None" if there is no related issue -->
|
||||
|
||||
## 解决的需求 / Problem Solved
|
||||
|
||||
> 请说明这个 PR 要解决什么问题,而不是只描述改了哪些代码 / Explain the problem this PR solves, not just which code was changed.
|
||||
|
||||
**要解决的需求或问题是什么?/ What problem does this PR solve?**
|
||||
|
||||
**在什么场景下会触发或需要它?/ In which scenarios is it needed?**
|
||||
|
||||
**实现方案简述 / Implementation summary**
|
||||
|
||||
## 是否在游戏内实际运行 / Verified In-Game
|
||||
|
||||
> BetterGI 的行为高度依赖真实游戏环境(分辨率、帧率、任务状态、网络延迟等),因此请如实填写本项,以下两项请只勾选一项。/ BetterGI's behavior heavily depends on the real game environment, so please answer this honestly. Check only one of the following.
|
||||
|
||||
- [ ] 已在游戏内实际运行并验证本次改动 / Yes, I actually ran and verified this change in the game
|
||||
- [ ] 未在游戏内实际运行 / No, I have not run it in the game
|
||||
|
||||
**若已在游戏内运行,请补充验证信息 / If yes, please provide details:**
|
||||
|
||||
| 项目 / Item | 内容 / Detail |
|
||||
| --- | --- |
|
||||
| 游戏版本 / Game version | |
|
||||
| 分辨率与窗口模式 / Resolution & window mode | |
|
||||
| 验证的功能或任务 / Verified feature or task | |
|
||||
| 验证次数与运行时长 / Runs & duration | |
|
||||
| 结果 / Result | 符合预期 / 存在问题(请说明) |
|
||||
|
||||
**若未在游戏内运行,请说明原因与替代验证方式(例如仅文档、仅 UI 调整、仅重构、单元测试)/ If not, explain why and what alternative verification was done:**
|
||||
|
||||
## 代码是否纯手工编写 / Hand-Written Code
|
||||
|
||||
> 本项目推荐使用 AI 辅助编写代码,但要求提交者完全理解并验证自己提交的每一行代码,并对最终结果负责。以下三项请只勾选一项。/ AI-assisted coding is recommended, but you must fully understand and verify every line you submit, and you are responsible for the result. Check only one of the following.
|
||||
|
||||
- [ ] 本次代码完全由我手工编写,未使用 AI 生成 / Entirely hand-written, no AI generation
|
||||
- [ ] 部分代码由 AI 辅助生成,我已逐行阅读、理解并验证 / Partly AI-assisted; I have read, understood and verified it line by line
|
||||
- [ ] 本次代码完全由 AI 生成,我已逐行阅读、理解并验证 / Fully AI-generated; I have read, understood and verified it line by line
|
||||
|
||||
**AI 参与的部分及我的验证方式(未使用 AI 请填“无”)/ AI-involved parts and how I verified them (write "None" if no AI was used):**
|
||||
|
||||
**我确认 / I confirm:**
|
||||
|
||||
- [ ] 我理解本次改动的全部逻辑,能够解释每一处修改的原因 / I understand the entire change and can explain every modification
|
||||
- [ ] 提交的代码不包含来源不明、我无法解释的代码片段 / No unexplained code from unknown sources is included
|
||||
|
||||
## 改动类型 / Type of Change
|
||||
|
||||
- [ ] 新功能 / New feature
|
||||
- [ ] 问题修复 / Bug fix
|
||||
- [ ] 重构或性能优化 / Refactor or performance
|
||||
- [ ] 文档或其他杂项 / Docs or chores
|
||||
|
||||
## 影响范围 / Impact
|
||||
|
||||
**涉及的模块或功能 / Affected modules or features:**
|
||||
|
||||
**可能带来的风险、兼容性影响或行为变化 / Potential risks, compatibility impact, or behavior changes:**
|
||||
|
||||
## 补充信息 / Additional Information
|
||||
|
||||
<!-- 截图、录屏、日志、参考链接等,可选 / Screenshots, recordings, logs, references (optional) -->
|
||||
+35
-12
@@ -6,7 +6,7 @@ providers:
|
||||
openAiCompatible:
|
||||
enabled: true
|
||||
baseUrl: https://api.openai.com/v1
|
||||
model: gpt-5.4
|
||||
model: gpt-5.6-luna
|
||||
apiStyle: responses
|
||||
timeoutMs: 30000
|
||||
|
||||
@@ -19,16 +19,22 @@ issues:
|
||||
commentAnchor: issue-bot:validation
|
||||
templates:
|
||||
- key: bug
|
||||
issueType: Bug
|
||||
detect:
|
||||
markers:
|
||||
- bug
|
||||
titlePrefixes:
|
||||
- "[bug]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复问题
|
||||
- 确认文档的内容无法解决我的问题
|
||||
- 我愿意为了解决这个问题尽自己所能
|
||||
requiredSections:
|
||||
- id: environment
|
||||
aliases:
|
||||
- 系统环境
|
||||
- System Environment
|
||||
- 运行环境与关键配置
|
||||
- id: version
|
||||
aliases:
|
||||
- BetterGI 版本号
|
||||
@@ -42,36 +48,45 @@ issues:
|
||||
- 复现步骤
|
||||
- Reproduction steps
|
||||
labels:
|
||||
whenValid:
|
||||
- BUG
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: feature
|
||||
issueType: Feature
|
||||
detect:
|
||||
markers:
|
||||
- feature
|
||||
titlePrefixes:
|
||||
- "[feature]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复建议
|
||||
- 我已确认当前版本中尚未提供该功能,或至少没有等价实现
|
||||
- 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好
|
||||
- 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳
|
||||
requiredSections:
|
||||
- id: request
|
||||
aliases:
|
||||
- 功能请求
|
||||
- Feature Request
|
||||
- 需求或建议
|
||||
- id: scenario
|
||||
aliases:
|
||||
- 使用场景
|
||||
- Use Case
|
||||
labels:
|
||||
whenValid:
|
||||
- 功能建议
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: suggestion
|
||||
issueType: Suggestions
|
||||
detect:
|
||||
markers:
|
||||
- suggestion
|
||||
titlePrefixes:
|
||||
- "[suggestion]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复建议
|
||||
- 确认文档的内容无法解决我的问题或覆盖我的建议
|
||||
requiredSections:
|
||||
- id: suggestion
|
||||
aliases:
|
||||
@@ -82,16 +97,19 @@ issues:
|
||||
- 预期收益
|
||||
- Expected Benefit
|
||||
labels:
|
||||
whenValid:
|
||||
- 功能建议
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: question
|
||||
issueType: Question
|
||||
detect:
|
||||
markers:
|
||||
- question
|
||||
titlePrefixes:
|
||||
- "[question]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复问题
|
||||
- 确认文档的内容无法解决我的问题
|
||||
requiredSections:
|
||||
- id: question
|
||||
aliases:
|
||||
@@ -102,8 +120,7 @@ issues:
|
||||
- 已尝试内容
|
||||
- What I Tried
|
||||
labels:
|
||||
whenValid:
|
||||
- 问题咨询
|
||||
whenValid: []
|
||||
whenInvalid:
|
||||
- 需要更多信息
|
||||
- key: normal
|
||||
@@ -113,6 +130,9 @@ issues:
|
||||
titlePrefixes:
|
||||
- "[feedback]"
|
||||
- "[normal]"
|
||||
formSignatures:
|
||||
- 我已经搜索过现有 issue,确认这不是重复反馈
|
||||
- 确认文档的内容无法解决我的问题或覆盖我的反馈
|
||||
requiredSections:
|
||||
- id: description
|
||||
aliases:
|
||||
@@ -143,9 +163,6 @@ issues:
|
||||
enabled: true
|
||||
autoCreateMissing: true
|
||||
managed:
|
||||
- BUG
|
||||
- 功能建议
|
||||
- 问题咨询
|
||||
- 需要更多信息
|
||||
- 重复
|
||||
definitions:
|
||||
@@ -227,3 +244,9 @@ pullRequests:
|
||||
enabled: false
|
||||
summary:
|
||||
enabled: false
|
||||
issueLink:
|
||||
enabled: true
|
||||
commentAnchor: pull-bot:issue-link
|
||||
appendCloseKeyword: true
|
||||
closeKeywordTemplate: "close #{number}"
|
||||
requireSameRepository: true
|
||||
@@ -1,4 +1,5 @@
|
||||
name: Repo Bot
|
||||
run-name: "Repo Bot #${{ github.event.issue.number || github.event.pull_request.number }} - ${{ github.event_name }}/${{ github.event.action }} - @${{ github.actor }}"
|
||||
|
||||
on:
|
||||
issues:
|
||||
@@ -11,45 +12,43 @@ on:
|
||||
types:
|
||||
- created
|
||||
- edited
|
||||
# pull_request_target (not pull_request) is required so that pull requests opened from
|
||||
# forks can be labelled/commented. Never check out or execute the pull request head here.
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- edited
|
||||
- synchronize
|
||||
- reopened
|
||||
- ready_for_review
|
||||
|
||||
jobs:
|
||||
repo-bot:
|
||||
runs-on: ubuntu-latest
|
||||
if: >-
|
||||
github.event.sender.type != 'Bot' &&
|
||||
(
|
||||
github.event_name != 'issue_comment' ||
|
||||
contains(github.event.comment.body, '/fix') ||
|
||||
contains(github.event.comment.body, '/refresh')
|
||||
)
|
||||
uses: ddaodan/bettergi-github-bot/.github/workflows/repo-bot.yml@v1
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: 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 }}
|
||||
secrets:
|
||||
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
|
||||
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
|
||||
with:
|
||||
config-path: .github/repo-bot.yml
|
||||
# pull_request_target: only fetch the configuration from the base branch.
|
||||
# Never check out the pull request head (it would execute untrusted code).
|
||||
checkout-mode: config-only
|
||||
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
|
||||
ai-enabled: ${{ vars.REPO_BOT_AI_ENABLED }}
|
||||
ai-base-url: ${{ vars.REPO_BOT_AI_BASE_URL }}
|
||||
ai-model: ${{ vars.REPO_BOT_AI_MODEL }}
|
||||
ai-api-style: ${{ vars.REPO_BOT_AI_API_STYLE }}
|
||||
ai-timeout-ms: ${{ vars.REPO_BOT_AI_TIMEOUT_MS }}
|
||||
action-ref: v1
|
||||
github-app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
|
||||
+13
-2
@@ -10,6 +10,13 @@
|
||||
|
||||
# Build results
|
||||
Build/
|
||||
!Build/
|
||||
Build/*
|
||||
!Build/BetterGenshinImpact.I18nSync/
|
||||
!Build/BetterGenshinImpact.I18nSync/**
|
||||
!Build/Scripts/
|
||||
Build/Scripts/*
|
||||
!Build/Scripts/i18n-sync.ps1
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
@@ -22,7 +29,11 @@ bld/
|
||||
[Ll]og/
|
||||
|
||||
# Mine
|
||||
Tmp/
|
||||
/Tmp/
|
||||
|
||||
# AI temporary design docs
|
||||
Docs/tmp/*
|
||||
!Docs/tmp/README.md
|
||||
/packages/
|
||||
node_modules/
|
||||
github_actions_cache/
|
||||
@@ -43,4 +54,4 @@ __pycache__/
|
||||
!.trae/skills/**
|
||||
|
||||
# Claude
|
||||
.claude/*
|
||||
.claude/*
|
||||
@@ -85,6 +85,14 @@
|
||||
dotnet build BetterGenshinImpact.sln -c Debug
|
||||
```
|
||||
|
||||
禁止 新增 BetterGenshinImpact\Assets 目录,这里的资源已经被 BetterGI.Assets.* 的外部资源给占用了。如果要新增资源,需要人工去修改对应 nuget 包的资源。
|
||||
|
||||
## 识别与模拟操作
|
||||
|
||||
在进行键鼠操作后再识图的时候,必须添加适当的延时!因为游戏内对键鼠的响应是有 30~60ms 的延迟的,截图的来源图也是有延迟的。
|
||||
|
||||
键鼠操作本身也不宜过快,在 30 fps 的游戏中,过快的操作可能会丢失。
|
||||
|
||||
## Code Review Rules
|
||||
|
||||
### Output language
|
||||
|
||||
@@ -17,6 +17,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{02CEA57F-C
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.UnitTest", "Test\BetterGenshinImpact.UnitTest\BetterGenshinImpact.UnitTest.csproj", "{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{DB7D66B7-B4DA-4A16-8BBF-3DDA83654C53}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.I18nSync", "Build\BetterGenshinImpact.I18nSync\BetterGenshinImpact.I18nSync.csproj", "{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -73,6 +77,14 @@ Global
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.Build.0 = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.ActiveCfg = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.Build.0 = Release|x64
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76}.Release|x64.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -80,6 +92,7 @@ Global
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{B63FC99D-3C56-4F95-A80B-8AAFD8482C76} = {DB7D66B7-B4DA-4A16-8BBF-3DDA83654C53}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {352D8B78-9DE3-4E58-985F-FADD22594DB4}
|
||||
|
||||
@@ -35,7 +35,6 @@
|
||||
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
|
||||
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
|
||||
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
|
||||
<bgivc:TrConverter x:Key="TrConverter" />
|
||||
<bgivc:AdaptiveUniformGridColumnsConverter x:Key="AdaptiveUniformGridColumnsConverter" />
|
||||
|
||||
<!-- ===== 全局 TextBox 安全剪贴板 ===== -->
|
||||
@@ -47,4 +46,4 @@
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
</Application>
|
||||
+112
-46
@@ -2,24 +2,32 @@ using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using BetterGenshinImpact.Core.Mask;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Monitor;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Audio;
|
||||
using BetterGenshinImpact.GameTask.Music.Service;
|
||||
using BetterGenshinImpact.GameTask.Runtime;
|
||||
using BetterGenshinImpact.GameTask.Runtime.Win32;
|
||||
using BetterGenshinImpact.GameTask.Runtime.WebPage;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.Helpers.Win32;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.Service.ChildSession;
|
||||
using BetterGenshinImpact.Service.Instance;
|
||||
using BetterGenshinImpact.Service.I18n;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using BetterGenshinImpact.Service.Notifier;
|
||||
using BetterGenshinImpact.View;
|
||||
using BetterGenshinImpact.View.Mask;
|
||||
using BetterGenshinImpact.View.Pages;
|
||||
using BetterGenshinImpact.View.Windows;
|
||||
using BetterGenshinImpact.ViewModel;
|
||||
@@ -68,8 +76,12 @@ public partial class App : Application
|
||||
Directory.CreateDirectory(logFolder);
|
||||
var logFile = Path.Combine(logFolder, "better-genshin-impact.log");
|
||||
var instanceContext = InstanceBootstrap.Current.Context;
|
||||
// 网页版实例带上实例名,例如 WebView(小号A):S1:P1234:T…
|
||||
var instanceTypeLabel = instanceContext.InstanceName is { } instanceName
|
||||
? $"{instanceContext.InstanceType}({instanceName})"
|
||||
: instanceContext.InstanceType.ToString();
|
||||
var instanceIdentity =
|
||||
$"{instanceContext.InstanceType}:S{instanceContext.WindowsSessionId}:P{instanceContext.ProcessId}:T{instanceContext.StartedAt.ToUnixTimeMilliseconds()}";
|
||||
$"{instanceTypeLabel}:S{instanceContext.WindowsSessionId}:P{instanceContext.ProcessId}:T{instanceContext.StartedAt.ToUnixTimeMilliseconds()}";
|
||||
|
||||
var richTextBox = new RichTextBoxImpl();
|
||||
services.AddSingleton<IRichTextBox>(richTextBox);
|
||||
@@ -89,34 +101,59 @@ public partial class App : Application
|
||||
.MinimumLevel.Debug()
|
||||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
|
||||
if (all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true })
|
||||
{
|
||||
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
}
|
||||
// 日志遮罩输出:仅当“遮罩启用且日志框可见”时才真正写入,隐藏时避免不必要的 UI 开销(#3161)。
|
||||
// 条件改为运行时每次写入时动态判断,因此启动后通过快捷键切换 ShowLogBox 也能即时恢复日志(#3357)。
|
||||
loggerConfiguration.WriteTo.Sink(
|
||||
new ConditionalLogEventSink(
|
||||
new LoggerConfiguration()
|
||||
.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.CreateLogger(),
|
||||
() => all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true }),
|
||||
LogEventLevel.Information);
|
||||
|
||||
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>();
|
||||
// });
|
||||
// }
|
||||
|
||||
// 配置和日志已经就绪,在任何推理服务或会话初始化前选定原生运行库。
|
||||
all.HardwareAccelerationConfig ??= new();
|
||||
var inferenceStartupStatus = InferenceRuntimeService.PrepareStartup(all.HardwareAccelerationConfig, InstanceBootstrap.Current.Context.IsRoot);
|
||||
// 只规范配置并绑定运行库;待验证状态在主窗口实际开始验证时才落盘。
|
||||
configService.Save();
|
||||
services.AddSingleton(inferenceStartupStatus);
|
||||
var onnxRuntimeLoader = new OnnxRuntimeLoader(all.HardwareAccelerationConfig, AppContext.BaseDirectory);
|
||||
services.AddSingleton(onnxRuntimeLoader);
|
||||
services.AddSingleton<IOnnxRuntimeSelection>(onnxRuntimeLoader);
|
||||
var onnxRuntimeInstaller = new OnnxRuntimeInstaller(AppContext.BaseDirectory);
|
||||
services.AddSingleton(onnxRuntimeInstaller);
|
||||
services.AddSingleton<IOnnxRuntimeInstaller>(onnxRuntimeInstaller);
|
||||
services.AddSingleton<IInferenceDeviceDiscovery, InferenceDeviceDiscovery>();
|
||||
services.AddSingleton<IInferenceBenchmarkLeaseProvider>(sp => new InferenceBenchmarkCoordinator(
|
||||
BetterGenshinImpact.GameTask.Common.TaskControl.TaskSemaphore,
|
||||
() => sp.GetRequiredService<TaskTriggerDispatcher>().PauseForInference()));
|
||||
services.AddSingleton<InferenceModelDiagnostics>();
|
||||
services.AddSingleton<IInferenceModelDiagnostics>(sp => sp.GetRequiredService<InferenceModelDiagnostics>());
|
||||
services.AddSingleton<InferenceRuntimeService>();
|
||||
services.AddSingleton<HardwareAccelerationViewModelFactory>();
|
||||
services.AddSingleton<IInferenceSettingsInteraction, InferenceSettingsInteraction>();
|
||||
|
||||
services.AddLocalization();
|
||||
var i18nService = I18nService.Instance;
|
||||
var uiLanguage = all.OtherConfig.UiCultureInfoName switch
|
||||
{
|
||||
"zh-CN" => "zh-Hans",
|
||||
"en-US" => "en",
|
||||
"ja-JP" => "ja",
|
||||
_ => all.OtherConfig.UiCultureInfoName,
|
||||
};
|
||||
if (uiLanguage != all.OtherConfig.UiCultureInfoName)
|
||||
{
|
||||
all.OtherConfig.UiCultureInfoName = uiLanguage;
|
||||
configService.Save();
|
||||
}
|
||||
|
||||
i18nService.ChangeLanguage(uiLanguage);
|
||||
services.AddSingleton(i18nService);
|
||||
|
||||
services.AddNavigationViewPageProvider();
|
||||
services.AddSingleton(InstanceBootstrap.Current);
|
||||
@@ -176,7 +213,32 @@ public partial class App : Application
|
||||
services.AddSingleton<IRelativeMouseInputMonitorFactory, RelativeMouseInputMonitorFactory>();
|
||||
services.AddSingleton<OverlayMetricsService>();
|
||||
services.AddSingleton<CustomHtmlMaskService>();
|
||||
|
||||
// 遮罩窗口:业务侧只依赖 IMaskWindowDrawingBoard / IMaskWindowHost / IMaskWindowMapState
|
||||
services.AddSingleton<MaskWindowDrawingBoard>();
|
||||
services.AddSingleton<IMaskWindowDrawingBoard>(sp => sp.GetRequiredService<MaskWindowDrawingBoard>());
|
||||
services.AddSingleton<IMaskWindowSnapshotSource<MaskWindowDrawingSnapshot>>(sp => sp.GetRequiredService<MaskWindowDrawingBoard>());
|
||||
services.AddSingleton<MaskWindowMapState>();
|
||||
services.AddSingleton<IMaskWindowMapState>(sp => sp.GetRequiredService<MaskWindowMapState>());
|
||||
services.AddSingleton<IMaskWindowSnapshotSource<MaskWindowMapSnapshot>>(sp => sp.GetRequiredService<MaskWindowMapState>());
|
||||
services.AddSingleton<MaskWindowViewModel>();
|
||||
services.AddTransient<MaskWindow>();
|
||||
services.AddSingleton<Func<MaskWindow>>(sp => () => sp.GetRequiredService<MaskWindow>());
|
||||
services.AddSingleton<IMaskWindowHost, MaskWindowHost>();
|
||||
services.AddSingleton<DialogueOptionVoiceDiagnosticState>();
|
||||
services.AddSingleton<DialogueOptionVoiceDiagnosticService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DialogueOptionVoiceDiagnosticService>());
|
||||
services.AddSingleton<TaskTriggerDispatcher>();
|
||||
// 游戏运行环境:按实例类型选定 Provider,见 Docs/design/game-runtime.md
|
||||
services.AddSingleton<Win32RuntimeProvider>();
|
||||
services.AddSingleton<IGameRuntimeProvider>(sp => sp.GetRequiredService<Win32RuntimeProvider>());
|
||||
services.AddSingleton<IGameRuntimeProvider, WebPageRuntimeProvider>();
|
||||
services.AddTransient<CloudWebHostWindow>();
|
||||
services.AddSingleton<Func<CloudWebHostWindow>>(sp => () => sp.GetRequiredService<CloudWebHostWindow>());
|
||||
services.AddSingleton<GameRuntimeService>();
|
||||
// 云原神网页版实例:实例名存储与启动器(Primary 首页使用)
|
||||
services.AddSingleton<WebViewInstanceStore>();
|
||||
services.AddSingleton<WebViewInstanceLauncher>();
|
||||
services.AddSingleton<RecognitionTemplateAssetService>();
|
||||
services.AddSingleton<RecognitionTemplateEditorService>();
|
||||
services.AddSingleton<NotificationService>();
|
||||
@@ -256,9 +318,15 @@ public partial class App : Application
|
||||
// 分配控制台窗口以支持控制台输出
|
||||
ConsoleHelper.AllocateConsole("BetterGI Console");
|
||||
RegisterEvents();
|
||||
var inferenceRuntime = _host.Services.GetRequiredService<InferenceRuntimeService>();
|
||||
// 此处只准备设备配置;模型验证和提示由主实例的 MainWindowViewModel.OnLoaded 执行。
|
||||
await inferenceRuntime.InitializeAsync();
|
||||
await _host.StartAsync();
|
||||
ServerTimeHelper.Initialize(_host.Services.GetRequiredService<IServerTimeProvider>());
|
||||
await UrlProtocolHelper.RegisterAsync();
|
||||
if (InstanceBootstrap.Current.Context.IsRoot)
|
||||
{
|
||||
await UrlProtocolHelper.RegisterAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -286,8 +354,8 @@ public partial class App : Application
|
||||
try
|
||||
{
|
||||
System.Windows.Forms.MessageBox.Show(
|
||||
$"{TranslateText("应用程序启动失败:")}{ex.Message}",
|
||||
TranslateText("BetterGI 启动失败"),
|
||||
$"应用程序启动失败:{ex.Message}",
|
||||
"BetterGI 启动失败",
|
||||
System.Windows.Forms.MessageBoxButtons.OK,
|
||||
System.Windows.Forms.MessageBoxIcon.Error);
|
||||
}
|
||||
@@ -300,6 +368,7 @@ public partial class App : Application
|
||||
// 启动失败 = 无可用的主界面,直接退出,避免留下无窗口的残留进程。
|
||||
Shutdown();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -311,8 +380,21 @@ public partial class App : Application
|
||||
|
||||
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
|
||||
|
||||
// 写入防抖窗口内尚未落盘的配置改动
|
||||
try
|
||||
{
|
||||
_host.Services.GetService<IConfigService>()?.Flush();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.WriteLine(ex);
|
||||
}
|
||||
|
||||
TempManager.CleanUp();
|
||||
|
||||
await _host.Services.GetRequiredService<InferenceRuntimeService>().StopAsync();
|
||||
await _host.Services.GetRequiredService<OnnxRuntimeInstaller>().StopAsync();
|
||||
await _host.Services.GetRequiredService<InferenceModelDiagnostics>().StopAsync();
|
||||
await _host.StopAsync();
|
||||
_host.Dispose();
|
||||
Log.CloseAndFlush();
|
||||
@@ -432,7 +514,7 @@ public partial class App : Application
|
||||
// 通过日志遮罩提示用户:非致命异常已记录。
|
||||
if (!isTerminating)
|
||||
{
|
||||
var nonFatalMessage = TranslateText("发生非致命异常,已记录日志,请查看日志详情。");
|
||||
const string nonFatalMessage = "发生非致命异常,已记录日志,请查看日志详情。";
|
||||
GetLogger<App>().LogWarning(nonFatalMessage);
|
||||
return false;
|
||||
}
|
||||
@@ -449,7 +531,7 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
// 确认 Dispatcher 可用后才记录"正在弹窗",避免与实际行为不一致。
|
||||
var popupShownMessage = TranslateText("发生致命异常,正在弹窗提示,同时已记录日志。");
|
||||
const string popupShownMessage = "发生致命异常,正在弹窗提示,同时已记录日志。";
|
||||
GetLogger<App>().LogWarning(popupShownMessage);
|
||||
|
||||
try
|
||||
@@ -482,8 +564,7 @@ public partial class App : Application
|
||||
// 只为"UI 是否开始执行"设置超时:UI 线程被阻塞/死锁时避免无限等待。
|
||||
if (!startedSignal.Wait(TimeSpan.FromSeconds(3)))
|
||||
{
|
||||
GetLogger<App>().LogWarning(
|
||||
TranslateText("弹窗调度超时,异常已记录,进程即将退出。"));
|
||||
GetLogger<App>().LogWarning("弹窗调度超时,异常已记录,进程即将退出。");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -500,21 +581,6 @@ public partial class App : Application
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 翻译一条异常提示文本。翻译服务不可用时返回原文。
|
||||
/// </summary>
|
||||
private static string TranslateText(string text)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ServiceProvider.GetService<ITranslationService>()?.Translate(text) ?? text;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return text;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ShowExceptionDialog(Exception e)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.64.0</Version>
|
||||
<Version>0.66.2-alpha.4</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
@@ -38,17 +38,26 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.1.120" />
|
||||
<PackageReference Include="CsTrees" Version="1.0.1" />
|
||||
<!-- 云原神网页版输入 SDK,由 WebView2InputBridge.InstallAsync 读取并注入页面 -->
|
||||
<None Remove="Resources\JavaScript\ys-input-inject.js" />
|
||||
<EmbeddedResource Include="Resources\JavaScript\ys-input-inject.js" LogicalName="BetterGenshinImpact.Resources.JavaScript.ys-input-inject.js" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Anthropic 官方 SDK:自动连招在 OpenAI 兼容端点之外可选的原生 Messages API 提供方 -->
|
||||
<PackageReference Include="Anthropic" Version="12.53.0" />
|
||||
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.1.120" />
|
||||
|
||||
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.21" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.31" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.25" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.24" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.38" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.27" />
|
||||
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="Clipper2" Version="2.0.0" />
|
||||
<PackageReference Include="CsTrees" Version="1.0.5" />
|
||||
<PackageReference Include="CsTrees.MEAI" Version="1.0.2" />
|
||||
<PackageReference Include="DeviceId" Version="6.9.0" />
|
||||
<PackageReference Include="DeviceId.Windows" Version="6.9.0" />
|
||||
<PackageReference Include="DeviceId.Windows.Wmi" Version="6.9.0" />
|
||||
@@ -61,6 +70,8 @@
|
||||
<PackageReference Include="Markdig" Version="1.3.2" />
|
||||
<PackageReference Include="Melanchall.DryWetMidi" Version="8.0.3" />
|
||||
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="10.6.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
|
||||
@@ -74,7 +85,7 @@
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
|
||||
<PackageReference Include="MimeKit" Version="4.16.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenccNetLib" Version="1.7.0" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||
@@ -84,13 +95,11 @@
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="NCalc" Version="6.2.0" />
|
||||
<PackageReference Include="PresentMonFps" Version="2.0.5" />
|
||||
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
|
||||
<PackageReference Include="Semver" Version="3.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.1" />
|
||||
<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.7" />
|
||||
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
|
||||
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
|
||||
@@ -101,7 +110,7 @@
|
||||
<PackageReference Include="WPF-UI" Version="4.3.0" />
|
||||
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="4.3.0" />
|
||||
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.3" />
|
||||
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.15" />
|
||||
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
@@ -266,5 +275,21 @@
|
||||
<ItemGroup>
|
||||
<_DeploymentManifestIconFile Remove="Resources\Images\logo.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<!--
|
||||
Melanchall.DryWetMidi 的 build\Melanchall.DryWetMidi.targets 会无条件把 x86/x64/macOS
|
||||
三份本地库都复制到输出目录(它没有使用 runtimes/{rid}/native 结构,不感知 RID)。
|
||||
本项目只支持 win-x64,这里在 AssignTargetPaths 之前把多余的 Native32.dll(x86)
|
||||
和 Native64.dylib(macOS)从 None 项中移除,避免它们被打进 Release 产物。
|
||||
-->
|
||||
<Target Name="RemoveDryWetMidiUnusedNativeLibs" BeforeTargets="AssignTargetPaths">
|
||||
<ItemGroup>
|
||||
<None Remove="@(None)" Condition="'%(Filename)' == 'Melanchall_DryWetMidi_Native32' Or ('%(Filename)' == 'Melanchall_DryWetMidi_Native64' And '%(Extension)' == '.dylib')" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<!-- 古树测试样例用于推理运行库验证与设置页测速。 -->
|
||||
<ItemGroup>
|
||||
<None Update="Assets\Model\Domain\test_petrified_trees.jpg" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,3 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -6,7 +7,6 @@ using System.Runtime.ExceptionServices;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
@@ -534,23 +534,23 @@ internal sealed class BvFlowServices
|
||||
Delay = async milliseconds => await page.Wait(milliseconds),
|
||||
GetTimestamp = System.Diagnostics.Stopwatch.GetTimestamp,
|
||||
GetElapsedMilliseconds = startedAt => System.Diagnostics.Stopwatch.GetElapsedTime(startedAt).TotalMilliseconds,
|
||||
KeyPress = key => Simulation.SendInput.Keyboard.KeyPress(key),
|
||||
KeyPress = key => InputHub.Foreground.Keyboard.KeyPress(key),
|
||||
LeftClick = GameCaptureRegion.GameRegion1080PPosClick,
|
||||
RightClick = (x, y) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(x, y);
|
||||
Simulation.SendInput.Mouse.RightButtonClick();
|
||||
InputHub.Foreground.Mouse.RightButtonClick();
|
||||
},
|
||||
MiddleClick = (x, y) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(x, y);
|
||||
Simulation.SendInput.Mouse.MiddleButtonClick();
|
||||
InputHub.Foreground.Mouse.MiddleButtonClick();
|
||||
},
|
||||
MoveTo = GameCaptureRegion.GameRegion1080PPosMove,
|
||||
Drag = async (fromX, fromY, toX, toY, duration) =>
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosMove(fromX, fromY);
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
InputHub.Foreground.Mouse.LeftButtonDown();
|
||||
try
|
||||
{
|
||||
var firstDelay = duration / 2;
|
||||
@@ -560,7 +560,7 @@ internal sealed class BvFlowServices
|
||||
}
|
||||
finally
|
||||
{
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
InputHub.Foreground.Mouse.LeftButtonUp();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,12 +4,11 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
@@ -20,9 +19,9 @@ public class BvPage
|
||||
private static readonly ILogger Logger = App.GetLogger<BvPage>();
|
||||
private readonly CancellationToken _cancellationToken;
|
||||
|
||||
public IKeyboardSimulator Keyboard => Simulation.SendInput.Keyboard;
|
||||
public IKeyboardInput Keyboard => InputHub.Foreground.Keyboard;
|
||||
|
||||
public IMouseSimulator Mouse => Simulation.SendInput.Mouse;
|
||||
public IMouseInput Mouse => InputHub.Foreground.Mouse;
|
||||
|
||||
/// <summary>
|
||||
/// Default timeout for operations in milliseconds
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoBoss;
|
||||
using BetterGenshinImpact.GameTask.AutoCombo.ComboBuild;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
@@ -60,6 +61,20 @@ public partial class AllConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _triggerInterval = 50;
|
||||
|
||||
/// <summary>
|
||||
/// WGC V2 帧率上限(毫秒,即最小更新间隔,限制 DWM 推帧频率以降低 GPU 占用)
|
||||
/// 0 = 不启用限流(默认);仅 Windows 11 24H2 及以上系统生效
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _wgcMinUpdateIntervalMs;
|
||||
|
||||
/// <summary>
|
||||
/// WGC V2 使用 CPU 颜色转换(BGRA→BGR 由 CPU CvtColor 完成)
|
||||
/// 默认关闭 = GPU compute shader 打包 BGR24(回读量更小、CPU 零转换);重启捕获后生效
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _wgcV2UseCpuConvert;
|
||||
|
||||
// /// <summary>
|
||||
// /// WGC使用位图缓存
|
||||
// /// 高帧率情况下,可能会导致卡顿
|
||||
@@ -131,6 +146,11 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public AutoFishingConfig AutoFishingConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动连招配置
|
||||
/// </summary>
|
||||
public AutoComboBuildConfig AutoComboBuildConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 快速传送配置
|
||||
/// </summary>
|
||||
@@ -272,49 +292,38 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public ChildSessionConfig ChildSessionConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 任意配置项变更后的回调(由 ConfigService 设置为防抖保存)
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
private ConfigChangeTracker? _changeTracker;
|
||||
|
||||
/// <summary>
|
||||
/// 开始追踪整个配置对象图的变更(含嵌套对象与集合),重复调用无副作用
|
||||
/// </summary>
|
||||
public void InitEvent()
|
||||
{
|
||||
PropertyChanged += OnAnyPropertyChanged;
|
||||
MaskWindowConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
CommonConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
if (_changeTracker != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
|
||||
KeyBindingsConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoBossConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoStygianOnslaughtConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
TpConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MusicConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
DevConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ChildSessionConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
_changeTracker = new ConfigChangeTracker(OnConfigChanged);
|
||||
_changeTracker.Track(this);
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
/// <param name="sender">触发变更的对象(某个子配置、嵌套对象或集合)</param>
|
||||
private void OnConfigChanged(object sender)
|
||||
{
|
||||
GameTaskManager.RefreshTriggerConfigs();
|
||||
// 实时触发器每帧读取配置,不需要在这里通知;只有切换遮罩显示相关的开关时清掉旧的识别结果
|
||||
if (sender is MaskWindowConfig)
|
||||
{
|
||||
TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.ClearAll();
|
||||
}
|
||||
|
||||
OnAnyChangedAction?.Invoke();
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,18 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
[Serializable]
|
||||
public partial class ChildSessionConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 桌面分身普通窗口模式的位置(物理像素坐标)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private WindowPositionConfig? _normalWindowPosition;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身小窗模式的位置(物理像素坐标)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private WindowPositionConfig? _smallWindowPosition;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身窗口是否置顶。
|
||||
/// </summary>
|
||||
@@ -41,4 +53,28 @@ public partial class ChildSessionConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _audioMuted = false;
|
||||
|
||||
/// <summary>
|
||||
/// 桌面分身是否处于观看模式。开启后键鼠不会在桌面分身内生效,仅显示画面。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _watchModeEnabled = false;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public sealed class WindowPositionConfig
|
||||
{
|
||||
public int Left { get; set; }
|
||||
|
||||
public int Top { get; set; }
|
||||
|
||||
public WindowPositionConfig()
|
||||
{
|
||||
}
|
||||
|
||||
public WindowPositionConfig(int left, int top)
|
||||
{
|
||||
Left = left;
|
||||
Top = top;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Media;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -62,6 +63,30 @@ public partial class CommonConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private WindowBackdropType _currentBackdropType = WindowBackdropType.Mica;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用主窗口自定义背景图
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _mainBackgroundEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口自定义背景图路径,空字符串表示未设置
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _mainBackgroundImagePath = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口背景图不透明度,数值越小背景越淡,文字越清晰
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _mainBackgroundOpacity = 0.35;
|
||||
|
||||
/// <summary>
|
||||
/// 主窗口背景图拉伸模式
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private Stretch _mainBackgroundStretch = Stretch.UniformToFill;
|
||||
|
||||
/// <summary>
|
||||
/// 是否是第一次运行
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 递归追踪配置对象图中所有 <see cref="INotifyPropertyChanged"/> / <see cref="INotifyCollectionChanged"/> 节点的变更。
|
||||
/// <para>
|
||||
/// 订阅是增量且幂等的:
|
||||
/// 1. 已访问对象记录在 <see cref="ConditionalWeakTable{TKey,TValue}"/> 中,同一对象只订阅一次,也天然防环,且不阻止 GC;
|
||||
/// 2. 属性被整体替换为新对象、集合新增元素时,只补订阅新出现的对象;
|
||||
/// 3. 被替换掉的旧对象不主动退订,它们之后再触发事件也只是多一次无害的变更回调。
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// 不做全量重扫:根节点上的子配置是无通知的自动属性,运行时可能被临时替换(如地脉花任务临时替换 AutoFightConfig),
|
||||
/// 全量重扫会把追踪挂到临时对象上。
|
||||
/// </para>
|
||||
/// 回调在触发事件的线程上同步执行。
|
||||
/// </summary>
|
||||
internal sealed class ConfigChangeTracker
|
||||
{
|
||||
/// <summary>
|
||||
/// 递归深度上限,防御异常的对象图
|
||||
/// </summary>
|
||||
private const int MaxDepth = 32;
|
||||
|
||||
private static readonly object Marker = new();
|
||||
|
||||
/// <summary>
|
||||
/// 每个类型可继续向下追踪的属性(按属性名索引)
|
||||
/// </summary>
|
||||
private static readonly ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> TrackablePropertyCache = new();
|
||||
|
||||
private readonly ConditionalWeakTable<object, object> _tracked = new();
|
||||
private readonly object _trackedLocker = new();
|
||||
private readonly Action<object> _onChanged;
|
||||
|
||||
/// <param name="onChanged">任意节点变更时回调,参数为触发事件的对象(属性所属对象或集合本身)</param>
|
||||
public ConfigChangeTracker(Action<object> onChanged)
|
||||
{
|
||||
_onChanged = onChanged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从根节点开始追踪
|
||||
/// </summary>
|
||||
public void Track(object root)
|
||||
{
|
||||
Visit(root, 0);
|
||||
}
|
||||
|
||||
private void Visit(object? node, int depth)
|
||||
{
|
||||
if (node == null || depth > MaxDepth || !IsTrackableInstance(node))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_trackedLocker)
|
||||
{
|
||||
if (_tracked.TryGetValue(node, out _))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_tracked.Add(node, Marker);
|
||||
}
|
||||
|
||||
if (node is INotifyPropertyChanged npc)
|
||||
{
|
||||
npc.PropertyChanged += OnPropertyChanged;
|
||||
}
|
||||
|
||||
if (node is INotifyCollectionChanged ncc)
|
||||
{
|
||||
ncc.CollectionChanged += OnCollectionChanged;
|
||||
}
|
||||
|
||||
VisitChildren(node, depth);
|
||||
}
|
||||
|
||||
private void VisitChildren(object node, int depth)
|
||||
{
|
||||
VisitItems(node, depth);
|
||||
|
||||
if (node is not INotifyPropertyChanged)
|
||||
{
|
||||
// 只沿着可通知对象向下展开属性,普通 POCO(如 GiTpPosition)没有变更通知,且可能存在会抛异常的计算属性
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var property in GetTrackableProperties(node.GetType()).Values)
|
||||
{
|
||||
Visit(TryGetValue(property, node), depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void VisitItems(object node, int depth)
|
||||
{
|
||||
if (node is string)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
switch (node)
|
||||
{
|
||||
case IDictionary dictionary:
|
||||
// 先拷贝一份,缩短与其他线程并发修改的冲突窗口
|
||||
foreach (var value in dictionary.Values.Cast<object?>().ToArray())
|
||||
{
|
||||
Visit(value, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
case IEnumerable enumerable:
|
||||
foreach (var item in enumerable.Cast<object?>().ToArray())
|
||||
{
|
||||
Visit(item, depth + 1);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ArgumentException)
|
||||
{
|
||||
// 其他线程正在修改集合,尽力而为:新元素会在下一次 CollectionChanged 或属性替换时补订阅
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPropertyChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (sender == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(e.PropertyName))
|
||||
{
|
||||
// 约定:属性名为空表示所有属性都已变化
|
||||
VisitChildren(sender, 0);
|
||||
}
|
||||
else if (GetTrackableProperties(sender.GetType()).TryGetValue(e.PropertyName, out var property))
|
||||
{
|
||||
// 子对象可能被整体替换,补订阅新值
|
||||
Visit(TryGetValue(property, sender), 0);
|
||||
}
|
||||
|
||||
_onChanged(sender);
|
||||
}
|
||||
|
||||
private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
|
||||
{
|
||||
if (sender == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Action == NotifyCollectionChangedAction.Reset)
|
||||
{
|
||||
VisitItems(sender, 0);
|
||||
}
|
||||
else if (e.NewItems != null)
|
||||
{
|
||||
foreach (var item in e.NewItems)
|
||||
{
|
||||
Visit(item, 0);
|
||||
}
|
||||
}
|
||||
|
||||
_onChanged(sender);
|
||||
}
|
||||
|
||||
private static object? TryGetValue(PropertyInfo property, object owner)
|
||||
{
|
||||
try
|
||||
{
|
||||
return property.GetValue(owner);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 计算属性可能抛异常(如依赖未初始化的数据),跳过即可
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只追踪可能产生变更通知或包含可通知元素的引用类型实例
|
||||
/// </summary>
|
||||
private static bool IsTrackableInstance(object node)
|
||||
{
|
||||
if (node is string or Delegate or MemberInfo || node.GetType().IsValueType)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return node is INotifyPropertyChanged or INotifyCollectionChanged or IEnumerable;
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetTrackableProperties(Type type)
|
||||
{
|
||||
return TrackablePropertyCache.GetOrAdd(type, static t => t
|
||||
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
|
||||
.Where(IsTrackableProperty)
|
||||
// 派生类用 new 隐藏基类属性时会出现同名属性,取第一个(最派生)即可
|
||||
.GroupBy(p => p.Name, StringComparer.Ordinal)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static bool IsTrackableProperty(PropertyInfo property)
|
||||
{
|
||||
if (property.GetMethod is not { IsPublic: true } || property.GetIndexParameters().Length > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var propertyType = property.PropertyType;
|
||||
if (propertyType.IsValueType || propertyType == typeof(string) || typeof(Delegate).IsAssignableFrom(propertyType))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 不参与序列化的属性不属于配置内容
|
||||
var jsonIgnore = property.GetCustomAttribute<JsonIgnoreAttribute>();
|
||||
return jsonIgnore is not { Condition: JsonIgnoreCondition.Always };
|
||||
}
|
||||
}
|
||||
@@ -1,90 +1,102 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
[JsonConverter(typeof(HardwareAccelerationConfigJsonConverter))]
|
||||
public partial class HardwareAccelerationConfig : ObservableObject
|
||||
{
|
||||
// 缺少新结构标识时不迁移旧参数,由启动准备流程使用 CPU 默认设置。
|
||||
[ObservableProperty] private int _formatVersion;
|
||||
[ObservableProperty] private InferenceEngineSettings _cpu = new() { DeviceId = "CPU" };
|
||||
[ObservableProperty] private PaddleOcrCpuConfig _paddleOcrCpu = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _directML = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _openVINO = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _cuda = new();
|
||||
[ObservableProperty] private InferenceEngineSettings _tensorRT = new();
|
||||
[ObservableProperty] private InferenceValidationState _validationState;
|
||||
[ObservableProperty] private string _verifiedSignature = "";
|
||||
// 历史成功记录仅用于设置页展示,不能代替当前设备和参数的验证签名。
|
||||
[ObservableProperty] private InferenceDeviceType[] _validatedEngines = [];
|
||||
[ObservableProperty] private InferenceDeviceType? _lastFailedEngine;
|
||||
[ObservableProperty] private string _lastValidationError = "";
|
||||
|
||||
public InferenceEngineSettings GetEngineSettings(InferenceDeviceType engine) => engine switch
|
||||
{
|
||||
InferenceDeviceType.Cpu => Cpu,
|
||||
InferenceDeviceType.DirectML => DirectML,
|
||||
InferenceDeviceType.OpenVINO => OpenVINO,
|
||||
InferenceDeviceType.CUDA => Cuda,
|
||||
InferenceDeviceType.TensorRT => TensorRT,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(engine))
|
||||
};
|
||||
|
||||
public void RecordValidatedEngine(InferenceDeviceType engine)
|
||||
{
|
||||
if (engine != InferenceDeviceType.Cpu && !ValidatedEngines.Contains(engine))
|
||||
ValidatedEngines = [.. ValidatedEngines, engine];
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsExpectedConfiguration => FormatVersion == 1 && Enum.IsDefined(InferenceDevice)
|
||||
&& Enum.IsDefined(ValidationState) && Cpu != null && DirectML != null && OpenVINO != null
|
||||
&& Cuda != null && TensorRT != null && Cpu.CpuThreads >= 0
|
||||
&& Cpu.CpuThreads <= Environment.ProcessorCount
|
||||
&& !string.IsNullOrWhiteSpace(GetEngineSettings(InferenceDevice).DeviceId);
|
||||
|
||||
/// <summary>配置结构损坏时恢复完整默认值。运行时回退不得调用此方法。</summary>
|
||||
public void ResetToDefaults()
|
||||
{
|
||||
FormatVersion = 1;
|
||||
Cpu = new() { DeviceId = "CPU" };
|
||||
PaddleOcrCpu = new();
|
||||
DirectML = new(); OpenVINO = new(); Cuda = new(); TensorRT = new();
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
CpuOcr = true;
|
||||
ValidationState = InferenceValidationState.None;
|
||||
VerifiedSignature = "";
|
||||
}
|
||||
|
||||
/// <summary>只把当前生效选择切换为 CPU,保留其他引擎、OCR 和线程设置。</summary>
|
||||
public void SwitchToCpu()
|
||||
{
|
||||
FormatVersion = 1;
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
Cpu.DeviceId = "CPU";
|
||||
ValidationState = InferenceValidationState.None;
|
||||
VerifiedSignature = "";
|
||||
}
|
||||
/// <summary>
|
||||
/// 推理使用的设备。默认CPU
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
|
||||
|
||||
partial void OnInferenceDeviceChanged(InferenceDeviceType value)
|
||||
{
|
||||
// 脚本或其他调用方写入历史编号、未知值时,也与配置读取保持一致。
|
||||
if (!Enum.IsDefined(value)) InferenceDevice = InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _cpuOcr = true;
|
||||
|
||||
#region 一般GPU加速设置
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定gpu设备,默认为0(使用默认设备)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _gpuDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 附加path,用;分割。默认为空。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _additionalPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// 是否输出优化后的模型文件到缓存。注意:在不支持的执行器上使用会导致异常。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _optimizedModel = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region cuda设置
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定cuda设备,默认为0(使用默认设备)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _cudaDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 自动附加cuda的path。一般情况下用这个就足够了。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoAppendCudaPath = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region TensorRT缓存设置
|
||||
|
||||
/// <summary>
|
||||
/// 启用TensorRT缓存。默认开启。不开的话使用TensorRT每次加载模型会卡爆。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableTensorRtCache = true;
|
||||
|
||||
/// <summary>
|
||||
/// 嵌入式引擎缓存。将引擎缓存嵌入到模型中。默认开启。关闭它可能会提高性能(如果不爆炸的话)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _embedTensorRtCache = true;
|
||||
|
||||
#endregion
|
||||
|
||||
#region OpenVINO设置
|
||||
/// <summary>
|
||||
/// OpenVino 设备参数。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _openVinoDevice = "AUTO:GPU,CPU";
|
||||
|
||||
/// <summary>
|
||||
/// 启用 OpenVINO 缓存。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableOpenVinoCache = false;
|
||||
|
||||
#region 已移除参数的源注释(不读取、不保存,也不参与新推理设置)
|
||||
// 强制指定gpu设备,默认为0(使用默认设备)
|
||||
// 附加path,用;分割。默认为空。
|
||||
// 是否输出优化后的模型文件到缓存。注意:在不支持的执行器上使用会导致异常。默认关闭。
|
||||
// 强制指定cuda设备,默认为0(使用默认设备)
|
||||
// 自动附加cuda的path。一般情况下用这个就足够了。默认关闭。
|
||||
// 启用TensorRT缓存。默认开启。不开的话使用TensorRT每次加载模型会卡爆。
|
||||
// 嵌入式引擎缓存。将引擎缓存嵌入到模型中。默认开启。关闭它可能会提高性能(如果不爆炸的话)。
|
||||
// OpenVino 设备参数。
|
||||
// 启用 OpenVINO 缓存。默认关闭。
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>把无效推理字段隔离在硬件设置内,不能因为单个字段错误重置整份用户配置。</summary>
|
||||
public sealed class HardwareAccelerationConfigJsonConverter : JsonConverter<HardwareAccelerationConfig>
|
||||
{
|
||||
public override HardwareAccelerationConfig Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
using var document = JsonDocument.ParseValue(ref reader);
|
||||
try
|
||||
{
|
||||
var data = document.RootElement.Deserialize<SerializedConfiguration>(options);
|
||||
if (data == null) return new();
|
||||
return new()
|
||||
{
|
||||
FormatVersion = data.FormatVersion, InferenceDevice = data.InferenceDevice, CpuOcr = data.CpuOcr,
|
||||
Cpu = data.Cpu!, DirectML = data.DirectML!, OpenVINO = data.OpenVINO!, Cuda = data.Cuda!, TensorRT = data.TensorRT!,
|
||||
PaddleOcrCpu = data.PaddleOcrCpu ?? new(),
|
||||
ValidationState = data.ValidationState, VerifiedSignature = data.VerifiedSignature ?? "",
|
||||
ValidatedEngines = data.ValidatedEngines ?? [],
|
||||
LastFailedEngine = data.LastFailedEngine, LastValidationError = data.LastValidationError ?? ""
|
||||
};
|
||||
}
|
||||
catch (JsonException) { return new(); }
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, HardwareAccelerationConfig value, JsonSerializerOptions options)
|
||||
=> JsonSerializer.Serialize(writer, new SerializedConfiguration
|
||||
{
|
||||
FormatVersion = value.FormatVersion, InferenceDevice = value.InferenceDevice, CpuOcr = value.CpuOcr,
|
||||
Cpu = value.Cpu, DirectML = value.DirectML, OpenVINO = value.OpenVINO, Cuda = value.Cuda, TensorRT = value.TensorRT,
|
||||
PaddleOcrCpu = value.PaddleOcrCpu,
|
||||
ValidationState = value.ValidationState, VerifiedSignature = value.VerifiedSignature,
|
||||
ValidatedEngines = value.ValidatedEngines,
|
||||
LastFailedEngine = value.LastFailedEngine, LastValidationError = value.LastValidationError
|
||||
}, options);
|
||||
|
||||
private sealed class SerializedConfiguration
|
||||
{
|
||||
public SerializedConfiguration() { }
|
||||
public int FormatVersion { get; set; }
|
||||
public InferenceDeviceType InferenceDevice { get; set; }
|
||||
public bool CpuOcr { get; set; } = true;
|
||||
public InferenceEngineSettings? Cpu { get; set; }
|
||||
public PaddleOcrCpuConfig? PaddleOcrCpu { get; set; }
|
||||
public InferenceEngineSettings? DirectML { get; set; }
|
||||
public InferenceEngineSettings? OpenVINO { get; set; }
|
||||
public InferenceEngineSettings? Cuda { get; set; }
|
||||
public InferenceEngineSettings? TensorRT { get; set; }
|
||||
public InferenceValidationState ValidationState { get; set; }
|
||||
public string? VerifiedSignature { get; set; }
|
||||
public InferenceDeviceType[]? ValidatedEngines { get; set; }
|
||||
public InferenceDeviceType? LastFailedEngine { get; set; }
|
||||
public string? LastValidationError { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,12 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _autoBossRunCount = 1;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _autoBossTotalRunCountLimit = 0;
|
||||
|
||||
[ObservableProperty]
|
||||
private int _autoBossCompletedRunCount = 0;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _autoBossUseTransientResin = false;
|
||||
|
||||
@@ -104,6 +110,22 @@ public partial class OneDragonFlowConfig : ObservableObject
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnAutoBossTotalRunCountLimitChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
AutoBossTotalRunCountLimit = 0;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnAutoBossCompletedRunCountChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
{
|
||||
AutoBossCompletedRunCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnAutoBossReviveRetryCountChanged(int value)
|
||||
{
|
||||
if (value < 0)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -12,12 +13,18 @@ public partial class OtherConfig : ObservableObject
|
||||
//调度器任务和部分独立任务,失去焦点,自动激活游戏窗口
|
||||
[ObservableProperty]
|
||||
private bool _restoreFocusOnLostEnabled = false;
|
||||
//窗口类名优先检测:原版仅靠进程名+MainWindowHandle 查找游戏窗口,该句柄为 0 或指向错误窗口时会找不到。开启后优先按窗口类名枚举检测,未命中再按进程枚举取客户区最大的可见窗口,仍不命中才回退原版方式。即时生效(每次查找窗口时读取),默认关闭,关闭时行为与旧版完全一致
|
||||
[ObservableProperty]
|
||||
private bool _windowClassDetectPreferred = false;
|
||||
//自动领取派遣任务城市
|
||||
[ObservableProperty]
|
||||
private string _autoFetchDispatchAdventurersGuildCountry = "无";
|
||||
//服务器时区偏移量
|
||||
[ObservableProperty]
|
||||
private TimeSpan _serverTimeZoneOffset = TimeSpan.FromHours(8);
|
||||
//物品图标识别模型
|
||||
[ObservableProperty]
|
||||
private ItemIconRecognitionMode _itemIconRecognitionMode = ItemIconRecognitionMode.Item;
|
||||
[ObservableProperty]
|
||||
private AutoRestart _autoRestartConfig = new();
|
||||
//锄地规划
|
||||
@@ -121,4 +128,5 @@ public partial class OtherConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _uiCultureInfoName = "zh-Hans";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>OCR 纯 CPU 推理的独立线程设置,默认跟随全局 CPU 线程数。</summary>
|
||||
public partial class PaddleOcrCpuConfig : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private PaddleOcrCpuMode _mode;
|
||||
[ObservableProperty] private int _detectionThreads = Math.Min(2, Environment.ProcessorCount);
|
||||
[ObservableProperty] private int _recognitionThreads = Math.Min(2, Environment.ProcessorCount);
|
||||
[ObservableProperty] private int _interOpThreads = 1;
|
||||
[ObservableProperty] private bool _parallelExecution;
|
||||
[ObservableProperty] private bool _allowSpinning = true;
|
||||
|
||||
public PaddleOcrCpuOptions ToOptions() => new()
|
||||
{
|
||||
Mode = Mode, DetectionThreads = DetectionThreads, RecognitionThreads = RecognitionThreads,
|
||||
InterOpThreads = InterOpThreads, ParallelExecution = ParallelExecution, AllowSpinning = AllowSpinning
|
||||
};
|
||||
|
||||
public static PaddleOcrCpuConfig FromOptions(PaddleOcrCpuOptions options) => new()
|
||||
{
|
||||
Mode = options.Mode, DetectionThreads = options.DetectionThreads, RecognitionThreads = options.RecognitionThreads,
|
||||
InterOpThreads = options.InterOpThreads, ParallelExecution = options.ParallelExecution, AllowSpinning = options.AllowSpinning
|
||||
};
|
||||
}
|
||||
@@ -263,10 +263,12 @@ public partial class PathingPartyConfig : ObservableObject
|
||||
|
||||
public static PathingPartyConfig BuildDefault()
|
||||
{
|
||||
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
|
||||
// 运行时回退配置保持禁用标记,确保继续使用地图追踪条件和独立战斗配置
|
||||
var pathingConditionConfig = TaskContext.Instance().Config.PathingConditionConfig;
|
||||
return new PathingPartyConfig
|
||||
{
|
||||
Enabled = false,
|
||||
AutoFightEnabled = false,
|
||||
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
|
||||
RecoverTiming = pathingConditionConfig.RecoverTiming,
|
||||
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Gamepad;
|
||||
|
||||
/// <summary>
|
||||
/// 手柄后端(预留,未实现)。前后台返回同一个通道,所有操作都 warn 后忽略。
|
||||
/// </summary>
|
||||
public sealed class GamepadInputBackend : IInputBackend
|
||||
{
|
||||
private readonly GamepadChannel _channel = new();
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.Gamepad;
|
||||
|
||||
public IInputChannel Foreground => _channel;
|
||||
|
||||
public IInputChannel Background => _channel;
|
||||
|
||||
public void ReleaseAll() => _channel.ReleaseAll();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 手柄通道(预留,未实现)。
|
||||
/// <para>实现时的约定:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item>覆写 SimulateAction,把 GIActions 直接映射成手柄输入;</item>
|
||||
/// <item>键盘按键按键位配置反查成 GIActions 再映射;</item>
|
||||
/// <item>MoveMouseBy 映射到右摇杆,是阻塞调用;</item>
|
||||
/// <item>原始鼠标按键和 MoveMouseTo 都 warn 后忽略。坐标点击由“移动 + 左键”两步组成,只忽略移动的话,左键会被映射成普攻。</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal sealed class GamepadChannel : InputChannelBase
|
||||
{
|
||||
private const string NotImplemented = "手柄后端未实现";
|
||||
|
||||
protected override void OnKeyDown(User32.VK key) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnMoveTo(double absX, double absY) => WarnUnsupported(NotImplemented);
|
||||
|
||||
protected override void OnScroll(int clicks) => WarnUnsupported(NotImplemented);
|
||||
|
||||
/// <summary>
|
||||
/// 未实现时没有真正按下的键
|
||||
/// </summary>
|
||||
public override bool IsKeyDown(User32.VK key) => false;
|
||||
|
||||
public override void ReleaseAll() => TakePressedKeys();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版 JS SDK(Resources/JavaScript/ys-input-inject.js,编译为嵌入资源)的通用调用接口
|
||||
/// </summary>
|
||||
public interface IWebInputBridge
|
||||
{
|
||||
/// <summary>
|
||||
/// 调用页面 SDK <c>window.__ysInputInject[method](...args)</c>。
|
||||
/// 不等待执行结果,页面侧按到达顺序串行执行;失败由实现类记录日志。
|
||||
/// 可选参数请直接省略,不要传 null:JSON 的 null 不会触发 JS 的参数默认值。
|
||||
/// </summary>
|
||||
void Invoke(string method, params object[] args);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// VK 到 KeyboardEvent.code 的映射,SDK 的 keyDown / keyUp / tapKey 接收 code 字符串。
|
||||
/// 泛指的 Shift / Ctrl / Alt 映射为左侧键
|
||||
/// </summary>
|
||||
public static class WebKeyCodes
|
||||
{
|
||||
public static bool TryGetCode(User32.VK vk, out string code)
|
||||
{
|
||||
var value = (int)vk;
|
||||
code = value switch
|
||||
{
|
||||
>= 0x41 and <= 0x5A => $"Key{(char)value}",
|
||||
>= 0x30 and <= 0x39 => $"Digit{(char)value}",
|
||||
>= 0x70 and <= 0x7B => $"F{value - 0x6F}",
|
||||
>= 0x60 and <= 0x69 => $"Numpad{value - 0x60}",
|
||||
0x08 => "Backspace",
|
||||
0x09 => "Tab",
|
||||
0x0D => "Enter",
|
||||
0x10 or 0xA0 => "ShiftLeft",
|
||||
0xA1 => "ShiftRight",
|
||||
0x11 or 0xA2 => "ControlLeft",
|
||||
0xA3 => "ControlRight",
|
||||
0x12 or 0xA4 => "AltLeft",
|
||||
0xA5 => "AltRight",
|
||||
0x13 => "Pause",
|
||||
0x14 => "CapsLock",
|
||||
0x1B => "Escape",
|
||||
0x20 => "Space",
|
||||
0x21 => "PageUp",
|
||||
0x22 => "PageDown",
|
||||
0x23 => "End",
|
||||
0x24 => "Home",
|
||||
0x25 => "ArrowLeft",
|
||||
0x26 => "ArrowUp",
|
||||
0x27 => "ArrowRight",
|
||||
0x28 => "ArrowDown",
|
||||
0x2C => "PrintScreen",
|
||||
0x2D => "Insert",
|
||||
0x2E => "Delete",
|
||||
0x5B => "MetaLeft",
|
||||
0x5C => "MetaRight",
|
||||
0x6A => "NumpadMultiply",
|
||||
0x6B => "NumpadAdd",
|
||||
0x6D => "NumpadSubtract",
|
||||
0x6E => "NumpadDecimal",
|
||||
0x6F => "NumpadDivide",
|
||||
0x90 => "NumLock",
|
||||
0x91 => "ScrollLock",
|
||||
0xBA => "Semicolon",
|
||||
0xBB => "Equal",
|
||||
0xBC => "Comma",
|
||||
0xBD => "Minus",
|
||||
0xBE => "Period",
|
||||
0xBF => "Slash",
|
||||
0xC0 => "Backquote",
|
||||
0xDB => "BracketLeft",
|
||||
0xDC => "Backslash",
|
||||
0xDD => "BracketRight",
|
||||
0xDE => "Quote",
|
||||
_ => string.Empty,
|
||||
};
|
||||
return code.Length > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版后端:把通道操作翻译成页面 SDK(ys-input-inject.js)的函数调用。
|
||||
/// 网页版没有前后台之分,后端自身就是唯一的通道,<see cref="Foreground"/> 与 <see cref="Background"/> 都返回自己。
|
||||
/// <para>
|
||||
/// 指针位置由 SDK 保存(setAbsPosition),按键和相对移动默认使用它;按住时长使用 SDK 的默认值
|
||||
/// (keyHoldMs 60 ms、clickHoldMs 35 ms),需要调整时通过 <c>Sdk.Invoke("setDefaults", …)</c>。
|
||||
/// </para>
|
||||
/// 由 WebPageRuntimeProvider 创建,GameRuntimeService 负责 InputHub.Attach。
|
||||
/// </summary>
|
||||
public sealed class WebSdkInputBackend : InputChannelBase, IInputBackend
|
||||
{
|
||||
// TODO(云原神网页版):鼠标相对移动的偏差值尚未实测,暂按 1:1 透传。
|
||||
// dx/dy 原样作为 ClientCore.mouseMove 的 rel 参数发送,与桌面端 SendInput 的相对位移是否等价尚未验证。
|
||||
// 调用方传入前通常已乘过 TaskContext.DpiScale,标定时需要一并考虑。
|
||||
// 实测后只调整这两个系数,不要在业务代码里补偿。
|
||||
private const double RelativeMoveScaleX = 1.0;
|
||||
private const double RelativeMoveScaleY = 1.0;
|
||||
|
||||
// TODO(云原神网页版):滚轮的方向和步长尚未实测,暂按 Windows 的 120/格 透传。
|
||||
private const int WheelDeltaPerClick = 120;
|
||||
|
||||
private readonly Func<RECT> _canvasRect;
|
||||
|
||||
/// <param name="sdk">SDK 调用桥,由宿主持有并释放</param>
|
||||
/// <param name="canvasRect">游戏画面在屏幕上的物理像素矩形,应与截图区域一致</param>
|
||||
public WebSdkInputBackend(IWebInputBridge sdk, Func<RECT> canvasRect)
|
||||
{
|
||||
Sdk = sdk ?? throw new ArgumentNullException(nameof(sdk));
|
||||
_canvasRect = canvasRect ?? throw new ArgumentNullException(nameof(canvasRect));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扩展口:直接调用 SDK 的其他函数,用于键鼠接口表达不了的需求,例如 sendIme、sendClipboard、setDefaults、look
|
||||
/// </summary>
|
||||
public IWebInputBridge Sdk { get; }
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.WebSdk;
|
||||
|
||||
public IInputChannel Foreground => this;
|
||||
|
||||
public IInputChannel Background => this;
|
||||
|
||||
#region 原子操作
|
||||
|
||||
protected override void OnKeyDown(User32.VK key) => InvokeKey("keyDown", key);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => InvokeKey("keyUp", key);
|
||||
|
||||
protected override void OnKeyPress(User32.VK key) => InvokeKey("tapKey", key);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
if (TryGetButtonName(button, out var name))
|
||||
{
|
||||
Sdk.Invoke(down ? "mouseDown" : "mouseUp", name);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
if (TryGetButtonName(button, out var name))
|
||||
{
|
||||
Sdk.Invoke("click", name);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) =>
|
||||
Sdk.Invoke("mouseMove", dx * RelativeMoveScaleX, dy * RelativeMoveScaleY);
|
||||
|
||||
/// <summary>
|
||||
/// 桌面 0~65535 坐标 -> 屏幕物理像素 -> 相对游戏画面归一化到 0~1
|
||||
/// </summary>
|
||||
protected override void OnMoveTo(double absX, double absY)
|
||||
{
|
||||
var rect = _canvasRect();
|
||||
if (rect.Width <= 0 || rect.Height <= 0)
|
||||
{
|
||||
WarnUnsupported("游戏画面区域为空时的鼠标定位");
|
||||
return;
|
||||
}
|
||||
|
||||
var screen = PrimaryScreen.WorkingArea;
|
||||
var x = Math.Clamp((absX * screen.Width / 65535d - rect.Left) / rect.Width, 0d, 1d);
|
||||
var y = Math.Clamp((absY * screen.Height / 65535d - rect.Top) / rect.Height, 0d, 1d);
|
||||
|
||||
// 位置由 SDK 保存,后续按键和相对移动都使用它
|
||||
Sdk.Invoke("setAbsPosition", x, y);
|
||||
Sdk.Invoke("mouseMove", 0, 0);
|
||||
}
|
||||
|
||||
protected override void OnScroll(int clicks) => Sdk.Invoke("scroll", clicks * WheelDeltaPerClick);
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// SDK 的 releaseAll 会释放页面侧记录的全部按键,本地记录同步清空。
|
||||
/// 同时满足 <see cref="IInputChannel.ReleaseAll"/> 与 <see cref="IInputBackend.ReleaseAll"/>
|
||||
/// </summary>
|
||||
public override void ReleaseAll()
|
||||
{
|
||||
TakePressedKeys();
|
||||
try
|
||||
{
|
||||
Sdk.Invoke("releaseAll");
|
||||
}
|
||||
catch (InvalidOperationException e)
|
||||
{
|
||||
// 页面或桥接已关闭时无法再发送释放指令。ReleaseAll 常在 finally 中调用,不能让它抛出并掩盖原异常
|
||||
Logger.LogDebug(e, "云原神页面已关闭,跳过释放按键");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 桥接由宿主持有并释放,这里不释放
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private void InvokeKey(string method, User32.VK key)
|
||||
{
|
||||
if (WebKeyCodes.TryGetCode(key, out var code))
|
||||
{
|
||||
Sdk.Invoke(method, code);
|
||||
}
|
||||
else
|
||||
{
|
||||
WarnUnsupported($"按键 {key}");
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryGetButtonName(InputMouseButton button, out string name)
|
||||
{
|
||||
name = button switch
|
||||
{
|
||||
InputMouseButton.Left => "left",
|
||||
InputMouseButton.Right => "right",
|
||||
InputMouseButton.Middle => "middle",
|
||||
_ => string.Empty,
|
||||
};
|
||||
if (name.Length > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
WarnUnsupported($"鼠标键 {button}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.WebSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 基于 WebView2 的 SDK 调用桥:负责把 SDK 注入页面、把调用投递到页面、查询 SDK 状态。
|
||||
/// <para>
|
||||
/// 宿主只需调用 <see cref="InstallAsync"/>。本类不持有 WebView2 的生命周期,由宿主创建和释放。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class WebView2InputBridge : IWebInputBridge, IDisposable
|
||||
{
|
||||
private const string RequestChannel = "bgi.input";
|
||||
private const string ErrorChannel = "bgi.input.error";
|
||||
private const string SdkResourceName = "BetterGenshinImpact.Resources.JavaScript.ys-input-inject.js";
|
||||
|
||||
/// <summary>
|
||||
/// 同类 warn 的最小间隔,避免每次按键都刷日志
|
||||
/// </summary>
|
||||
private const long WarnIntervalMs = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// 页面侧分发脚本:按到达顺序串行调用 window.__ysInputInject 上的函数,只在失败时回报。
|
||||
/// 只在顶层文档生效:注入脚本也会在子 frame 中执行,而子 frame 没有 chrome.webview
|
||||
/// </summary>
|
||||
private const string BootstrapScript = """
|
||||
(() => {
|
||||
if (window.top !== window || !window.chrome?.webview || window.__bgiInputBridge) return;
|
||||
window.__bgiInputBridge = true;
|
||||
let queue = Promise.resolve();
|
||||
window.chrome.webview.addEventListener("message", ({ data }) => {
|
||||
if (!data || data.channel !== "bgi.input") return;
|
||||
const { method, args = [] } = data;
|
||||
// 串行执行:tapKey、click 等是异步函数,并发执行会打乱按键顺序
|
||||
queue = queue
|
||||
.then(() => {
|
||||
const sdk = window.__ysInputInject;
|
||||
if (!sdk || !Object.hasOwn(sdk, method) || typeof sdk[method] !== "function") {
|
||||
throw new Error(`unknown sdk method: ${method}`);
|
||||
}
|
||||
return sdk[method](...args);
|
||||
})
|
||||
.catch(e => window.chrome.webview.postMessage({
|
||||
channel: "bgi.input.error", method, error: String(e?.message ?? e)
|
||||
}));
|
||||
});
|
||||
})();
|
||||
""";
|
||||
|
||||
/// <summary>
|
||||
/// 状态查询脚本:SDK 未注入或页面尚未加载到游戏时 status() 会抛错,统一转成 error 字段
|
||||
/// </summary>
|
||||
private const string StatusScript = """
|
||||
(() => {
|
||||
try {
|
||||
const s = window.__ysInputInject?.status();
|
||||
if (!s) return { error: "sdk not installed" };
|
||||
return { rtcDataChannelState: s.rtcDataChannelState ?? null, gameDataStarted: s.gameDataStarted ?? null };
|
||||
} catch (e) {
|
||||
return { error: String(e?.message ?? e) };
|
||||
}
|
||||
})()
|
||||
""";
|
||||
|
||||
private static ILogger? _logger;
|
||||
private static string? _sdkScript;
|
||||
|
||||
private readonly CoreWebView2 _core;
|
||||
private readonly Dispatcher _dispatcher;
|
||||
private long _lastPostWarnTicks = long.MinValue;
|
||||
private long _lastErrorWarnTicks = long.MinValue;
|
||||
private volatile bool _disposed;
|
||||
|
||||
private WebView2InputBridge(CoreWebView2 core, Dispatcher dispatcher)
|
||||
{
|
||||
_core = core;
|
||||
_dispatcher = dispatcher;
|
||||
_core.WebMessageReceived += OnWebMessageReceived;
|
||||
}
|
||||
|
||||
private static ILogger Logger => _logger ??= App.GetLogger<WebView2InputBridge>();
|
||||
|
||||
/// <summary>
|
||||
/// 注入 SDK 与分发脚本(对之后的每次导航生效),然后返回桥。
|
||||
/// 必须在 CoreWebView2 所在的 UI 线程上、首次导航之前调用
|
||||
/// </summary>
|
||||
public static async Task<WebView2InputBridge> InstallAsync(CoreWebView2 core)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(core);
|
||||
var dispatcher = Dispatcher.CurrentDispatcher;
|
||||
|
||||
// SDK 本身不改动,外面包一层只在顶层文档执行
|
||||
await core.AddScriptToExecuteOnDocumentCreatedAsync($"if (window.top === window) {{\n{GetSdkScript()}\n}}");
|
||||
await core.AddScriptToExecuteOnDocumentCreatedAsync(BootstrapScript);
|
||||
return new WebView2InputBridge(core, dispatcher);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 投递一次 SDK 调用,不等待页面执行。可在任意线程调用:
|
||||
/// 其他线程经 Dispatcher.BeginInvoke 投递到 UI 线程,同优先级按先后顺序执行,任务线程不阻塞,也不会与等待任务的 UI 线程互相死锁;
|
||||
/// UI 线程上直接投递。桥已释放时抛出 <see cref="InvalidOperationException"/>
|
||||
/// </summary>
|
||||
public void Invoke(string method, params object[] args)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(method);
|
||||
if (_disposed)
|
||||
{
|
||||
throw new InvalidOperationException("云原神 WebView2 输入桥已释放");
|
||||
}
|
||||
|
||||
var json = JsonConvert.SerializeObject(new { channel = RequestChannel, method, args });
|
||||
if (_dispatcher.CheckAccess())
|
||||
{
|
||||
// UI 线程直接投递:保证宿主关闭前(Closing 中)发出的 releaseAll 能在页面销毁前送达
|
||||
Post(method, json);
|
||||
}
|
||||
else
|
||||
{
|
||||
_dispatcher.BeginInvoke(() => Post(method, json));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询 SDK 状态。在 UI 线程上调用(宿主的 DispatcherTimer),其他线程会被切到 UI 线程执行
|
||||
/// </summary>
|
||||
public async Task<WebSdkStatus> GetStatusAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return new WebSdkStatus(null, null, "bridge disposed");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = _dispatcher.CheckAccess()
|
||||
? await _core.ExecuteScriptAsync(StatusScript)
|
||||
: await _dispatcher.InvokeAsync(() => _core.ExecuteScriptAsync(StatusScript)).Task.Unwrap();
|
||||
var result = JToken.Parse(json) as JObject;
|
||||
return new WebSdkStatus(
|
||||
result?.Value<string>("rtcDataChannelState"),
|
||||
result?.Value<bool?>("gameDataStarted"),
|
||||
result?.Value<string>("error"));
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ObjectDisposedException or JsonException
|
||||
or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
// 页面正在导航或 WebView2 已关闭
|
||||
return new WebSdkStatus(null, null, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_core.WebMessageReceived -= OnWebMessageReceived;
|
||||
}
|
||||
|
||||
private void Post(string method, string json)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_core.PostWebMessageAsJson(json);
|
||||
}
|
||||
catch (Exception e) when (e is InvalidOperationException or ObjectDisposedException
|
||||
or System.Runtime.InteropServices.COMException)
|
||||
{
|
||||
// 页面已关闭或正在导航。调用方已经返回,只能记录
|
||||
if (ShouldWarn(ref _lastPostWarnTicks))
|
||||
{
|
||||
Logger.LogWarning("云原神 SDK 调用投递失败:{Method},{Error}", method, e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
|
||||
{
|
||||
JObject message;
|
||||
try
|
||||
{
|
||||
message = JObject.Parse(e.WebMessageAsJson);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// 不是 JSON 对象的消息与本桥无关
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(message.Value<string>("channel"), ErrorChannel, StringComparison.Ordinal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 页面断开由宿主的状态轮询发现,这里只记录调用错误
|
||||
if (ShouldWarn(ref _lastErrorWarnTicks))
|
||||
{
|
||||
Logger.LogWarning("云原神 SDK 调用失败:{Method},{Error}",
|
||||
message.Value<string>("method") ?? string.Empty,
|
||||
message.Value<string>("error") ?? "未知错误");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool ShouldWarn(ref long lastTicks)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var last = Interlocked.Read(ref lastTicks);
|
||||
if (last != long.MinValue && now - last < WarnIntervalMs)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Interlocked.Exchange(ref lastTicks, now);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string GetSdkScript()
|
||||
{
|
||||
if (_sdkScript != null)
|
||||
{
|
||||
return _sdkScript;
|
||||
}
|
||||
|
||||
using var stream = typeof(WebView2InputBridge).Assembly.GetManifestResourceStream(SdkResourceName)
|
||||
?? throw new InvalidOperationException($"找不到嵌入资源 {SdkResourceName}");
|
||||
using var reader = new StreamReader(stream);
|
||||
return _sdkScript = reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 页面 SDK 的状态快照
|
||||
/// </summary>
|
||||
/// <param name="RtcDataChannelState">RTC 数据通道状态,open 时输入才能发往云端</param>
|
||||
/// <param name="GameDataStarted">游戏数据通道是否已开始,即已进入游戏画面</param>
|
||||
/// <param name="Error">SDK 未注入、页面未加载到游戏或查询失败时的原因</param>
|
||||
public sealed record WebSdkStatus(string? RtcDataChannelState, bool? GameDataStarted, string? Error)
|
||||
{
|
||||
public bool IsReady => RtcDataChannelState == "open" && GameDataStarted == true;
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道:包装 PostMessageSimulator,向游戏窗口投递消息。
|
||||
/// 游戏不在前台时,每次操作前先补发 WM_ACTIVATE。
|
||||
/// 不支持相对移动、中键、侧键、滚轮(warn 后忽略)
|
||||
/// </summary>
|
||||
internal sealed class PostMessageChannel : InputChannelBase
|
||||
{
|
||||
private readonly IntPtr _hWnd;
|
||||
private readonly PostMessageSimulator? _simulator;
|
||||
|
||||
/// <summary>
|
||||
/// 后续点击使用的客户区坐标。未调用过 MoveMouseTo 时沿用原实现的 (16,16)
|
||||
/// </summary>
|
||||
private Point _pointer = new(16, 16);
|
||||
|
||||
public PostMessageChannel(IntPtr hWnd)
|
||||
{
|
||||
_hWnd = hWnd;
|
||||
_simulator = hWnd == IntPtr.Zero ? null : new PostMessageSimulator(hWnd);
|
||||
}
|
||||
|
||||
protected override void OnKeyDown(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyDown(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnKeyUp(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyUp(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnKeyPress(User32.VK key)
|
||||
{
|
||||
if (TryPrepare("按键"))
|
||||
{
|
||||
_simulator!.KeyPress(key);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
if (!IsSupported(button) || !TryPrepare("鼠标"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var (x, y) = (_pointer.X, _pointer.Y);
|
||||
_ = (button, down) switch
|
||||
{
|
||||
(InputMouseButton.Left, true) => _simulator!.LeftButtonDown(x, y),
|
||||
(InputMouseButton.Left, false) => _simulator!.LeftButtonUp(x, y),
|
||||
(InputMouseButton.Right, true) => _simulator!.RightButtonDown(x, y),
|
||||
_ => _simulator!.RightButtonUp(x, y),
|
||||
};
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
if (!IsSupported(button) || !TryPrepare("鼠标"))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = button == InputMouseButton.Left
|
||||
? _simulator!.LeftButtonClick(_pointer.X, _pointer.Y)
|
||||
: _simulator!.RightButtonClick(_pointer.X, _pointer.Y);
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => WarnUnsupported("后台相对移动 MoveMouseBy");
|
||||
|
||||
/// <summary>
|
||||
/// 换算成客户区坐标,记为后续点击的位置,不移动真实光标
|
||||
/// </summary>
|
||||
protected override void OnMoveTo(double absX, double absY)
|
||||
{
|
||||
if (_simulator is null)
|
||||
{
|
||||
WarnUnsupported("未绑定游戏窗口时的后台鼠标");
|
||||
return;
|
||||
}
|
||||
|
||||
var screen = PrimaryScreen.WorkingArea;
|
||||
var point = new POINT(
|
||||
(int)Math.Round(absX * screen.Width / 65535d),
|
||||
(int)Math.Round(absY * screen.Height / 65535d));
|
||||
if (!User32.ScreenToClient(_hWnd, ref point))
|
||||
{
|
||||
WarnUnsupported("后台鼠标坐标换算");
|
||||
return;
|
||||
}
|
||||
|
||||
_pointer = new Point(point.X, point.Y);
|
||||
}
|
||||
|
||||
protected override void OnScroll(int clicks) => WarnUnsupported("后台滚轮 VerticalScroll");
|
||||
|
||||
private bool IsSupported(InputMouseButton button)
|
||||
{
|
||||
if (button is InputMouseButton.Left or InputMouseButton.Right)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
WarnUnsupported($"后台鼠标键 {button}");
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查是否绑定了窗口,游戏不在前台时补发 WM_ACTIVATE
|
||||
/// </summary>
|
||||
private bool TryPrepare(string operation)
|
||||
{
|
||||
if (_simulator is null)
|
||||
{
|
||||
WarnUnsupported($"未绑定游戏窗口时的后台{operation}");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (User32.GetForegroundWindow() != _hWnd)
|
||||
{
|
||||
_simulator.Activate();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using Fischless.WindowsInput;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// 前台通道:包装 Simulation.SendInput(Fischless.WindowsInput)
|
||||
/// </summary>
|
||||
internal sealed class SendInputChannel : InputChannelBase
|
||||
{
|
||||
private static InputSimulator Input => Simulation.SendInput;
|
||||
|
||||
// 扩展标志按真实键盘判断(见 ExtendedKeys):左 Alt 等不带,避免被识别成右 Alt;方向键等带,避免被识别成小键盘按键。
|
||||
// 不使用 Fischless 的自动判断,它把左 Alt 与泛指的 Alt / Ctrl 也算作扩展键
|
||||
protected override void OnKeyDown(User32.VK key) => Input.Keyboard.KeyDown(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnKeyUp(User32.VK key) => Input.Keyboard.KeyUp(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnKeyPress(User32.VK key) => Input.Keyboard.KeyPress(ExtendedKeys.IsExtended(key), key);
|
||||
|
||||
protected override void OnMouseButton(InputMouseButton button, bool down)
|
||||
{
|
||||
var mouse = Input.Mouse;
|
||||
switch (button)
|
||||
{
|
||||
case InputMouseButton.Left:
|
||||
_ = down ? mouse.LeftButtonDown() : mouse.LeftButtonUp();
|
||||
break;
|
||||
case InputMouseButton.Right:
|
||||
_ = down ? mouse.RightButtonDown() : mouse.RightButtonUp();
|
||||
break;
|
||||
case InputMouseButton.Middle:
|
||||
_ = down ? mouse.MiddleButtonDown() : mouse.MiddleButtonUp();
|
||||
break;
|
||||
case InputMouseButton.X1:
|
||||
_ = down ? mouse.XButtonDown(0x0001) : mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
case InputMouseButton.X2:
|
||||
_ = down ? mouse.XButtonDown(0x0002) : mouse.XButtonUp(0x0002);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
var mouse = Input.Mouse;
|
||||
switch (button)
|
||||
{
|
||||
case InputMouseButton.Left:
|
||||
mouse.LeftButtonClick();
|
||||
break;
|
||||
case InputMouseButton.Right:
|
||||
mouse.RightButtonClick();
|
||||
break;
|
||||
case InputMouseButton.Middle:
|
||||
mouse.MiddleButtonClick();
|
||||
break;
|
||||
case InputMouseButton.X1:
|
||||
mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
case InputMouseButton.X2:
|
||||
mouse.XButtonClick(0x0002);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnMoveBy(int dx, int dy) => Input.Mouse.MoveMouseBy(dx, dy);
|
||||
|
||||
protected override void OnMoveTo(double absX, double absY) => Input.Mouse.MoveMouseTo(absX, absY);
|
||||
|
||||
protected override void OnScroll(int clicks) => Input.Mouse.VerticalScroll(clicks);
|
||||
|
||||
/// <summary>
|
||||
/// 与原 Simulation.IsKeyDown 一致,查询系统的实际按键状态
|
||||
/// </summary>
|
||||
public override bool IsKeyDown(User32.VK key) => Simulation.IsKeyDown(key);
|
||||
|
||||
/// <summary>
|
||||
/// 按记录抬起,再用 Simulation.ReleaseAllKey 兜底(与原 Simulation.ReleaseAllKey 行为一致)
|
||||
/// </summary>
|
||||
public override void ReleaseAll()
|
||||
{
|
||||
base.ReleaseAll();
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
|
||||
/// <summary>
|
||||
/// Windows 键鼠后端:前台 SendInput,后台 PostMessage。两路总是同时可用
|
||||
/// </summary>
|
||||
public sealed class Win32InputBackend : IInputBackend
|
||||
{
|
||||
/// <param name="hWnd">游戏窗口句柄。为 IntPtr.Zero 时后台通道的所有操作都 warn</param>
|
||||
public Win32InputBackend(IntPtr hWnd)
|
||||
{
|
||||
Foreground = new SendInputChannel();
|
||||
Background = new PostMessageChannel(hWnd);
|
||||
}
|
||||
|
||||
public InputBackendKind Kind => InputBackendKind.Win32;
|
||||
|
||||
public IInputChannel Foreground { get; }
|
||||
|
||||
public IInputChannel Background { get; }
|
||||
|
||||
public void ReleaseAll()
|
||||
{
|
||||
Background.ReleaseAll();
|
||||
Foreground.ReleaseAll();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 一组可以整体切换的输入输出:Win32 (SendInput + PostMessage)、WebSdk、Gamepad
|
||||
/// </summary>
|
||||
public interface IInputBackend : IDisposable
|
||||
{
|
||||
InputBackendKind Kind { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 前台通道
|
||||
/// </summary>
|
||||
IInputChannel Foreground { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道。WebSdk / Gamepad 没有前后台之分,与 <see cref="Foreground"/> 是同一实例
|
||||
/// </summary>
|
||||
IInputChannel Background { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 释放所有通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
void ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 输入通道:后端内部的一路输出(前台或后台)
|
||||
/// </summary>
|
||||
public interface IInputChannel
|
||||
{
|
||||
IKeyboardInput Keyboard { get; }
|
||||
|
||||
IMouseInput Mouse { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 模拟游戏动作,按键由用户的键位配置决定
|
||||
/// </summary>
|
||||
IInputChannel SimulateAction(GIActions action, KeyType type = KeyType.KeyPress);
|
||||
|
||||
/// <summary>
|
||||
/// 按键是否处于按下状态,含鼠标键 VK_LBUTTON 等
|
||||
/// </summary>
|
||||
bool IsKeyDown(User32.VK key);
|
||||
|
||||
IInputChannel Sleep(int ms);
|
||||
|
||||
/// <summary>
|
||||
/// 释放本通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
void ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 键盘输入。传入鼠标键 VK(VK_LBUTTON、VK_RBUTTON、VK_MBUTTON、VK_XBUTTON1、VK_XBUTTON2)时按对应鼠标键处理
|
||||
/// </summary>
|
||||
public interface IKeyboardInput
|
||||
{
|
||||
IKeyboardInput KeyDown(User32.VK key);
|
||||
|
||||
IKeyboardInput KeyUp(User32.VK key);
|
||||
|
||||
IKeyboardInput KeyPress(User32.VK key);
|
||||
|
||||
IKeyboardInput Sleep(int ms);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 鼠标输入。方法名与 Fischless.WindowsInput.IMouseSimulator 保持一致
|
||||
/// </summary>
|
||||
public interface IMouseInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 相对移动(视角控制)
|
||||
/// </summary>
|
||||
IMouseInput MoveMouseBy(int dx, int dy);
|
||||
|
||||
/// <summary>
|
||||
/// 绝对定位。与 Fischless 相同:桌面绝对坐标,按主屏幕归一化到 0~65535。
|
||||
/// 是否是 1080P 坐标由调用方(Region 体系)换算,输入层不感知游戏分辨率
|
||||
/// </summary>
|
||||
IMouseInput MoveMouseTo(double absX, double absY);
|
||||
|
||||
IMouseInput LeftButtonDown();
|
||||
|
||||
IMouseInput LeftButtonUp();
|
||||
|
||||
IMouseInput LeftButtonClick();
|
||||
|
||||
IMouseInput RightButtonDown();
|
||||
|
||||
IMouseInput RightButtonUp();
|
||||
|
||||
IMouseInput RightButtonClick();
|
||||
|
||||
IMouseInput MiddleButtonDown();
|
||||
|
||||
IMouseInput MiddleButtonUp();
|
||||
|
||||
IMouseInput MiddleButtonClick();
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonDown(int buttonId);
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonUp(int buttonId);
|
||||
|
||||
/// <param name="buttonId">1 = 侧键1(XBUTTON1),2 = 侧键2(XBUTTON2)</param>
|
||||
IMouseInput XButtonClick(int buttonId);
|
||||
|
||||
IMouseInput VerticalScroll(int scrollAmountInClicks);
|
||||
|
||||
IMouseInput Sleep(int ms);
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 输入通道基类。
|
||||
/// 一个实例同时实现通道、键盘、鼠标三个接口,<see cref="Keyboard"/> 与 <see cref="Mouse"/> 都返回自身。
|
||||
/// 负责:按下状态记录、GIActions 默认映射、鼠标键 VK 转发、不支持操作的限频 warn。
|
||||
/// 子类只需实现 On* 原子操作。
|
||||
/// </summary>
|
||||
public abstract class InputChannelBase : IInputChannel, IKeyboardInput, IMouseInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 同一种不支持的操作在此时间内只打一次 warn
|
||||
/// </summary>
|
||||
private const long WarnIntervalMs = 10_000;
|
||||
|
||||
private static ILogger? _logger;
|
||||
|
||||
private readonly object _pressedLock = new();
|
||||
private readonly HashSet<User32.VK> _pressed = [];
|
||||
private readonly ConcurrentDictionary<string, long> _lastWarnTicks = new();
|
||||
|
||||
protected static ILogger Logger => _logger ??= App.GetLogger<InputChannelBase>();
|
||||
|
||||
public IKeyboardInput Keyboard => this;
|
||||
|
||||
public IMouseInput Mouse => this;
|
||||
|
||||
#region 子类实现的原子操作
|
||||
|
||||
protected abstract void OnKeyDown(User32.VK key);
|
||||
|
||||
protected abstract void OnKeyUp(User32.VK key);
|
||||
|
||||
/// <summary>
|
||||
/// 默认为按下 + 抬起,子类可覆写以保持各自的时序
|
||||
/// </summary>
|
||||
protected virtual void OnKeyPress(User32.VK key)
|
||||
{
|
||||
OnKeyDown(key);
|
||||
OnKeyUp(key);
|
||||
}
|
||||
|
||||
protected abstract void OnMouseButton(InputMouseButton button, bool down);
|
||||
|
||||
/// <summary>
|
||||
/// 默认为按下 + 抬起,子类可覆写以保持各自的时序
|
||||
/// </summary>
|
||||
protected virtual void OnMouseClick(InputMouseButton button)
|
||||
{
|
||||
OnMouseButton(button, true);
|
||||
OnMouseButton(button, false);
|
||||
}
|
||||
|
||||
protected abstract void OnMoveBy(int dx, int dy);
|
||||
|
||||
protected abstract void OnMoveTo(double absX, double absY);
|
||||
|
||||
protected abstract void OnScroll(int clicks);
|
||||
|
||||
#endregion
|
||||
|
||||
#region IInputChannel
|
||||
|
||||
public virtual IInputChannel SimulateAction(GIActions action, KeyType type = KeyType.KeyPress)
|
||||
{
|
||||
var key = action.ToActionKey();
|
||||
if (key is KeyId.None or KeyId.Unknown)
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
// KeyId 的鼠标键取值与 VK 一致,鼠标键由 Keyboard 接口转发到鼠标
|
||||
var vk = key.ToVK();
|
||||
switch (type)
|
||||
{
|
||||
case KeyType.KeyPress:
|
||||
KeyPress(vk);
|
||||
break;
|
||||
case KeyType.KeyDown:
|
||||
KeyDown(vk);
|
||||
break;
|
||||
case KeyType.KeyUp:
|
||||
KeyUp(vk);
|
||||
break;
|
||||
case KeyType.Hold:
|
||||
KeyDown(vk);
|
||||
Thread.Sleep(1000);
|
||||
KeyUp(vk);
|
||||
break;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public virtual bool IsKeyDown(User32.VK key)
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
return _pressed.Contains(key);
|
||||
}
|
||||
}
|
||||
|
||||
IInputChannel IInputChannel.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按记录逐个抬起。单个按键失败不影响其余按键
|
||||
/// </summary>
|
||||
public virtual void ReleaseAll()
|
||||
{
|
||||
foreach (var key in TakePressedKeys())
|
||||
{
|
||||
try
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
OnMouseButton(button, false);
|
||||
}
|
||||
else
|
||||
{
|
||||
OnKeyUp(key);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.LogDebug(e, "释放按键 {Key} 失败", key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IKeyboardInput
|
||||
|
||||
public IKeyboardInput KeyDown(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonDown(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
OnKeyDown(key);
|
||||
SetPressed(key, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IKeyboardInput KeyUp(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonUp(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
SetPressed(key, false);
|
||||
OnKeyUp(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IKeyboardInput KeyPress(User32.VK key)
|
||||
{
|
||||
if (TryGetMouseButton(key, out var button))
|
||||
{
|
||||
ButtonClick(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
SetPressed(key, false);
|
||||
OnKeyPress(key);
|
||||
return this;
|
||||
}
|
||||
|
||||
IKeyboardInput IKeyboardInput.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IMouseInput
|
||||
|
||||
public IMouseInput MoveMouseBy(int dx, int dy)
|
||||
{
|
||||
OnMoveBy(dx, dy);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMouseInput MoveMouseTo(double absX, double absY)
|
||||
{
|
||||
OnMoveTo(absX, absY);
|
||||
return this;
|
||||
}
|
||||
|
||||
public IMouseInput LeftButtonDown() => ButtonDown(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput LeftButtonUp() => ButtonUp(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput LeftButtonClick() => ButtonClick(InputMouseButton.Left);
|
||||
|
||||
public IMouseInput RightButtonDown() => ButtonDown(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput RightButtonUp() => ButtonUp(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput RightButtonClick() => ButtonClick(InputMouseButton.Right);
|
||||
|
||||
public IMouseInput MiddleButtonDown() => ButtonDown(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput MiddleButtonUp() => ButtonUp(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput MiddleButtonClick() => ButtonClick(InputMouseButton.Middle);
|
||||
|
||||
public IMouseInput XButtonDown(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonDown(b) : this;
|
||||
|
||||
public IMouseInput XButtonUp(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonUp(b) : this;
|
||||
|
||||
public IMouseInput XButtonClick(int buttonId) => TryGetXButton(buttonId, out var b) ? ButtonClick(b) : this;
|
||||
|
||||
public IMouseInput VerticalScroll(int scrollAmountInClicks)
|
||||
{
|
||||
OnScroll(scrollAmountInClicks);
|
||||
return this;
|
||||
}
|
||||
|
||||
IMouseInput IMouseInput.Sleep(int ms)
|
||||
{
|
||||
Thread.Sleep(ms);
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 辅助
|
||||
|
||||
/// <summary>
|
||||
/// 不支持的操作:限频打 warn 后直接忽略
|
||||
/// </summary>
|
||||
protected void WarnUnsupported(string operation)
|
||||
{
|
||||
var now = Environment.TickCount64;
|
||||
var last = _lastWarnTicks.GetOrAdd(operation, long.MinValue);
|
||||
if (last != long.MinValue && now - last < WarnIntervalMs)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_lastWarnTicks[operation] = now;
|
||||
Logger.LogWarning("[{Channel}] 不支持的输入操作已忽略:{Operation}", GetType().Name, operation);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取出并清空按下记录
|
||||
/// </summary>
|
||||
protected IReadOnlyList<User32.VK> TakePressedKeys()
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
var keys = _pressed.ToList();
|
||||
_pressed.Clear();
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
|
||||
protected static bool TryGetMouseButton(User32.VK key, out InputMouseButton button)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case User32.VK.VK_LBUTTON:
|
||||
button = InputMouseButton.Left;
|
||||
return true;
|
||||
case User32.VK.VK_RBUTTON:
|
||||
button = InputMouseButton.Right;
|
||||
return true;
|
||||
case User32.VK.VK_MBUTTON:
|
||||
button = InputMouseButton.Middle;
|
||||
return true;
|
||||
case User32.VK.VK_XBUTTON1:
|
||||
button = InputMouseButton.X1;
|
||||
return true;
|
||||
case User32.VK.VK_XBUTTON2:
|
||||
button = InputMouseButton.X2;
|
||||
return true;
|
||||
default:
|
||||
button = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected static User32.VK ToVirtualKey(InputMouseButton button) => button switch
|
||||
{
|
||||
InputMouseButton.Left => User32.VK.VK_LBUTTON,
|
||||
InputMouseButton.Right => User32.VK.VK_RBUTTON,
|
||||
InputMouseButton.Middle => User32.VK.VK_MBUTTON,
|
||||
InputMouseButton.X1 => User32.VK.VK_XBUTTON1,
|
||||
InputMouseButton.X2 => User32.VK.VK_XBUTTON2,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(button), button, null),
|
||||
};
|
||||
|
||||
private bool TryGetXButton(int buttonId, out InputMouseButton button)
|
||||
{
|
||||
switch (buttonId)
|
||||
{
|
||||
case 1:
|
||||
button = InputMouseButton.X1;
|
||||
return true;
|
||||
case 2:
|
||||
button = InputMouseButton.X2;
|
||||
return true;
|
||||
default:
|
||||
button = default;
|
||||
WarnUnsupported($"侧键编号 {buttonId}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonDown(InputMouseButton button)
|
||||
{
|
||||
OnMouseButton(button, true);
|
||||
SetPressed(ToVirtualKey(button), true);
|
||||
return this;
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonUp(InputMouseButton button)
|
||||
{
|
||||
SetPressed(ToVirtualKey(button), false);
|
||||
OnMouseButton(button, false);
|
||||
return this;
|
||||
}
|
||||
|
||||
private InputChannelBase ButtonClick(InputMouseButton button)
|
||||
{
|
||||
SetPressed(ToVirtualKey(button), false);
|
||||
OnMouseClick(button);
|
||||
return this;
|
||||
}
|
||||
|
||||
private void SetPressed(User32.VK key, bool pressed)
|
||||
{
|
||||
lock (_pressedLock)
|
||||
{
|
||||
if (pressed)
|
||||
{
|
||||
_pressed.Add(key);
|
||||
}
|
||||
else
|
||||
{
|
||||
_pressed.Remove(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 可整体切换的输入后端
|
||||
/// </summary>
|
||||
public enum InputBackendKind
|
||||
{
|
||||
/// <summary>
|
||||
/// Windows 键鼠:前台 SendInput + 后台 PostMessage
|
||||
/// </summary>
|
||||
Win32,
|
||||
|
||||
/// <summary>
|
||||
/// 云原神网页版 JS SDK
|
||||
/// </summary>
|
||||
WebSdk,
|
||||
|
||||
/// <summary>
|
||||
/// 手柄(预留)
|
||||
/// </summary>
|
||||
Gamepad,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 输入层内部使用的鼠标按键。
|
||||
/// 不复用 WPF 的 System.Windows.Input.MouseButton 与 Fischless 的 MouseButton,避免重名
|
||||
/// </summary>
|
||||
public enum InputMouseButton
|
||||
{
|
||||
Left,
|
||||
Right,
|
||||
Middle,
|
||||
X1,
|
||||
X2,
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using BetterGenshinImpact.Core.Input.Backends.Win32;
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Input;
|
||||
|
||||
/// <summary>
|
||||
/// 模拟输入的统一入口。
|
||||
/// 业务代码只通过这里取通道,不直接使用 Simulation / PostMessageSimulator 等原始实现。
|
||||
/// <para>
|
||||
/// 通道引用只能在单个任务内持有;跨任务存活的对象(静态字段、DI 单例、Trigger 等)必须每次从这里取,
|
||||
/// 否则后端切换后引用会过期。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static class InputHub
|
||||
{
|
||||
private static readonly object AttachLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 未 Attach 时:未绑定窗口的 Win32 后端,前台可用,后台 warn
|
||||
/// </summary>
|
||||
private static IInputBackend _backend = new Win32InputBackend(IntPtr.Zero);
|
||||
|
||||
public static IInputBackend Backend => Volatile.Read(ref _backend);
|
||||
|
||||
public static IInputChannel Foreground => Backend.Foreground;
|
||||
|
||||
/// <summary>
|
||||
/// 后台通道。WebSdk / Gamepad 后端下与 <see cref="Foreground"/> 相同
|
||||
/// </summary>
|
||||
public static IInputChannel Background => Backend.Background;
|
||||
|
||||
/// <summary>
|
||||
/// 替换当前后端并释放旧后端。按键释放由停止流程显式处理,避免绑定新后端时释放全局按键。
|
||||
/// 只在没有任务运行时调用。
|
||||
/// (a,b)、c、d 之间的切换都通过它完成
|
||||
/// </summary>
|
||||
public static void Attach(IInputBackend backend)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(backend);
|
||||
lock (AttachLock)
|
||||
{
|
||||
var old = Backend;
|
||||
if (ReferenceEquals(old, backend))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _backend, backend);
|
||||
old.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放当前后端所有通道中处于按下状态的按键
|
||||
/// </summary>
|
||||
public static void ReleaseAll() => Backend.ReleaseAll();
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制入口(业务侧)。
|
||||
/// 线程安全,所有方法只写数据并立即返回,不等待 UI;何时重绘由遮罩窗口自行决定。
|
||||
/// </summary>
|
||||
public interface IMaskWindowDrawingBoard
|
||||
{
|
||||
/// <summary>
|
||||
/// 整组替换。shapes 为 null 或空时等价于 <see cref="Clear"/>;内容与当前相同则不做任何事
|
||||
/// </summary>
|
||||
void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes);
|
||||
|
||||
void Clear(MaskWindowDrawingGroup group);
|
||||
|
||||
void ClearAll();
|
||||
}
|
||||
|
||||
public static class MaskWindowDrawingBoardExtensions
|
||||
{
|
||||
public static void Set(this IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group, MaskWindowDrawingShape shape)
|
||||
{
|
||||
board.Set(group, new[] { shape });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回一个作用域,Dispose 时清除该分组。用于"任务期间显示、结束即清"
|
||||
/// </summary>
|
||||
public static IDisposable Scope(this IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group)
|
||||
{
|
||||
return new MaskWindowDrawingScope(board, group);
|
||||
}
|
||||
|
||||
private sealed class MaskWindowDrawingScope(IMaskWindowDrawingBoard board, MaskWindowDrawingGroup group) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
{
|
||||
board.Clear(group);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Windows;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口宿主:唯一负责遮罩窗口的创建、显隐、置顶和跟随游戏窗口。
|
||||
/// View 层以外的代码只能通过它接触遮罩窗口。
|
||||
/// </summary>
|
||||
public interface IMaskWindowHost
|
||||
{
|
||||
/// <summary>
|
||||
/// UI 线程调用。首次调用时创建窗口,绑定游戏窗口并显示
|
||||
/// </summary>
|
||||
void Attach(nint gameHandle);
|
||||
|
||||
/// <summary>
|
||||
/// UI 线程调用。隐藏窗口并解除绑定,窗口实例保留复用
|
||||
/// </summary>
|
||||
void Detach();
|
||||
|
||||
/// <summary>
|
||||
/// UI 线程调用。关闭并释放窗口(程序退出时)
|
||||
/// </summary>
|
||||
void Close();
|
||||
|
||||
/// <summary>
|
||||
/// 任意线程调用,每帧可调,立即返回。宿主去重后决定显隐、置顶、跟随
|
||||
/// </summary>
|
||||
void ReportGameWindow(GameWindowState state);
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次应用到窗口上的状态,任意线程可读
|
||||
/// </summary>
|
||||
MaskWindowState State { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 可见性或位置变化后在 UI 线程触发,附属遮罩(HtmlMask 等)订阅
|
||||
/// </summary>
|
||||
event EventHandler<MaskWindowState>? StateChanged;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 游戏窗口的状态。描述的是游戏窗口,不是遮罩窗口,所以不加 MaskWindow 前缀
|
||||
/// </summary>
|
||||
/// <param name="IsCapturing">截图器是否在运行</param>
|
||||
/// <param name="IsActive">游戏窗口是否在前台</param>
|
||||
/// <param name="IsMinimized">游戏窗口是否最小化</param>
|
||||
/// <param name="IsForegroundOwnedByBetterGiOrGame">前台窗口属于 BetterGI 自身或游戏进程(或者没有前台窗口)。按进程 ID 判断</param>
|
||||
/// <param name="Bounds">游戏捕获区域(屏幕物理像素),为空表示本次不更新位置</param>
|
||||
public readonly record struct GameWindowState(
|
||||
bool IsCapturing,
|
||||
bool IsActive,
|
||||
bool IsMinimized,
|
||||
bool IsForegroundOwnedByBetterGiOrGame,
|
||||
RECT Bounds);
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口的状态
|
||||
/// </summary>
|
||||
/// <param name="IsVisible">是否可见</param>
|
||||
/// <param name="Bounds">窗口位置(DIP)</param>
|
||||
public readonly record struct MaskWindowState(bool IsVisible, Rect Bounds);
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口地图点位区域的状态入口(业务侧)。线程安全,立即返回
|
||||
/// </summary>
|
||||
public interface IMaskWindowMapState
|
||||
{
|
||||
/// <summary>
|
||||
/// 字段为 null 表示不修改;多次调用合并为一个快照
|
||||
/// </summary>
|
||||
void Update(bool? isInBigMap = null, Rect? bigMapViewport = null, Rect? miniMapViewport = null);
|
||||
|
||||
/// <summary>
|
||||
/// 退出大地图并清空两个视口。在任务开始、地图遮罩关闭时调用
|
||||
/// </summary>
|
||||
void Reset();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 地图点位区域的不可变快照
|
||||
/// </summary>
|
||||
/// <param name="IsInBigMap">是否在大地图界面</param>
|
||||
/// <param name="BigMapViewport">大地图视口(2048 级地图坐标),空矩形表示不显示</param>
|
||||
/// <param name="MiniMapViewport">小地图视口,空矩形表示不显示</param>
|
||||
public sealed record MaskWindowMapSnapshot(bool IsInBigMap, Rect BigMapViewport, Rect MiniMapViewport)
|
||||
{
|
||||
public static MaskWindowMapSnapshot Empty { get; } = new(false, default, default);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口渲染侧的读取接口,仅 MaskWindowViewModel 使用
|
||||
/// </summary>
|
||||
public interface IMaskWindowSnapshotSource<out T>
|
||||
{
|
||||
/// <summary>
|
||||
/// 不可变快照,UI 线程直接读取,无需加锁
|
||||
/// </summary>
|
||||
T Current { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 可在任意线程触发,只表示"有新版本",由订阅方自行合并。回调里只能做 O(1) 的操作
|
||||
/// </summary>
|
||||
event Action? Changed;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制内容的存储。
|
||||
/// 业务线程写入不可变快照,UI 侧订阅 <see cref="Changed"/> 后合并拉取。
|
||||
/// </summary>
|
||||
public sealed class MaskWindowDrawingBoard : IMaskWindowDrawingBoard, IMaskWindowSnapshotSource<MaskWindowDrawingSnapshot>
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
|
||||
private ImmutableDictionary<string, MaskWindowDrawingEntry> _entries =
|
||||
ImmutableDictionary.Create<string, MaskWindowDrawingEntry>(StringComparer.Ordinal);
|
||||
|
||||
private MaskWindowDrawingSnapshot _current = MaskWindowDrawingSnapshot.Empty;
|
||||
|
||||
public MaskWindowDrawingSnapshot Current => Volatile.Read(ref _current);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes)
|
||||
{
|
||||
if (shapes == null || shapes.Count == 0)
|
||||
{
|
||||
Clear(group);
|
||||
return;
|
||||
}
|
||||
|
||||
// 拷贝一份,调用方之后再修改原列表也不会影响已存的内容
|
||||
var copy = shapes.ToArray();
|
||||
lock (_lock)
|
||||
{
|
||||
if (_entries.TryGetValue(group.Name, out var existing)
|
||||
&& existing.Group == group
|
||||
&& existing.Shapes.SequenceEqual(copy))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.SetItem(group.Name, new MaskWindowDrawingEntry(group, copy));
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Clear(MaskWindowDrawingGroup group)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_entries.ContainsKey(group.Name))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.Remove(group.Name);
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_entries.IsEmpty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_entries = _entries.Clear();
|
||||
PublishLocked();
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private void PublishLocked()
|
||||
{
|
||||
var entries = _entries.IsEmpty ? Array.Empty<MaskWindowDrawingEntry>() : _entries.Values.ToArray();
|
||||
Volatile.Write(ref _current, new MaskWindowDrawingSnapshot(_current.Version + 1, entries));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
public static class MaskWindowDrawingConversions
|
||||
{
|
||||
/// <summary>
|
||||
/// 捕获像素坐标系下的 OpenCV 矩形转换为遮罩窗口绘制矩形。
|
||||
/// 只能用于坐标已经是整个游戏捕获区域的矩形;子区域内的坐标请用 Region.ToMaskWindowDrawingRect
|
||||
/// </summary>
|
||||
public static MaskWindowDrawingRect ToMaskWindowDrawingRect(this OpenCvSharp.Rect rect, System.Drawing.Pen? pen = null)
|
||||
{
|
||||
return new MaskWindowDrawingRect(
|
||||
new System.Windows.Rect(rect.X, rect.Y, rect.Width, rect.Height),
|
||||
MaskWindowDrawingStroke.FromPen(pen));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 绘制分组的类型,决定分组在遮罩窗口上的显示规则
|
||||
/// </summary>
|
||||
public enum MaskWindowDrawingKind
|
||||
{
|
||||
/// <summary>
|
||||
/// 识别结果(调试可视化):受「在遮罩上显示识别结果」开关和统一样式控制
|
||||
/// </summary>
|
||||
Recognition,
|
||||
|
||||
/// <summary>
|
||||
/// 功能提示(技能 CD、地脉 OCR 区域等):遮罩可见就显示,使用图形自带样式
|
||||
/// </summary>
|
||||
Feature,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 绘制分组。一组图形按 Name 整体替换,Kind 决定显示规则
|
||||
/// </summary>
|
||||
public readonly record struct MaskWindowDrawingGroup(string Name, MaskWindowDrawingKind Kind = MaskWindowDrawingKind.Recognition)
|
||||
{
|
||||
public static implicit operator MaskWindowDrawingGroup(string name) => new(name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口上的图形。坐标统一使用游戏捕获区域的物理像素(与截图 Mat 相同)
|
||||
/// </summary>
|
||||
public abstract record MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingRect(Rect Bounds, MaskWindowDrawingStroke? Stroke = null) : MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingLine(Point From, Point To, MaskWindowDrawingStroke? Stroke = null) : MaskWindowDrawingShape;
|
||||
|
||||
public sealed record MaskWindowDrawingText(string Text, Point Origin, MaskWindowDrawingTextStyle? Style = null) : MaskWindowDrawingShape;
|
||||
|
||||
/// <summary>
|
||||
/// 线条样式。Thickness 为 DIP
|
||||
/// </summary>
|
||||
public readonly record struct MaskWindowDrawingStroke(Color Color, double Thickness = 2)
|
||||
{
|
||||
/// <summary>
|
||||
/// 兼容业务代码里现有的 System.Drawing.Pen(如 Pens.Lime、识别对象的 DrawOnWindowPen)
|
||||
/// </summary>
|
||||
public static MaskWindowDrawingStroke? FromPen(System.Drawing.Pen? pen)
|
||||
{
|
||||
if (pen == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var c = pen.Color;
|
||||
return new MaskWindowDrawingStroke(Color.FromArgb(c.A, c.R, c.G, c.B), pen.Width);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字样式。为 null 的字段使用 MaskWindowConfig 中的识别结果样式
|
||||
/// </summary>
|
||||
/// <param name="Foreground">文字颜色</param>
|
||||
/// <param name="FontSize">字号,单位为捕获像素</param>
|
||||
/// <param name="Background">不为空时在文字下方绘制圆角底色</param>
|
||||
/// <param name="Numeric">是否使用数字字体(Fgi)</param>
|
||||
public sealed record MaskWindowDrawingTextStyle(
|
||||
Color? Foreground = null,
|
||||
double? FontSize = null,
|
||||
Color? Background = null,
|
||||
bool Numeric = false);
|
||||
|
||||
/// <summary>
|
||||
/// 绘制快照中的一个分组
|
||||
/// </summary>
|
||||
public sealed record MaskWindowDrawingEntry(MaskWindowDrawingGroup Group, IReadOnlyList<MaskWindowDrawingShape> Shapes);
|
||||
|
||||
/// <summary>
|
||||
/// 绘制内容的不可变快照,UI 线程直接读取
|
||||
/// </summary>
|
||||
public sealed record MaskWindowDrawingSnapshot(long Version, IReadOnlyList<MaskWindowDrawingEntry> Entries)
|
||||
{
|
||||
public static MaskWindowDrawingSnapshot Empty { get; } = new(0, Array.Empty<MaskWindowDrawingEntry>());
|
||||
|
||||
public bool IsEmpty => Entries.Count == 0;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口绘制层的全局样式,由 MaskWindowViewModel 从 MaskWindowConfig 的 Recognition* 配置合成
|
||||
/// </summary>
|
||||
/// <param name="OverrideRecognitionStroke">为 true 时 Recognition 分组忽略图形自带的线条样式,统一使用下面的线条样式</param>
|
||||
/// <param name="RectStroke">识别框的统一线条样式</param>
|
||||
/// <param name="LineStroke">识别线的统一线条样式</param>
|
||||
/// <param name="TextColor">文字未指定颜色时使用的颜色</param>
|
||||
/// <param name="TextFontSize">文字未指定字号时使用的字号,单位为捕获像素</param>
|
||||
public sealed record MaskWindowDrawingStyle(
|
||||
bool OverrideRecognitionStroke,
|
||||
MaskWindowDrawingStroke RectStroke,
|
||||
MaskWindowDrawingStroke LineStroke,
|
||||
Color TextColor,
|
||||
double TextFontSize)
|
||||
{
|
||||
public static MaskWindowDrawingStroke DefaultStroke { get; } = new(Colors.Red, 2);
|
||||
|
||||
public static MaskWindowDrawingStyle Default { get; } =
|
||||
new(false, DefaultStroke, DefaultStroke, Colors.Black, 36);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 地图点位区域状态的存储。写入时按字段合并,内容不变则不通知
|
||||
/// </summary>
|
||||
public sealed class MaskWindowMapState : IMaskWindowMapState, IMaskWindowSnapshotSource<MaskWindowMapSnapshot>
|
||||
{
|
||||
private readonly object _lock = new();
|
||||
private MaskWindowMapSnapshot _current = MaskWindowMapSnapshot.Empty;
|
||||
|
||||
public MaskWindowMapSnapshot Current => Volatile.Read(ref _current);
|
||||
|
||||
public event Action? Changed;
|
||||
|
||||
public void Update(bool? isInBigMap = null, Rect? bigMapViewport = null, Rect? miniMapViewport = null)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var next = new MaskWindowMapSnapshot(
|
||||
isInBigMap ?? _current.IsInBigMap,
|
||||
bigMapViewport ?? _current.BigMapViewport,
|
||||
miniMapViewport ?? _current.MiniMapViewport);
|
||||
if (next == _current)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _current, next);
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_current == MaskWindowMapSnapshot.Empty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Volatile.Write(ref _current, MaskWindowMapSnapshot.Empty);
|
||||
}
|
||||
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Mask;
|
||||
|
||||
/// <summary>
|
||||
/// 空实现,用于单测以及不挂在截图区域下的 Region
|
||||
/// </summary>
|
||||
public sealed class NullMaskWindowDrawingBoard : IMaskWindowDrawingBoard
|
||||
{
|
||||
public static NullMaskWindowDrawingBoard Instance { get; } = new();
|
||||
|
||||
private NullMaskWindowDrawingBoard()
|
||||
{
|
||||
}
|
||||
|
||||
public void Set(MaskWindowDrawingGroup group, IReadOnlyList<MaskWindowDrawingShape>? shapes)
|
||||
{
|
||||
}
|
||||
|
||||
public void Clear(MaskWindowDrawingGroup group)
|
||||
{
|
||||
}
|
||||
|
||||
public void ClearAll()
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Gma.System.MouseKeyHook;
|
||||
@@ -66,8 +66,6 @@ public partial class MouseKeyMonitor : IDisposable
|
||||
return _globalHook;
|
||||
}
|
||||
}
|
||||
private nint _hWnd;
|
||||
|
||||
public MouseKeyMonitor()
|
||||
{
|
||||
_spaceTimer.Elapsed += OnSpaceTimerElapsed;
|
||||
@@ -77,7 +75,7 @@ public partial class MouseKeyMonitor : IDisposable
|
||||
public void Subscribe(nint gameHandle)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
_hWnd = gameHandle;
|
||||
// 按键经 InputHub.Background 发往 TaskContext.Init 绑定的游戏窗口,gameHandle 与其相同
|
||||
|
||||
_pickUpKey = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToWinFormKeys();
|
||||
_pickUpKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToVK();
|
||||
@@ -120,12 +118,12 @@ public partial class MouseKeyMonitor : IDisposable
|
||||
|
||||
private void OnSpaceTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
Simulation.PostMessage(_hWnd).KeyPress(_releaseControlKeyCode);
|
||||
InputHub.Background.Keyboard.KeyPress(_releaseControlKeyCode);
|
||||
}
|
||||
|
||||
private void OnFTimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
Simulation.PostMessage(_hWnd).KeyPress(_pickUpKeyCode);
|
||||
InputHub.Background.Keyboard.KeyPress(_pickUpKeyCode);
|
||||
}
|
||||
|
||||
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
|
||||
|
||||
@@ -16,7 +16,24 @@ public class OcrFactory : IDisposable
|
||||
|
||||
|
||||
public static IOcrService Paddle => App.ServiceProvider.GetRequiredService<OcrFactory>().PaddleOcr;
|
||||
private IOcrService PaddleOcr => _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
|
||||
public IOcrService PaddleOcr
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_serviceLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
return _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
|
||||
}
|
||||
}
|
||||
}
|
||||
private readonly object _serviceLock = new();
|
||||
private bool _disposed;
|
||||
private PaddleOcrService.PaddleOcrModelType? _activeModelType;
|
||||
public PaddleOcrService.PaddleOcrModelType ActiveModelType
|
||||
{
|
||||
get { lock (_serviceLock) return _activeModelType ?? ResolveModelType(); }
|
||||
}
|
||||
|
||||
private IOcrService? _paddleOcrService;
|
||||
private readonly ILogger<BgiOnnxFactory> _logger;
|
||||
@@ -86,38 +103,35 @@ public class OcrFactory : IDisposable
|
||||
}
|
||||
|
||||
private PaddleOcrService CreatePaddleOcrInstance()
|
||||
{
|
||||
_activeModelType = ResolveModelType();
|
||||
return new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(), _activeModelType);
|
||||
}
|
||||
|
||||
private PaddleOcrService.PaddleOcrModelType ResolveModelType()
|
||||
{
|
||||
return _config.PaddleOcrModelConfig switch
|
||||
{
|
||||
PaddleOcrModelConfig.V4Auto =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V4),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V4,
|
||||
PaddleOcrModelConfig.V5Auto =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V5),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V5,
|
||||
PaddleOcrModelConfig.V5 =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5),
|
||||
PaddleOcrService.PaddleOcrModelType.V5,
|
||||
PaddleOcrModelConfig.V6 =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V6),
|
||||
PaddleOcrService.PaddleOcrModelType.V6,
|
||||
PaddleOcrModelConfig.V4 =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V4),
|
||||
PaddleOcrService.PaddleOcrModelType.V4,
|
||||
PaddleOcrModelConfig.V4En =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V4En),
|
||||
PaddleOcrService.PaddleOcrModelType.V4En,
|
||||
PaddleOcrModelConfig.V5Korean =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Korean),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Korean,
|
||||
PaddleOcrModelConfig.V5Latin =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Latin),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Latin,
|
||||
PaddleOcrModelConfig.V5Eslav =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Eslav),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Eslav,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(_config.PaddleOcrModelConfig),
|
||||
_config.PaddleOcrModelConfig, "不支持的 Paddle OCR 模型配置")
|
||||
};
|
||||
@@ -125,27 +139,23 @@ public class OcrFactory : IDisposable
|
||||
|
||||
public Task Unload()
|
||||
{
|
||||
if (_paddleOcrService is not IDisposable disposable)
|
||||
lock (_serviceLock)
|
||||
{
|
||||
if (_paddleOcrService is IDisposable disposable) disposable.Dispose();
|
||||
_paddleOcrService = null;
|
||||
return Task.CompletedTask;
|
||||
_activeModelType = null;
|
||||
}
|
||||
try
|
||||
{
|
||||
disposable.Dispose();
|
||||
_paddleOcrService = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "卸载 OCR 服务时发生错误");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Unload().GetAwaiter().GetResult();
|
||||
lock (_serviceLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
Unload().GetAwaiter().GetResult();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
@@ -37,17 +33,6 @@ public static class OcrResultExtension
|
||||
return default;
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableList(this OcrResult result, Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(pen)).ToList();
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this OcrResult result, int offsetX, int offsetY,
|
||||
Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(offsetX, offsetY, pen)).ToList();
|
||||
}
|
||||
|
||||
public static PaddleOcrResultRect ToOcrResultRect(this OcrResultRegion region)
|
||||
{
|
||||
return new PaddleOcrResultRect(region.Rect.BoundingRect(), region.Text, region.Score);
|
||||
|
||||
@@ -8,10 +8,12 @@ using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgiOnnxFactory)
|
||||
public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxSessionFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly object _sessionLock = new();
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Gets or sets the detection side length limit used by the Python det preprocess.</summary>
|
||||
public int LimitSideLen { get; set; } = 960;
|
||||
@@ -40,21 +42,14 @@ 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; } = 1.5f;
|
||||
|
||||
~Det()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public RotatedRect[] Run(Mat src)
|
||||
@@ -98,8 +93,9 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
|
||||
config.NormalizeImage.Mean, config.NormalizeImage.Std, out var owner);
|
||||
using (owner)
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
|
||||
@@ -27,6 +27,8 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
private readonly Det _localDetModel;
|
||||
|
||||
private readonly Rec _localRecModel;
|
||||
private readonly object _inferenceLock = new();
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Gets or sets the official recognition score threshold used to discard low-confidence results.</summary>
|
||||
public float DropScore { get; set; } = 0.5f;
|
||||
@@ -107,11 +109,11 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
preHeatImagePath ?? TestImagePath);
|
||||
}
|
||||
|
||||
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
|
||||
public (Det, Rec) Build(BgiOnnxSessionFactory onnxFactory)
|
||||
{
|
||||
return (
|
||||
new Det(DetectionModel, DetectionVersion, onnxFactory),
|
||||
new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory));
|
||||
var detection = new Det(DetectionModel, DetectionVersion, onnxFactory);
|
||||
try { return (detection, new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory)); }
|
||||
catch { detection.Dispose(); throw; }
|
||||
}
|
||||
|
||||
public static readonly PaddleOcrModelType V4 = Create(
|
||||
@@ -250,18 +252,32 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
}
|
||||
|
||||
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType)
|
||||
: this(bgiOnnxFactory.ForCurrentRuntime(), modelType)
|
||||
{
|
||||
}
|
||||
|
||||
internal PaddleOcrService(BgiOnnxSessionFactory bgiOnnxFactory, PaddleOcrModelType modelType)
|
||||
{
|
||||
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory);
|
||||
_localDetModel = modelsDet;
|
||||
_localRecModel = modelsRec;
|
||||
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
Debug.WriteLine(
|
||||
$"PaddleOcrService 预热完成,使用模型: {modelType.DetectionModel.Name} 和 {modelType.RecognitionModel.Name},结果: {preHeatResult.Text}");
|
||||
try
|
||||
{
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
Debug.WriteLine(
|
||||
$"PaddleOcrService 预热完成,使用模型: {modelType.DetectionModel.Name} 和 {modelType.RecognitionModel.Name},结果: {preHeatResult.Text}");
|
||||
}
|
||||
catch
|
||||
{
|
||||
_localDetModel.Dispose();
|
||||
_localRecModel.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -277,13 +293,17 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
/// </summary>
|
||||
public OcrResult OcrResult(Mat mat)
|
||||
{
|
||||
if (mat.Channels() == 4)
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
|
||||
return _OcrResult(mat3);
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (mat.Channels() == 4)
|
||||
{
|
||||
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
|
||||
return _OcrResult(mat3);
|
||||
}
|
||||
|
||||
return _OcrResult(mat);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -291,11 +311,15 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
/// </summary>
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
}
|
||||
|
||||
private OcrResult _OcrResult(Mat mat)
|
||||
@@ -415,8 +439,13 @@ public class PaddleOcrService : IOcrService, IDisposable
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_localDetModel.Dispose();
|
||||
_localRecModel.Dispose();
|
||||
lock (_inferenceLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
try { _localDetModel.Dispose(); }
|
||||
finally { _localRecModel.Dispose(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -16,27 +16,21 @@ public class Rec(
|
||||
BgiOnnxModel model,
|
||||
IReadOnlyList<string> labels,
|
||||
OcrVersionConfig config,
|
||||
BgiOnnxFactory bgiOnnxFactory)
|
||||
BgiOnnxSessionFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly object _sessionLock = new();
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
private bool _disposed;
|
||||
|
||||
// _labels = File.ReadAllLines(labelFilePath);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
|
||||
~Rec()
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -124,8 +118,9 @@ public class Rec(
|
||||
})
|
||||
.Select(inputTensor =>
|
||||
{
|
||||
lock (_session)
|
||||
lock (_sessionLock)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
// 多线程推理会出现问题,加锁解决。
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
|
||||
@@ -4,93 +4,72 @@ using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.Win32;
|
||||
using Vanara;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public class BgiOnnxFactory
|
||||
/// <summary>从当前已解析运行时创建会话。每次调用只读取一次 Current,已有会话不会受后续回退影响。</summary>
|
||||
public sealed class BgiOnnxFactory(ILogger<BgiOnnxFactory> logger, InferenceRuntimeService runtime)
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
internal BgiOnnxSessionFactory ForCurrentRuntime() => new(logger, runtime.Current);
|
||||
|
||||
internal BgiOnnxSessionFactory ForRuntime(ResolvedInferenceRuntime resolvedRuntime) => new(logger, resolvedRuntime);
|
||||
|
||||
public BgiYoloPredictor CreateYoloPredictor(BgiOnnxModel model)
|
||||
=> ForCurrentRuntime().CreateYoloPredictor(model);
|
||||
|
||||
public InferenceSession CreateInferenceSession(BgiOnnxModel model, bool ocr = false)
|
||||
=> ForCurrentRuntime().CreateInferenceSession(model, ocr);
|
||||
|
||||
/// <summary>为明确不参与硬件加速选择的模型创建纯 CPU 会话。</summary>
|
||||
public static InferenceSession CreateCpuOnlyInferenceSession(BgiOnnxModel model,
|
||||
Action<SessionOptions>? configure = null)
|
||||
{
|
||||
using var options = new SessionOptions();
|
||||
configure?.Invoke(options);
|
||||
options.AppendExecutionProvider_CPU();
|
||||
return new InferenceSession(model.ModalPath, options);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>绑定单个已解析运行时的会话工厂。</summary>
|
||||
public sealed class BgiOnnxSessionFactory
|
||||
{
|
||||
private readonly ILogger<BgiOnnxFactory> _logger;
|
||||
private readonly ProviderType[] _providerTypes;
|
||||
private readonly ResolvedInferenceRuntime _runtime;
|
||||
|
||||
/// <summary>
|
||||
/// 缓存模型路径。如果一开始使用缓存就一直使用缓存文件,如果没有使用缓存就一直使用原始模型路径。
|
||||
/// 缓存模型路径对应的目录;会话始终加载原始模型,不再使用嵌入缓存文件。
|
||||
/// <br />
|
||||
/// 这样能避免并发加载模型问题。比如使用了未完全构建好的缓存文件,导致模型加载失败。
|
||||
/// 这样能避免并发加载模型问题。普通缓存目录按模型内容、设备与设置隔离。
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<BgiOnnxModel, string?> _cachedModelPaths = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 请勿直接实例化此类
|
||||
/// </summary>
|
||||
/// <param name="logger"></param>
|
||||
public BgiOnnxFactory(ILogger<BgiOnnxFactory> logger)
|
||||
internal BgiOnnxSessionFactory(ILogger<BgiOnnxFactory> logger, ResolvedInferenceRuntime runtime)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
var config = GetConfig();
|
||||
if (config.AutoAppendCudaPath) AppendCudaPath();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(config.AdditionalPath))
|
||||
AppendPath(config.AdditionalPath.Split(Path.PathSeparator));
|
||||
|
||||
|
||||
OptimizedModel = config.OptimizedModel;
|
||||
CudaDeviceId = config.CudaDevice;
|
||||
DmlDeviceId = config.GpuDevice;
|
||||
TrtUseEmbedMode = config.EmbedTensorRtCache;
|
||||
EnableCache = config.EnableTensorRtCache;
|
||||
CpuOcr = config.CpuOcr;
|
||||
OpenVinoDevice = config.OpenVinoDevice;
|
||||
OpenVinoCache = config.EnableOpenVinoCache;
|
||||
ProviderTypes = GetProviderType(config.InferenceDevice);
|
||||
_logger.LogDebug(
|
||||
"[ONNX]启用的provider:{Device},初始化参数: InferenceDevice={InferenceDevice}, OptimizedModel={OptimizedModel}, CudaDeviceId={CudaDeviceId}, DmlDeviceId={DmlDeviceId}, EmbedTensorRtCache={EmbedTensorRtCache}, EnableTensorRtCache={EnableTensorRtCache}, CpuOcr={CpuOcr}",
|
||||
string.Join(",", ProviderTypes.Select<ProviderType, string>(Enum.GetName!)),
|
||||
config.InferenceDevice,
|
||||
OptimizedModel,
|
||||
CudaDeviceId,
|
||||
DmlDeviceId,
|
||||
TrtUseEmbedMode,
|
||||
EnableCache,
|
||||
CpuOcr);
|
||||
_runtime = runtime;
|
||||
_providerTypes = GetProviderType(runtime.Engine);
|
||||
_logger.LogInformation("[ONNX]当前引擎 {Engine},设备 {Device},OCR 强制 CPU:{CpuOcr}",
|
||||
runtime.Engine, runtime.Device.Name, runtime.CpuOcr);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 硬件加速配置
|
||||
/// 为了单元测试
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private HardwareAccelerationConfig GetConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 直接使用配置
|
||||
return TaskContext.Instance().Config.HardwareAccelerationConfig;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 如果配置获取失败,使用默认配置
|
||||
_logger.LogWarning(e, "获取硬件加速配置失败,使用默认配置");
|
||||
return new HardwareAccelerationConfig();
|
||||
}
|
||||
}
|
||||
public ResolvedInferenceRuntime Runtime => _runtime;
|
||||
|
||||
public ProviderType[] ProviderTypes { get; }
|
||||
public int DmlDeviceId { get; }
|
||||
public int CudaDeviceId { get; }
|
||||
public bool OptimizedModel { get; }
|
||||
public bool TrtUseEmbedMode { get; }
|
||||
public string OpenVinoDevice { get; }
|
||||
public bool EnableCache { get; }
|
||||
public bool CpuOcr { get; }
|
||||
public bool OpenVinoCache { get; }
|
||||
// OCR 验证使用独立会话,必须实际加载所选 provider;不改变业务 OCR 的 CPU 设置。
|
||||
internal BgiOnnxSessionFactory ForOcrValidation()
|
||||
=> new(_logger, Runtime with { CpuOcr = false });
|
||||
|
||||
public ProviderType[] ProviderTypes => (ProviderType[])_providerTypes.Clone();
|
||||
public int DmlDeviceId => Runtime.Device.Index;
|
||||
public int CudaDeviceId => Runtime.Device.Index;
|
||||
public string OpenVinoDevice => Runtime.Device.ProviderDevice;
|
||||
public bool EnableCache => Runtime.EnableModelCache;
|
||||
public bool CpuOcr => Runtime.CpuOcr;
|
||||
public bool OpenVinoCache => Runtime.EnableModelCache;
|
||||
|
||||
|
||||
/// <summary>
|
||||
@@ -98,203 +77,36 @@ public class BgiOnnxFactory
|
||||
/// </summary>
|
||||
/// <param name="inferenceDeviceType">InferenceDeviceType</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="InvalidEnumArgumentException"></exception>
|
||||
/// <remarks>历史上的自动 GPU 选项已移除,无法识别的设置回退到 CPU。</remarks>
|
||||
private ProviderType[] GetProviderType(InferenceDeviceType inferenceDeviceType)
|
||||
{
|
||||
// 无论如何都要加入 CPU,一些计算在纯 GPU 上不被支持或性能很差。
|
||||
switch (inferenceDeviceType)
|
||||
{
|
||||
case InferenceDeviceType.Cpu:
|
||||
return [ProviderType.Cpu];
|
||||
case InferenceDeviceType.GpuDirectMl:
|
||||
case InferenceDeviceType.DirectML:
|
||||
//只用dml不加cpu的话在很多场景下性能很差。
|
||||
// DirectML 的性能和稳定性取决于模型与设备,现在由用户独立选择,不与 TensorRT、CUDA 自动比较。
|
||||
return [ProviderType.Dml, ProviderType.Cpu];
|
||||
case InferenceDeviceType.Gpu:
|
||||
{
|
||||
List<ProviderType> list = [];
|
||||
SessionOptions? testSession = null;
|
||||
var hasGpu = false;
|
||||
if (!hasGpu && CudaDeviceId >= 0)
|
||||
// tensorrt本身包含cuda,设备id也是cuda的id,且比纯cuda效果好很多。
|
||||
try
|
||||
{
|
||||
testSession = SessionOptions.MakeSessionOptionWithTensorrtProvider(CudaDeviceId);
|
||||
list.Add(ProviderType.TensorRt);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载TensorRt。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu && DmlDeviceId >= 0)
|
||||
// dml效果不如tensorrt,但是比纯cuda稳定性强
|
||||
try
|
||||
{
|
||||
testSession = new SessionOptions();
|
||||
testSession.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
list.Add(ProviderType.Dml);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载DML。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu && CudaDeviceId >= 0)
|
||||
// cuda优先级比较低,因为跑起来并不太理想。
|
||||
try
|
||||
{
|
||||
testSession = SessionOptions.MakeSessionOptionWithCudaProvider(CudaDeviceId);
|
||||
list.Add(ProviderType.Cuda);
|
||||
hasGpu = true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载Cuda。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
if (!hasGpu) _logger.LogWarning("[init]GPU自动选择失败,回退到CPU处理");
|
||||
|
||||
//无论如何都要加入cpu,一些计算在纯gpu上不被支持或性能很烂
|
||||
list.Add(ProviderType.Cpu);
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
case InferenceDeviceType.OpenVino:
|
||||
{
|
||||
List<ProviderType> list = [];
|
||||
SessionOptions? testSession = null;
|
||||
case InferenceDeviceType.OpenVINO:
|
||||
// OpenVino是英特尔的OpenVINO执行提供程序
|
||||
// 目前来看比Dml强
|
||||
try
|
||||
{
|
||||
testSession = new SessionOptions();
|
||||
testSession.AppendExecutionProvider("OpenVINO", GetOpenVinoProviderConfig(null));
|
||||
testSession.GraphOptimizationLevel = GraphOptimizationLevel.ORT_DISABLE_ALL;
|
||||
list.Add(ProviderType.OpenVino);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogDebug("[init]无法加载OpenVino。可能不支持,跳过。({Err})", e.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
testSession?.Dispose();
|
||||
}
|
||||
|
||||
list.Add(ProviderType.Cpu);
|
||||
return list.ToArray();
|
||||
}
|
||||
// provider 注册统一在 CreateSessionOptions 中完成,避免重复创建原生选项探测。
|
||||
return [ProviderType.OpenVino, ProviderType.Cpu];
|
||||
case InferenceDeviceType.CUDA:
|
||||
// CUDA 的效果依赖具体模型,不再受旧自动选择策略中的低优先级限制。
|
||||
return [ProviderType.Cuda, ProviderType.Cpu];
|
||||
case InferenceDeviceType.TensorRT:
|
||||
// TensorRT 使用配置的设备编号,性能收益需要按模型和设备判断。
|
||||
// TensorRT 独立注册,未接管的算子由 CPU 兜底。
|
||||
return [ProviderType.TensorRt, ProviderType.Cpu];
|
||||
default:
|
||||
throw new InvalidEnumArgumentException("无效的推理设备");
|
||||
_logger.LogWarning("[ONNX]无法识别推理设备设置 {Device},回退到 CPU", inferenceDeviceType);
|
||||
return [ProviderType.Cpu];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动嗅探并修改path以加载cuda
|
||||
/// </summary>
|
||||
private void AppendCudaPath()
|
||||
{
|
||||
var cudaVersion =
|
||||
Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\NVIDIA Corporation\GPU Computing Toolkit\CUDA",
|
||||
"FirstVersionInstalled", null)?.ToString() ?? "v12.8";
|
||||
string[] filePrefix = ["cudnn", "nvrtc", "cudart", "nvinfer", "cublas", "onnx"];
|
||||
string[] environmentVariableNames = ["PATH", "CUDA_PATH", "CUDNN_PATH", "LD_LIBRARY_PATH"];
|
||||
|
||||
// 例如: CUDNN\v9.8\lib\12.8\x64
|
||||
var validPaths = environmentVariableNames.SelectMany(s => Environment
|
||||
// 获取所有可能包含CUDA/cuDNN路径的环境变量
|
||||
.GetEnvironmentVariable(s, EnvironmentVariableTarget.Process)?
|
||||
.Split(Path.PathSeparator) ?? []).Distinct()
|
||||
// 环境变量下层文件夹
|
||||
.SelectMany<string, string>(s =>
|
||||
// lib路径
|
||||
[s, Path.Combine(s, cudaVersion), Path.Combine(s, "bin"), Path.Combine(s, "lib")])
|
||||
.SelectMany<string, string>(
|
||||
// cuda的版本
|
||||
s => cudaVersion.StartsWith("v", StringComparison.InvariantCultureIgnoreCase)
|
||||
? [s, Path.Combine(s, cudaVersion), Path.Combine(s, cudaVersion[1..])]
|
||||
: [s, Path.Combine(s, cudaVersion)])
|
||||
.SelectMany<string, string>(s =>
|
||||
{
|
||||
// 体系架构
|
||||
var architecture = Enum.GetName(RuntimeInformation.ProcessArchitecture);
|
||||
if (architecture is null) return [s];
|
||||
|
||||
return
|
||||
[
|
||||
s, Path.Combine(s, architecture), Path.Combine(s, architecture.ToLowerInvariant()),
|
||||
Path.Combine(s, architecture.ToUpperInvariant())
|
||||
];
|
||||
})
|
||||
.Where(basePath => !string.IsNullOrWhiteSpace(basePath))
|
||||
//构建完了需要搜索的路径,去重。
|
||||
.Distinct()
|
||||
|
||||
//确定路径是否真的存在
|
||||
.Where(d =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.Exists(d);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
})
|
||||
.SelectMany(s =>
|
||||
//确定需要的文件是否存在
|
||||
filePrefix.SelectMany(se =>
|
||||
{
|
||||
try
|
||||
{
|
||||
return Directory.GetFiles(s, $"{se}*.dll").Select(Path.GetDirectoryName).WhereNotNull();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}))
|
||||
//去重
|
||||
.Distinct();
|
||||
AppendPath(validPaths.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将附加的path应用进来
|
||||
/// </summary>
|
||||
/// <param name="extraPath">附加的path字符串</param>
|
||||
private void AppendPath(string[] extraPath)
|
||||
{
|
||||
if (extraPath.Length <= 0) return;
|
||||
|
||||
var pathVariables = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process)
|
||||
?.Split(Path.PathSeparator).ToList() ?? new List<string>();
|
||||
pathVariables.AddRange(extraPath);
|
||||
if (pathVariables.Count <= 0)
|
||||
{
|
||||
_logger.LogWarning("[GpuAuto]SetCudaPath:No valid paths found.");
|
||||
return;
|
||||
}
|
||||
|
||||
var updatedPath = string.Join(Path.PathSeparator, pathVariables.Distinct());
|
||||
_logger.LogDebug("[GpuAuto]修改进程PATH为:{UpdatedPath}", updatedPath);
|
||||
Environment.SetEnvironmentVariable("PATH", updatedPath, EnvironmentVariableTarget.Process);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据模型创建一个YoloPredictor
|
||||
/// </summary>
|
||||
@@ -302,13 +114,19 @@ public class BgiOnnxFactory
|
||||
/// <returns>BgiYoloPredictor</returns>
|
||||
public BgiYoloPredictor CreateYoloPredictor(BgiOnnxModel model)
|
||||
{
|
||||
// 延后验证只影响后续新建会话,不修改或释放已经运行中的会话。
|
||||
// logger.LogDebug("[Yolo]创建yolo预测器,模型: {ModelName}", model.Name);
|
||||
if (!EnableCache) return new BgiYoloPredictor(model, model.ModalPath, CreateSessionOptions(model, false));
|
||||
|
||||
var cached = GetCached(model);
|
||||
return cached == null
|
||||
? new BgiYoloPredictor(model, model.ModalPath, CreateSessionOptions(model, true))
|
||||
: new BgiYoloPredictor(model, cached, CreateSessionOptions(model, false));
|
||||
var options = CreateSessionOptions(model, EnableCache);
|
||||
try
|
||||
{
|
||||
// 延迟创建会话,配置的所有权转交给预测器。
|
||||
return new BgiYoloPredictor(model, model.ModalPath, options);
|
||||
}
|
||||
catch
|
||||
{
|
||||
options.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -323,69 +141,30 @@ public class BgiOnnxFactory
|
||||
ProviderType[]? providerTypes = null;
|
||||
if (CpuOcr && ocr) providerTypes = [ProviderType.Cpu];
|
||||
|
||||
if (!EnableCache)
|
||||
return new InferenceSession(model.ModalPath, CreateSessionOptions(model, false, providerTypes));
|
||||
|
||||
var cached = GetCached(model, providerTypes);
|
||||
return cached == null
|
||||
? new InferenceSession(model.ModalPath, CreateSessionOptions(model, true, providerTypes))
|
||||
: new InferenceSession(cached, CreateSessionOptions(model, false, providerTypes));
|
||||
using var options = CreateSessionOptions(model, EnableCache, providerTypes);
|
||||
return new InferenceSession(model.ModalPath, options);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取带有缓存的模型(目前只支持TensorRT)
|
||||
/// 获取普通缓存目录(TensorRT / OpenVINO)
|
||||
/// </summary>
|
||||
/// <param name="model">模型</param>
|
||||
/// <param name="forcedProvider">强制使用的 providerTypes</param>
|
||||
/// <returns>带有缓存的模型绝对路径,null表示尚未创建缓存</returns>
|
||||
/// <returns>缓存目录绝对路径,null 表示当前 provider 不需要缓存</returns>
|
||||
private string? GetCached(BgiOnnxModel model, ProviderType[]? forcedProvider = null)
|
||||
{
|
||||
var providerTypes = forcedProvider ?? ProviderTypes;
|
||||
// 目前只支持TensorRT
|
||||
if (!providerTypes.Contains(ProviderType.TensorRt)) return null;
|
||||
var result = _cachedModelPaths.GetOrAdd(model, _GetCached);
|
||||
if (result is null) return result;
|
||||
|
||||
// 判断文件是否存在
|
||||
if (File.Exists(result)) return result;
|
||||
|
||||
_logger.LogWarning("[ONNX]模型 {Model} 的缓存文件可能已被删除,使用原始模型文件。", model.Name);
|
||||
return null;
|
||||
var providers = forcedProvider ?? ProviderTypes;
|
||||
if (!providers.Contains(ProviderType.TensorRt) && !providers.Contains(ProviderType.OpenVino)) return null;
|
||||
// 判断文件是否存在:这里只缓存目录,原始模型始终保持不变,不加载旧 _ctx.onnx。
|
||||
return _cachedModelPaths.GetOrAdd(model, _ => Runtime.GetCachePath(model));
|
||||
}
|
||||
|
||||
private string? _GetCached(BgiOnnxModel model)
|
||||
{
|
||||
if (model.ModelRelativePath.StartsWith(BgiOnnxModel.ModelCacheRelativePath) &&
|
||||
model.ModelRelativePath.EndsWith("_ctx.onnx"))
|
||||
// 这已经是带有缓存的文件路径了
|
||||
return model.ModalPath;
|
||||
|
||||
var ctxA = Path.Combine(model.CachePath, "trt", "_ctx.onnx");
|
||||
if (File.Exists(ctxA))
|
||||
{
|
||||
_logger.LogDebug("[ONNX]模型 {Model} 命中TRT匿名缓存文件: {Path}", model.Name, ctxA);
|
||||
return ctxA;
|
||||
}
|
||||
|
||||
var ctxB = Path.Combine(model.CachePath, "trt",
|
||||
Path.GetFileNameWithoutExtension(model.ModalPath) + "_ctx.onnx");
|
||||
if (File.Exists(ctxB))
|
||||
{
|
||||
_logger.LogDebug("[ONNX]模型 {Model} 命中TRT命名缓存文件: {Path}", model.Name, ctxB);
|
||||
return ctxB;
|
||||
}
|
||||
|
||||
_logger.LogDebug("[ONNX]没有找到模型 {Model} 的模型缓存文件。", model.Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 通过模型路径生成SessionOptions <br />
|
||||
/// 如果加载的模型文件已经是带有缓存的模型,请将cacheFolder设为null避免重复生成。
|
||||
/// 会话始终加载原始模型,缓存只用于加速原生 provider 的初始化。
|
||||
/// </summary>
|
||||
/// <param name="model">模型路径</param>
|
||||
/// <param name="genCache">是否生成缓存。有几种情况下不生成缓存:1为用户主动关闭,即enableCache为false。2为即将加载的模型文件已经是带有缓存的模型文件。</param>
|
||||
/// <param name="genCache">是否启用当前引擎的普通缓存。</param>
|
||||
/// <param name="forcedProvider">强制使用的Provider,为空或null则不强制</param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="InvalidEnumArgumentException"></exception>
|
||||
@@ -393,68 +172,92 @@ public class BgiOnnxFactory
|
||||
ProviderType[]? forcedProvider = null)
|
||||
{
|
||||
var sessionOptions = new SessionOptions();
|
||||
foreach (var type in
|
||||
forcedProvider is null || forcedProvider.Length == 0 ? ProviderTypes : forcedProvider)
|
||||
try
|
||||
try
|
||||
{
|
||||
var cache = genCache ? GetCached(model, forcedProvider) : null;
|
||||
var providers = forcedProvider is { Length: > 0 } ? forcedProvider : ProviderTypes;
|
||||
foreach (var type in providers)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case ProviderType.Dml:
|
||||
// DirectML 执行提供程序不支持在 onnxruntime 中使用内存模式优化或并行执行。在创建 InferenceSession 期间提供会话选项时,必须禁用这些选项,否则将返回错误。
|
||||
sessionOptions.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
sessionOptions.EnableMemoryPattern = false;
|
||||
sessionOptions.ExecutionMode = ExecutionMode.ORT_SEQUENTIAL;
|
||||
sessionOptions.AppendExecutionProvider_DML(DmlDeviceId);
|
||||
break;
|
||||
case ProviderType.Cpu:
|
||||
ConfigureCpuSessionOptions(sessionOptions, model, providers.Length == 1);
|
||||
sessionOptions.AppendExecutionProvider_CPU();
|
||||
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
|
||||
// {
|
||||
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
|
||||
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
|
||||
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
|
||||
// }
|
||||
break;
|
||||
case ProviderType.Dnnl:
|
||||
sessionOptions.AppendExecutionProvider_Dnnl();
|
||||
break;
|
||||
case ProviderType.OpenVino:
|
||||
sessionOptions.AppendExecutionProvider("OpenVINO",
|
||||
GetOpenVinoProviderConfig(OpenVinoCache ? model.CachePath : null));
|
||||
sessionOptions.AppendExecutionProvider("OpenVINO", GetOpenVinoProviderConfig(cache));
|
||||
sessionOptions.GraphOptimizationLevel = GraphOptimizationLevel.ORT_DISABLE_ALL;
|
||||
break;
|
||||
case ProviderType.TensorRt:
|
||||
using (var options = new OrtTensorRTProviderOptions())
|
||||
{
|
||||
options.UpdateOptions(GetTrtProviderConfig(genCache ? model.CachePath : null));
|
||||
options.UpdateOptions(GetTrtProviderConfig(cache));
|
||||
sessionOptions.AppendExecutionProvider_Tensorrt(options);
|
||||
}
|
||||
|
||||
break;
|
||||
case ProviderType.Cuda:
|
||||
using (var options = new OrtCUDAProviderOptions())
|
||||
{
|
||||
options.UpdateOptions(GetCudaProviderConfig());
|
||||
sessionOptions.AppendExecutionProvider_CUDA();
|
||||
sessionOptions.AppendExecutionProvider_CUDA(options);
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
throw new InvalidEnumArgumentException("无效的推理设备");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法加载指定的 ONNX provider {Provider},跳过。请检查推理设备配置是否正确。({Err})", Enum.GetName(type),
|
||||
e.Message);
|
||||
}
|
||||
|
||||
if (!OptimizedModel) return sessionOptions;
|
||||
if (!genCache) return sessionOptions;
|
||||
var optPath = Path.Combine(model.CachePath, "optimized");
|
||||
if (!Directory.Exists(optPath)) Directory.CreateDirectory(optPath);
|
||||
sessionOptions.OptimizedModelFilePath = Path.Combine(optPath, Path.GetFileName(model.ModalPath));
|
||||
return sessionOptions;
|
||||
return sessionOptions;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 目标 provider 初始化失败必须向上报告,不能跳过后用 CPU 假装验证成功。
|
||||
sessionOptions.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal void ConfigureCpuSessionOptions(SessionOptions sessionOptions, BgiOnnxModel model, bool cpuOnly)
|
||||
{
|
||||
var isPaddleOcr = model.Name.StartsWith("PpOcrDet", StringComparison.Ordinal)
|
||||
|| model.Name.StartsWith("PpOcrRec", StringComparison.Ordinal);
|
||||
// “ONNX Runtime 自动调度”需要跳过通用 CPU 线程数;新建 SessionOptions 的 0 即 ORT 原生默认值。
|
||||
if (!cpuOnly || !isPaddleOcr || Runtime.PaddleOcrCpu.Mode != PaddleOcrCpuMode.RuntimeAuto)
|
||||
sessionOptions.IntraOpNumThreads = Runtime.CpuThreads;
|
||||
ConfigurePaddleOcrCpu(sessionOptions, model, cpuOnly);
|
||||
}
|
||||
|
||||
/// <summary>只覆盖 PPOCR 纯 CPU 会话;GPU 会话的 CPU 兜底与其他模型仍使用全局设置。</summary>
|
||||
internal void ConfigurePaddleOcrCpu(SessionOptions sessionOptions, BgiOnnxModel model, bool cpuOnly)
|
||||
{
|
||||
if (!cpuOnly) return;
|
||||
var detection = model.Name.StartsWith("PpOcrDet", StringComparison.Ordinal);
|
||||
if (!detection && !model.Name.StartsWith("PpOcrRec", StringComparison.Ordinal)) return;
|
||||
if (Runtime.PaddleOcrCpu.Mode == PaddleOcrCpuMode.RuntimeAuto)
|
||||
{
|
||||
_logger.LogInformation("[ONNX]OCR CPU 线程策略,模型 {Model},使用 ONNX Runtime 自动调度", model.Name);
|
||||
return;
|
||||
}
|
||||
var options = Runtime.PaddleOcrCpu.Resolve(detection);
|
||||
if (options == null) return;
|
||||
sessionOptions.IntraOpNumThreads = options.IntraOpThreads;
|
||||
sessionOptions.InterOpNumThreads = options.InterOpThreads;
|
||||
sessionOptions.ExecutionMode = options.ParallelExecution ? ExecutionMode.ORT_PARALLEL : ExecutionMode.ORT_SEQUENTIAL;
|
||||
sessionOptions.AddSessionConfigEntry("session.intra_op.allow_spinning", options.AllowSpinning ? "1" : "0");
|
||||
sessionOptions.AddSessionConfigEntry("session.inter_op.allow_spinning", options.AllowSpinning ? "1" : "0");
|
||||
_logger.LogInformation("[ONNX]OCR CPU 线程策略,模型 {Model},算子内线程 {IntraOp},算子间线程 {InterOp},并行 {Parallel},自旋 {Spinning}",
|
||||
model.Name, options.IntraOpThreads, options.InterOpThreads, options.ParallelExecution, options.AllowSpinning);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取TensorRT的配置
|
||||
@@ -463,73 +266,22 @@ public class BgiOnnxFactory
|
||||
/// <returns>trt配置</returns>
|
||||
private Dictionary<string, string> GetTrtProviderConfig(string? cacheFolder)
|
||||
{
|
||||
var result = new Dictionary<string, string> { ["device_id"] = CudaDeviceId.ToString() };
|
||||
if (cacheFolder is null)
|
||||
{
|
||||
// 不使用缓存目录
|
||||
var r = new Dictionary<string, string>
|
||||
{
|
||||
["device_id"] = CudaDeviceId.ToString()
|
||||
};
|
||||
return r;
|
||||
return result;
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, string>
|
||||
{
|
||||
["trt_engine_cache_enable"] = "1",
|
||||
["trt_dump_ep_context_model"] = "1",
|
||||
["trt_ep_context_file_path"] = Path.Combine(cacheFolder, "trt"),
|
||||
// ["trt_ep_context_embed_mode"] = "1", // 因为yoloSharp是把模型转为嵌入式运行,不这样会爆炸
|
||||
// ["trt_engine_cache_path"] = ".\\" // 没必要了
|
||||
["trt_timing_cache_enable"] = "1",
|
||||
["trt_timing_cache_path"] =
|
||||
Global.Absolute(Path.Combine(BgiOnnxModel.ModelCacheRelativePath, "trt_timing")),
|
||||
// ["trt_force_timing_cache"] = "1",
|
||||
["device_id"] = CudaDeviceId.ToString()
|
||||
};
|
||||
if (TrtUseEmbedMode)
|
||||
{
|
||||
result["trt_ep_context_embed_mode"] = "1";
|
||||
}
|
||||
else
|
||||
{
|
||||
result["trt_ep_context_embed_mode"] = "0";
|
||||
result["trt_engine_cache_path"] = ".\\";
|
||||
}
|
||||
|
||||
if (!Directory.Exists(result["trt_ep_context_file_path"]))
|
||||
{
|
||||
// 如果不存在就创建目录
|
||||
_logger.LogDebug("[ONNX]TensorRT上下文文件路径不存在,创建目录: {Path}", result["trt_ep_context_file_path"]);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(result["trt_ep_context_file_path"]);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法创建TensorRT上下文文件路径: {Path},请检查权限。({Err})",
|
||||
result["trt_ep_context_file_path"], e.Message);
|
||||
// 如果无法创建目录,就不使用缓存
|
||||
result.Remove("trt_ep_context_file_path");
|
||||
}
|
||||
}
|
||||
|
||||
if (!Directory.Exists(result["trt_timing_cache_path"]))
|
||||
{
|
||||
// 如果不存在就创建目录
|
||||
_logger.LogDebug("[ONNX]TensorRT计时缓存路径不存在,创建目录: {Path}", result["trt_timing_cache_path"]);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(result["trt_timing_cache_path"]);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_logger.LogError("无法创建TensorRT计时缓存路径: {Path},请检查权限。({Err})",
|
||||
result["trt_timing_cache_path"], e.Message);
|
||||
// 如果无法创建目录,就不使用缓存
|
||||
result.Remove("trt_timing_cache_path");
|
||||
}
|
||||
}
|
||||
|
||||
// 如果不存在就创建目录。使用普通 engine/timing 缓存,不导出或嵌入优化模型。
|
||||
var engine = Path.Combine(cacheFolder, "trt");
|
||||
var timing = Path.Combine(cacheFolder, "trt_timing");
|
||||
Directory.CreateDirectory(engine);
|
||||
Directory.CreateDirectory(timing);
|
||||
result["trt_engine_cache_enable"] = "1";
|
||||
result["trt_engine_cache_path"] = engine;
|
||||
result["trt_timing_cache_enable"] = "1";
|
||||
result["trt_timing_cache_path"] = timing;
|
||||
// ["trt_force_timing_cache"] = "1", // 不跨设备强制复用 timing cache。
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -556,7 +308,7 @@ public class BgiOnnxFactory
|
||||
var result = new Dictionary<string, string>();
|
||||
if (!string.IsNullOrWhiteSpace(OpenVinoDevice))
|
||||
{
|
||||
result["deice_type"] = OpenVinoDevice;
|
||||
result["device_type"] = OpenVinoDevice;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(cacheFolder))
|
||||
@@ -579,7 +331,26 @@ public class BgiOnnxFactory
|
||||
}
|
||||
}
|
||||
|
||||
result["enable_opencl_throttling"] = "true";
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
#region 历史路径探测说明(仅保留注释,依赖由独立安装目录管理)
|
||||
// 获取 硬件加速配置
|
||||
// 为了单元测试
|
||||
// 直接使用配置
|
||||
// 如果配置获取失败,使用默认配置
|
||||
// 自动嗅探并修改path以加载cuda
|
||||
// 例如: CUDNN\v9.8\lib\12.8\x64
|
||||
// 获取所有可能包含CUDA/cuDNN路径的环境变量
|
||||
// 环境变量下层文件夹
|
||||
// lib路径
|
||||
// cuda的版本
|
||||
// 体系架构
|
||||
//构建完了需要搜索的路径,去重。
|
||||
//确定路径是否真的存在
|
||||
//确定需要的文件是否存在
|
||||
//去重
|
||||
// 将附加的path应用进来
|
||||
// <param name="extraPath">附加的path字符串</param>
|
||||
#endregion
|
||||
}
|
||||
@@ -42,7 +42,7 @@ public class BgiOnnxModel
|
||||
/// <summary>
|
||||
/// 用于捡东西等的大世界模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiWorld = Register("BgiTree", @"Assets\Model\World\bgi_world.onnx");
|
||||
public static readonly BgiOnnxModel BgiWorld = Register("BgiWorld", @"Assets\Model\World\bgi_world.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 矿物识别模型
|
||||
@@ -61,12 +61,30 @@ public class BgiOnnxModel
|
||||
public static readonly BgiOnnxModel BgiQClassify =
|
||||
Register("BgiQClassify", @"Assets\Model\Common\q_classify_sim.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// E技能就绪分类模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel BgiEClassify =
|
||||
Register("BgiEClassify", @"Assets\Model\Common\e_classify_sim.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 队伍配置角色头像识别模型
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel AvatarGridIcon =
|
||||
Register("AvatarGridIcon", @"Assets\Model\AvatarGridIcon\avatar.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 物品网格图标识别模型,固定使用 CPU。
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel GridIcon =
|
||||
Register("GridIcon", @"Assets\Model\Item\gridIcon.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// 物品图标识别模型,固定使用 CPU。
|
||||
/// </summary>
|
||||
public static readonly BgiOnnxModel ItemIcon =
|
||||
Register("ItemIcon", @"Assets\Model\ItemV2\item.onnx");
|
||||
|
||||
/// <summary>
|
||||
/// Silero 人声检测模型
|
||||
/// </summary>
|
||||
@@ -135,7 +153,7 @@ public class BgiOnnxModel
|
||||
|
||||
#endregion
|
||||
|
||||
private BgiOnnxModel(string name, string modelRelativePath, string cacheRelativePath)
|
||||
public BgiOnnxModel(string name, string modelRelativePath, string cacheRelativePath)
|
||||
{
|
||||
Name = name;
|
||||
ModelRelativePath = modelRelativePath;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
using System;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using OpenCvSharp;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
|
||||
@@ -17,6 +16,9 @@ public class BgiYoloPredictor : IDisposable
|
||||
|
||||
|
||||
private readonly Lazy<YoloPredictor> _lazyPredictor;
|
||||
private readonly SessionOptions _sessionOptions;
|
||||
private readonly object _syncRoot = new();
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// 使用 BgiOnnxFactory 创建这个类的实例
|
||||
@@ -27,14 +29,36 @@ public class BgiYoloPredictor : IDisposable
|
||||
protected internal BgiYoloPredictor(BgiOnnxModel onnxModel, string modelPath, SessionOptions sessionOptions)
|
||||
{
|
||||
_model = onnxModel;
|
||||
_lazyPredictor = new Lazy<YoloPredictor>(() => new YoloPredictor(modelPath,
|
||||
new YoloPredictorOptions
|
||||
_sessionOptions = sessionOptions;
|
||||
_lazyPredictor = new Lazy<YoloPredictor>(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
SessionOptions = sessionOptions
|
||||
}));
|
||||
return new YoloPredictor(modelPath, new YoloPredictorOptions
|
||||
{
|
||||
SessionOptions = _sessionOptions
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 会话创建完成(含失败)后不再需要配置;未初始化时由 Dispose 释放。
|
||||
_sessionOptions.Dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public YoloPredictor Predictor => _lazyPredictor.Value;
|
||||
public YoloPredictor Predictor
|
||||
{
|
||||
get
|
||||
{
|
||||
// 串行化延迟初始化与释放,避免创建会话时配置被提前释放。
|
||||
lock (_syncRoot)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
return _lazyPredictor.Value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检测
|
||||
@@ -63,18 +87,31 @@ public class BgiYoloPredictor : IDisposable
|
||||
|
||||
var list = result
|
||||
.Select(box => new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height))
|
||||
.Select(rect => region.ToRectDrawable(rect, _model.Name)).ToList();
|
||||
.Select(rect => region.ToMaskWindowDrawingRect(rect)).ToList();
|
||||
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(_model.Name, list);
|
||||
region.DrawingBoard.Set(_model.Name, list);
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_lazyPredictor.IsValueCreated)
|
||||
lock (_syncRoot)
|
||||
{
|
||||
Predictor.Dispose();
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
try
|
||||
{
|
||||
if (_lazyPredictor.IsValueCreated)
|
||||
{
|
||||
_lazyPredictor.Value.Dispose();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_sessionOptions.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public interface IInferenceBenchmarkLeaseProvider
|
||||
{
|
||||
bool IsAvailable { get; }
|
||||
IDisposable Acquire();
|
||||
}
|
||||
|
||||
/// <summary>与独立任务使用同一把锁,暂停并等待正在执行的自动识别帧完成。</summary>
|
||||
public sealed class InferenceBenchmarkCoordinator(SemaphoreSlim taskSemaphore, Func<IDisposable> suspend) : IInferenceBenchmarkLeaseProvider
|
||||
{
|
||||
public bool IsAvailable => taskSemaphore.CurrentCount > 0;
|
||||
public IDisposable Acquire()
|
||||
{
|
||||
if (!taskSemaphore.Wait(0)) throw new InvalidOperationException("请先停止正在运行的任务,再进行推理测速。");
|
||||
try { return new Lease(taskSemaphore, suspend()); }
|
||||
catch { taskSemaphore.Release(); throw; }
|
||||
}
|
||||
|
||||
private sealed class Lease(SemaphoreSlim semaphore, IDisposable suspension) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
try { suspension.Dispose(); }
|
||||
finally { semaphore.Release(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using SharpDX.DXGI;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public interface IInferenceDeviceDiscovery
|
||||
{
|
||||
IReadOnlyList<InferenceDeviceInfo> GetDevices(InferenceDeviceType engine, string runtimeDirectory);
|
||||
}
|
||||
|
||||
/// <summary>只探测硬件 API,不加载、替换其他引擎的 onnxruntime.dll。</summary>
|
||||
public sealed class InferenceDeviceDiscovery : IInferenceDeviceDiscovery
|
||||
{
|
||||
public IReadOnlyList<InferenceDeviceInfo> GetDevices(InferenceDeviceType engine, string runtimeDirectory) => engine switch
|
||||
{
|
||||
InferenceDeviceType.Cpu => [ResolvedInferenceRuntime.CpuDevice],
|
||||
InferenceDeviceType.DirectML => GetDirectMlDevices(),
|
||||
InferenceDeviceType.CUDA or InferenceDeviceType.TensorRT => GetNvidiaDevices(engine),
|
||||
InferenceDeviceType.OpenVINO => GetOpenVinoDevices(runtimeDirectory),
|
||||
_ => []
|
||||
};
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetDirectMlDevices()
|
||||
{
|
||||
if (!BetterGenshinImpact.Helpers.OsVersionHelper.IsWindows10_1903_OrGreater) return [];
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
using var factory = new Factory1();
|
||||
for (var index = 0; ; index++)
|
||||
{
|
||||
Adapter1 adapter;
|
||||
try { adapter = factory.GetAdapter1(index); }
|
||||
catch (SharpDX.SharpDXException) { break; }
|
||||
using (adapter)
|
||||
{
|
||||
var description = adapter.Description1;
|
||||
if ((description.Flags & AdapterFlags.Software) != 0) continue;
|
||||
var iid = new Guid("189819f1-1db6-4b57-be54-1821339b85f7");
|
||||
var result = D3D12CreateDevice(adapter.NativePointer, 0xb000, ref iid, out var device);
|
||||
if (device != IntPtr.Zero) Marshal.Release(device);
|
||||
if (result < 0) continue;
|
||||
var id = GetDirectMlIdentity(description);
|
||||
devices.Add(new(id, description.Description.Trim(), index, index.ToString()));
|
||||
}
|
||||
}
|
||||
return NormalizeDirectMlDevices(devices);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<InferenceDeviceInfo> NormalizeDirectMlDevices(IReadOnlyList<InferenceDeviceInfo> devices)
|
||||
{
|
||||
// DXGI 可能暴露同一物理显卡的多个适配器入口。保留原始序号,不重新编号。
|
||||
var unique = devices.DistinctBy(device => device.Id).ToArray();
|
||||
return unique.Select(device => unique.Count(other => other.Name == device.Name) > 1
|
||||
? device with { Name = $"{device.Name}(设备 {device.Index + 1})" } : device).ToArray();
|
||||
}
|
||||
|
||||
private static string GetDirectMlIdentity(AdapterDescription1 description)
|
||||
{
|
||||
// LUID 只在一次 Windows 启动期间稳定,持久化时改用显卡的 PCI 位置和型号。
|
||||
var adapter = new KernelAdapter { Luid = description.Luid };
|
||||
if (D3DKMTOpenAdapterFromLuid(ref adapter) >= 0)
|
||||
{
|
||||
var buffer = Marshal.AllocHGlobal(Marshal.SizeOf<AdapterAddress>());
|
||||
try
|
||||
{
|
||||
var query = new AdapterQuery { Handle = adapter.Handle, Type = 6, Data = buffer, Size = (uint)Marshal.SizeOf<AdapterAddress>() };
|
||||
if (D3DKMTQueryAdapterInfo(ref query) >= 0)
|
||||
{
|
||||
var address = Marshal.PtrToStructure<AdapterAddress>(buffer);
|
||||
return $"DXGI:{description.VendorId:X4}:{description.DeviceId:X4}:{address.Bus}:{address.Device}:{address.Function}";
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
var handle = adapter.Handle;
|
||||
D3DKMTCloseAdapter(ref handle);
|
||||
}
|
||||
}
|
||||
// 非 PCI 适配器保留型号与 LUID,避免误合并多张同型号显卡。跨启动标识失效时重新选设备。
|
||||
return $"DXGI:{description.VendorId:X4}:{description.DeviceId:X4}:{description.SubsystemId:X8}:{description.Luid:X16}";
|
||||
}
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetNvidiaDevices(InferenceDeviceType engine)
|
||||
{
|
||||
if (!NativeLibrary.TryLoad(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "nvcuda.dll"), out var library)) return [];
|
||||
try
|
||||
{
|
||||
var init = Get<CudaInit>(library, "cuInit");
|
||||
var count = Get<CudaCount>(library, "cuDeviceGetCount");
|
||||
var get = Get<CudaDevice>(library, "cuDeviceGet");
|
||||
var name = Get<CudaName>(library, "cuDeviceGetName");
|
||||
var uuid = Get<CudaUuid>(library, "cuDeviceGetUuid");
|
||||
var attribute = Get<CudaAttribute>(library, "cuDeviceGetAttribute");
|
||||
var driverVersion = Get<CudaCount>(library, "cuDriverGetVersion");
|
||||
if (init(0) != 0 || driverVersion(out var version) != 0 || version < 12000 || count(out var size) != 0) return [];
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
var compatible = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
for (var ordinal = 0; ordinal < size; ordinal++)
|
||||
{
|
||||
if (get(out var device, ordinal) != 0) continue;
|
||||
var text = new StringBuilder(256);
|
||||
if (name(text, text.Capacity, device) != 0 || uuid(out var id, device) != 0) continue;
|
||||
if (attribute(out var major, 75, device) != 0 || attribute(out var minor, 76, device) != 0) continue;
|
||||
// TensorRT 10.8 的硬件下限为 Turing (SM 7.5),不把旧显卡作为可选设备。
|
||||
var bytes = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref id, 1));
|
||||
var hex = Convert.ToHexString(bytes).ToLowerInvariant();
|
||||
var key = $"GPU-{hex[..8]}-{hex[8..12]}-{hex[12..16]}-{hex[16..20]}-{hex[20..]}";
|
||||
devices.Add(new(key, text.ToString(), ordinal, ordinal.ToString()));
|
||||
if ((engine != InferenceDeviceType.TensorRT && major >= 5) || (engine == InferenceDeviceType.TensorRT && major * 10 + minor >= 75))
|
||||
compatible.Add(key);
|
||||
}
|
||||
// cuInit 已按 CUDA_VISIBLE_DEVICES 过滤并重排设备,ordinal 就是 ORT 需要的 device_id,不能再次映射。
|
||||
return devices.Where(device => compatible.Contains(device.Id)).ToArray();
|
||||
}
|
||||
finally { NativeLibrary.Free(library); }
|
||||
}
|
||||
|
||||
private static IReadOnlyList<InferenceDeviceInfo> GetOpenVinoDevices(string directory)
|
||||
{
|
||||
var path = Path.Combine(directory, "openvino_c.dll");
|
||||
if (!File.Exists(path)) return [];
|
||||
var library = LoadLibraryEx(path, IntPtr.Zero, 0x00001100);
|
||||
if (library == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "OpenVINO 设备探测库加载失败");
|
||||
IntPtr core = IntPtr.Zero;
|
||||
var available = new OpenVinoDevices();
|
||||
try
|
||||
{
|
||||
var create = Get<OvCreate>(library, "ov_core_create");
|
||||
var get = Get<OvDevices>(library, "ov_core_get_available_devices");
|
||||
var property = Get<OvProperty>(library, "ov_core_get_property");
|
||||
var free = Get<OvFree>(library, "ov_free");
|
||||
if (create(out core) != 0 || get(core, ref available) != 0)
|
||||
throw new InvalidOperationException("无法枚举 OpenVINO 设备,请检查设备驱动。");
|
||||
var devices = new List<InferenceDeviceInfo>();
|
||||
for (var i = 0; i < checked((int)available.Size); i++)
|
||||
{
|
||||
var id = Marshal.PtrToStringUTF8(Marshal.ReadIntPtr(available.Devices, i * IntPtr.Size));
|
||||
if (id == null || !(id == "CPU" || id.StartsWith("GPU", StringComparison.Ordinal) || id.StartsWith("NPU", StringComparison.Ordinal))) continue;
|
||||
string display = id;
|
||||
if (property(core, id, "FULL_DEVICE_NAME", out var value) == 0 && value != IntPtr.Zero)
|
||||
{
|
||||
try { display = $"{id} · {Marshal.PtrToStringUTF8(value)}"; }
|
||||
finally { free(value); }
|
||||
}
|
||||
devices.Add(new(id, display, i, id));
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (available.Devices != IntPtr.Zero) Get<OvDevicesFree>(library, "ov_available_devices_free")(ref available);
|
||||
if (core != IntPtr.Zero) Get<OvFree>(library, "ov_core_free")(core);
|
||||
NativeLibrary.Free(library);
|
||||
}
|
||||
}
|
||||
|
||||
private static T Get<T>(IntPtr library, string name) where T : Delegate => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library, name));
|
||||
[StructLayout(LayoutKind.Sequential)] private struct DeviceUuid { public uint A, B, C, D; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct KernelAdapter { public long Luid; public uint Handle; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct AdapterAddress { public uint Bus, Device, Function; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct AdapterQuery { public uint Handle; public int Type; public IntPtr Data; public uint Size; }
|
||||
[StructLayout(LayoutKind.Sequential)] private struct OpenVinoDevices { public IntPtr Devices; public nuint Size; }
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaInit(uint flags);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaCount(out int count);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaDevice(out int device, int ordinal);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet = CharSet.Ansi)] private delegate int CudaName(StringBuilder name, int length, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaUuid(out DeviceUuid uuid, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate int CudaAttribute(out int value, int attribute, int device);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvCreate(out IntPtr core);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvDevices(IntPtr core, ref OpenVinoDevices devices);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void OvDevicesFree(ref OpenVinoDevices devices);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int OvProperty(IntPtr core, [MarshalAs(UnmanagedType.LPUTF8Str)] string device, [MarshalAs(UnmanagedType.LPUTF8Str)] string key, out IntPtr value);
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void OvFree(IntPtr value);
|
||||
[DllImport("d3d12.dll")] private static extern int D3D12CreateDevice(IntPtr adapter, int level, ref Guid iid, out IntPtr device);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTOpenAdapterFromLuid(ref KernelAdapter adapter);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTQueryAdapterInfo(ref AdapterQuery query);
|
||||
[DllImport("gdi32.dll")] private static extern int D3DKMTCloseAdapter(ref uint handle);
|
||||
[DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr LoadLibraryEx(string path, IntPtr file, uint flags);
|
||||
}
|
||||
@@ -1,9 +1,32 @@
|
||||
// ReSharper disable InconsistentNaming
|
||||
using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
[JsonConverter(typeof(InferenceDeviceTypeJsonConverter))]
|
||||
public enum InferenceDeviceType
|
||||
{
|
||||
Cpu,
|
||||
GpuDirectMl,
|
||||
Gpu,
|
||||
OpenVino
|
||||
}
|
||||
// 保持已有后端的配置编号,旧 Gpu 的编号 2 不再复用,读取时回退 CPU。
|
||||
Cpu = 0,
|
||||
DirectML = 1,
|
||||
OpenVINO = 3,
|
||||
CUDA = 4,
|
||||
// TensorRT 推理速度特别慢(首次还要构建引擎,等待时间更长),已从设置页与首页下线:
|
||||
// 界面不再提供该选项,历史配置在启动准备阶段自动回退 CPU。枚举编号、运行库与 provider 代码保留,便于日后恢复。
|
||||
TensorRT = 5
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推理引擎在界面上的可用范围。TensorRT 首次构建引擎耗时过长,已从设置页与首页下线;
|
||||
/// 枚举编号、运行库与 provider 代码保留,便于日后恢复。
|
||||
/// </summary>
|
||||
public static class InferenceDeviceTypeExtensions
|
||||
{
|
||||
/// <summary>设置页与首页可供用户选择的推理引擎,顺序即界面顺序。</summary>
|
||||
public static readonly InferenceDeviceType[] Selectable =
|
||||
[InferenceDeviceType.Cpu, InferenceDeviceType.DirectML, InferenceDeviceType.OpenVINO, InferenceDeviceType.CUDA];
|
||||
|
||||
public static bool IsSelectable(this InferenceDeviceType engine) => Selectable.Contains(engine);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>
|
||||
/// 保留现有数字配置格式;旧 Gpu、未知枚举值和无法识别的设置只回退推理类型,
|
||||
/// 不让单个字段的兼容问题导致整份配置读取失败。
|
||||
/// </summary>
|
||||
public sealed class InferenceDeviceTypeJsonConverter : JsonConverter<InferenceDeviceType>
|
||||
{
|
||||
public override bool HandleNull => true;
|
||||
|
||||
public override InferenceDeviceType Read(ref Utf8JsonReader reader, Type typeToConvert,
|
||||
JsonSerializerOptions options)
|
||||
{
|
||||
if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt32(out var number))
|
||||
{
|
||||
var value = (InferenceDeviceType)number;
|
||||
return Enum.IsDefined(value) ? value : InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
var name = reader.GetString();
|
||||
// 未标记 Flags 的枚举也能解析逗号组合,推理类型只接受一个明确的选项。
|
||||
if (name is not null && !name.Contains(',') &&
|
||||
Enum.TryParse<InferenceDeviceType>(name, true, out var value) && Enum.IsDefined(value))
|
||||
return value;
|
||||
}
|
||||
|
||||
// 对错误的对象或数组值消费整个节点,继续读取同一配置中的其他字段。
|
||||
reader.Skip();
|
||||
return InferenceDeviceType.Cpu;
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, InferenceDeviceType value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteNumberValue(Enum.IsDefined(value) ? (int)value : (int)InferenceDeviceType.Cpu);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>每个引擎独立保存的用户设置,原生 provider 的参数由工厂统一生成。</summary>
|
||||
public partial class InferenceEngineSettings : ObservableObject
|
||||
{
|
||||
[ObservableProperty] private string _deviceId = "";
|
||||
[ObservableProperty] private int _cpuThreads;
|
||||
[ObservableProperty] private bool _enableModelCache = true;
|
||||
|
||||
public InferenceEngineSettings Copy() => new()
|
||||
{
|
||||
DeviceId = DeviceId, CpuThreads = CpuThreads, EnableModelCache = EnableModelCache
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Image = SixLabors.ImageSharp.Image;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public sealed record InferenceBenchmarkProgress(string Scene, int Completed, int Total);
|
||||
public sealed record InferenceBenchmarkResult(string Scene, string Execution, IReadOnlyList<double> Milliseconds)
|
||||
{
|
||||
public double Average => Milliseconds.Average();
|
||||
public double Minimum => Milliseconds.Min();
|
||||
public double Maximum => Milliseconds.Max();
|
||||
public string SamplesText => "每次耗时(ms):" + string.Join(" / ", Milliseconds.Select(t => t.ToString("F1")));
|
||||
}
|
||||
|
||||
/// <summary>将面向用户的失败原因与供日志排查的原始技术信息分开。</summary>
|
||||
internal sealed class InferenceValidationException(
|
||||
string scene, string userReason, string technicalDetails, Exception? innerException = null)
|
||||
: InvalidOperationException(technicalDetails, innerException)
|
||||
{
|
||||
public string Scene { get; } = scene;
|
||||
public string UserReason { get; } = userReason;
|
||||
}
|
||||
|
||||
public interface IInferenceModelDiagnostics
|
||||
{
|
||||
bool HasDomainTreeImage { get; }
|
||||
Task ValidateTreeAsync(BgiOnnxSessionFactory factory, CancellationToken token);
|
||||
Task ValidateOcrAsync(BgiOnnxSessionFactory factory, CancellationToken token);
|
||||
Task PreheatOcrAsync();
|
||||
Task<InferenceBenchmarkResult> BenchmarkAsync(InferenceBenchmarkScene scene, BgiOnnxSessionFactory factory,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token);
|
||||
}
|
||||
|
||||
public sealed class InferenceModelDiagnostics(
|
||||
OcrFactory ocr, IInferenceBenchmarkLeaseProvider leases, ILogger<InferenceModelDiagnostics> logger)
|
||||
: IInferenceModelDiagnostics, IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private readonly object _warmupLock = new();
|
||||
private Task? _warmupTask;
|
||||
public bool HasDomainTreeImage => InferenceTestImages.HasDomainTreeImage;
|
||||
|
||||
public Task PreheatOcrAsync()
|
||||
{
|
||||
lock (_warmupLock)
|
||||
return _warmupTask ??= Task.Run(async () =>
|
||||
{
|
||||
await _gate.WaitAsync(_lifetime.Token);
|
||||
try
|
||||
{
|
||||
_lifetime.Token.ThrowIfCancellationRequested();
|
||||
var service = ocr.PaddleOcr;
|
||||
using var image = new Mat(ocr.ActiveModelType.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 预热图片无法读取。");
|
||||
Debug.WriteLine("PaddleOcr预热结果:" + service.Ocr(image));
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}, _lifetime.Token);
|
||||
}
|
||||
|
||||
public async Task ValidateTreeAsync(BgiOnnxSessionFactory factory, CancellationToken token)
|
||||
{
|
||||
if (!HasDomainTreeImage) throw new FileNotFoundException("古树测试图片待提供。", InferenceTestImages.DomainTreePath);
|
||||
await ValidateAsync(factory, "古树检测", validationToken =>
|
||||
{
|
||||
using var image = Image.Load<Rgb24>(InferenceTestImages.DomainTreePath);
|
||||
using var predictor = factory.CreateYoloPredictor(BgiOnnxModel.BgiTree);
|
||||
_ = predictor.Predictor.Detect(image);
|
||||
logger.LogInformation("[ONNX]古树检测完整推理已执行");
|
||||
}, token);
|
||||
}
|
||||
|
||||
public Task ValidateOcrAsync(BgiOnnxSessionFactory factory, CancellationToken token)
|
||||
=> ValidateAsync(factory, "OCR", validationToken =>
|
||||
{
|
||||
var model = ocr.ActiveModelType;
|
||||
using var image = new Mat(model.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 验证图片无法读取。");
|
||||
using var service = new PaddleOcrService(factory.ForOcrValidation(), model);
|
||||
validationToken.ThrowIfCancellationRequested();
|
||||
_ = service.Ocr(image);
|
||||
logger.LogInformation("[ONNX]OCR 验证完整推理已执行");
|
||||
}, token);
|
||||
|
||||
/// <summary>验证所选 provider 能创建会话并完成一次真实推理;不再解析性能记录判断单个算子的执行位置。</summary>
|
||||
private async Task ValidateAsync(BgiOnnxSessionFactory factory, string scene,
|
||||
Action<CancellationToken> inference, CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
await _gate.WaitAsync(linked.Token);
|
||||
try
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
inference(linked.Token);
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (InferenceValidationException) { throw; }
|
||||
catch (Exception e)
|
||||
{
|
||||
throw CreateRuntimeFailure(scene, factory.Runtime, e);
|
||||
}
|
||||
}, linked.Token);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
internal static InferenceValidationException CreateRuntimeFailure(string scene, ResolvedInferenceRuntime runtime,
|
||||
Exception exception)
|
||||
{
|
||||
var cause = exception.GetBaseException();
|
||||
var message = cause.Message;
|
||||
var missingDependencies = OnnxRuntimePackageCatalog.MissingDependencyFiles(runtime.Engine, runtime.RuntimeDirectory);
|
||||
string reason;
|
||||
if (missingDependencies.Length > 0 &&
|
||||
(cause is DllNotFoundException || message.Contains("LoadLibrary", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("找不到指定的模块", StringComparison.OrdinalIgnoreCase)))
|
||||
reason = OnnxRuntimePackageCatalog.DescribeMissingDependencies(runtime.Engine, missingDependencies);
|
||||
else if (cause is DllNotFoundException || message.Contains("LoadLibrary", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("找不到指定的模块", StringComparison.OrdinalIgnoreCase))
|
||||
reason = "运行库或配套依赖无法加载,请在硬件加速设置中重新检测并补齐依赖。";
|
||||
else if (cause is BadImageFormatException)
|
||||
reason = "运行库文件与当前系统不兼容,请重新下载该推理引擎。";
|
||||
else if (cause is FileNotFoundException fileNotFound)
|
||||
reason = $"验证需要的文件“{Path.GetFileName(fileNotFound.FileName) ?? "未知文件"}”不存在。";
|
||||
else if (cause is OutOfMemoryException || message.Contains("out of memory", StringComparison.OrdinalIgnoreCase))
|
||||
reason = "运行模型时内存或显存不足。";
|
||||
else if (message.Contains("device", StringComparison.OrdinalIgnoreCase)
|
||||
&& (message.Contains("not found", StringComparison.OrdinalIgnoreCase)
|
||||
|| message.Contains("unavailable", StringComparison.OrdinalIgnoreCase)))
|
||||
reason = "保存的推理设备当前不可用,请重新选择设备。";
|
||||
else
|
||||
reason = $"加载或运行{scene}模型时发生错误,详细错误已记录到硬件加速设置和日志中。";
|
||||
|
||||
var technicalDetails = $"{scene}验证异常:{message}";
|
||||
if (missingDependencies.Length > 0)
|
||||
technicalDetails += $"\r\n运行库目录:{runtime.RuntimeDirectory}\r\n缺少依赖:{string.Join("、", missingDependencies)}";
|
||||
return new InferenceValidationException(scene, reason, technicalDetails, exception);
|
||||
}
|
||||
|
||||
public async Task<InferenceBenchmarkResult> BenchmarkAsync(InferenceBenchmarkScene scene, BgiOnnxSessionFactory factory,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
if (scene == InferenceBenchmarkScene.DomainTree && !HasDomainTreeImage) throw new FileNotFoundException("古树测试图片待提供。");
|
||||
using var lease = await Task.Run(leases.Acquire, linked.Token);
|
||||
await _gate.WaitAsync(linked.Token);
|
||||
try
|
||||
{
|
||||
// 在主程序后台测量,结束单次原生调用之后才能响应取消并释放会话。
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
if (scene == InferenceBenchmarkScene.Ocr)
|
||||
{
|
||||
var type = ocr.ActiveModelType;
|
||||
using var service = new PaddleOcrService(factory, type);
|
||||
using var image = new Mat(ocr.ActiveModelType.PreHeatImagePath);
|
||||
if (image.Empty()) throw new InvalidDataException("OCR 测试图片无法读取。");
|
||||
return Measure("OCR", $"{factory.Runtime.OcrDescription} · {type.DetectionModel.Name}/{type.RecognitionModel.Name}",
|
||||
() => _ = service.Ocr(image), progress, linked.Token);
|
||||
}
|
||||
using var treeImage = Image.Load<Rgb24>(InferenceTestImages.DomainTreePath);
|
||||
using var predictor = factory.CreateYoloPredictor(BgiOnnxModel.BgiTree);
|
||||
return Measure("古树检测", factory.Runtime.Description,
|
||||
() => _ = predictor.Predictor.Detect(treeImage), progress, linked.Token);
|
||||
}, linked.Token);
|
||||
}
|
||||
finally { _gate.Release(); }
|
||||
}
|
||||
|
||||
public static InferenceBenchmarkResult Measure(string scene, string execution, Action inference,
|
||||
IProgress<InferenceBenchmarkProgress>? progress, CancellationToken token)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
progress?.Report(new(scene + "预热", 0, 10));
|
||||
inference();
|
||||
var times = new double[10];
|
||||
for (var i = 0; i < times.Length; i++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var start = Stopwatch.GetTimestamp();
|
||||
inference();
|
||||
times[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
|
||||
progress?.Report(new(scene, i + 1, times.Length));
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
return new(scene, execution, times);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
Task? warmup;
|
||||
lock (_warmupLock) warmup = _warmupTask;
|
||||
if (warmup != null)
|
||||
{
|
||||
try { await warmup; }
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception) { /* 预热错误已经由调用方报告;退出仍须等待资源释放。 */ }
|
||||
}
|
||||
await _gate.WaitAsync();
|
||||
_gate.Release();
|
||||
}
|
||||
|
||||
public void Dispose() { _lifetime.Dispose(); _gate.Dispose(); }
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>仅属于本次启动的提示,不从持久化的历史验证错误恢复。</summary>
|
||||
public sealed record InferenceStartupStatus(string FallbackMessage, bool IsMainInstance = true);
|
||||
|
||||
/// <summary>设备配置先发布;主窗口加载后的友好验证不作为业务初始化的前置条件。</summary>
|
||||
public sealed class InferenceRuntimeService(
|
||||
IConfigService configService, IOnnxRuntimeSelection loader, IInferenceDeviceDiscovery devices,
|
||||
IInferenceModelDiagnostics diagnostics, ILogger<BgiOnnxFactory> logger, InferenceStartupStatus? startupStatus = null) : IDisposable
|
||||
{
|
||||
private sealed record PublishedRuntime(ResolvedInferenceRuntime Runtime, bool IsValidated);
|
||||
|
||||
private PublishedRuntime? _published;
|
||||
private readonly object _initializationLock = new();
|
||||
private readonly object _settingsLock = new();
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
private Task? _initializationTask;
|
||||
private Task? _validationTask;
|
||||
private long _settingsRevision;
|
||||
private long _startupRevision;
|
||||
private PublishedRuntime Published => Volatile.Read(ref _published)
|
||||
?? throw new InvalidOperationException("推理初始化尚未完成。");
|
||||
public ResolvedInferenceRuntime Current => Published.Runtime;
|
||||
public bool IsReady => Volatile.Read(ref _published) != null;
|
||||
public bool IsStopping => _lifetime.IsCancellationRequested;
|
||||
public bool IsCurrentValidated => Volatile.Read(ref _published)?.IsValidated ?? false;
|
||||
public bool HasPendingRestart => Interlocked.Read(ref _settingsRevision) != Interlocked.Read(ref _startupRevision);
|
||||
public string StartupMessage { get; private set; } = startupStatus?.FallbackMessage ?? "";
|
||||
public event EventHandler? SettingsChanged;
|
||||
private bool IsMainInstance => startupStatus?.IsMainInstance ?? true;
|
||||
private HardwareAccelerationConfig Config => configService.Get().HardwareAccelerationConfig;
|
||||
|
||||
public static InferenceStartupStatus PrepareStartup(HardwareAccelerationConfig config, bool isMainInstance = true)
|
||||
{
|
||||
var fallbackMessage = "";
|
||||
config.LastValidationError ??= "";
|
||||
config.VerifiedSignature ??= "";
|
||||
config.ValidatedEngines ??= [];
|
||||
// 新增 OCR 参数单独修正,避免无效比例或换用核心数较少的处理器时丢失其他引擎设置。
|
||||
config.PaddleOcrCpu = PaddleOcrCpuConfig.FromOptions((config.PaddleOcrCpu ?? new()).ToOptions().Normalize());
|
||||
if (config.IsExpectedConfiguration && !string.IsNullOrWhiteSpace(config.VerifiedSignature))
|
||||
{
|
||||
// 兼容已有的单份验证签名:只恢复能与保存参数匹配的历史成功记录。
|
||||
foreach (var engine in Enum.GetValues<InferenceDeviceType>().Where(engine => engine != InferenceDeviceType.Cpu))
|
||||
{
|
||||
var settings = config.GetEngineSettings(engine);
|
||||
if (string.IsNullOrWhiteSpace(settings.DeviceId)) continue;
|
||||
if (InferenceRuntimeFingerprint.Compute(config, engine) == config.VerifiedSignature)
|
||||
config.RecordValidatedEngine(engine);
|
||||
}
|
||||
}
|
||||
if (!config.IsExpectedConfiguration)
|
||||
{
|
||||
config.ResetToDefaults();
|
||||
config.LastFailedEngine = null;
|
||||
config.LastValidationError = "";
|
||||
}
|
||||
else if (!config.InferenceDevice.IsSelectable())
|
||||
{
|
||||
// TensorRT 已下线:只把生效引擎改回 CPU,其他引擎已保存的设备参数保持不变。
|
||||
var retiredEngine = config.InferenceDevice;
|
||||
config.SwitchToCpu();
|
||||
config.LastFailedEngine = null;
|
||||
config.LastValidationError = "";
|
||||
fallbackMessage = $"{retiredEngine} 推理引擎已停止提供(首次构建引擎耗时过长),本次已使用 CPU。\r\n\r\n" +
|
||||
"请在首页的“硬件加速设置”中选择其他引擎后重试。";
|
||||
}
|
||||
else if (isMainInstance && config.ValidationState == InferenceValidationState.Validating)
|
||||
{
|
||||
var failedEngine = config.InferenceDevice;
|
||||
config.SwitchToCpu();
|
||||
config.LastFailedEngine = failedEngine;
|
||||
config.LastValidationError = "上一次推理验证未正常完成,已回退 CPU。";
|
||||
fallbackMessage = $"{failedEngine} 上一次推理验证未正常完成,本次已使用 CPU。";
|
||||
}
|
||||
// PendingRestart 在窗口加载前保持原样,真正开始验证时才记录 Validating。
|
||||
return new(fallbackMessage, isMainInstance);
|
||||
}
|
||||
|
||||
/// <summary>只准备设备与生效配置,不创建模型、运行推理或弹出提示。</summary>
|
||||
public Task InitializeAsync(CancellationToken token = default)
|
||||
{
|
||||
lock (_initializationLock) return _initializationTask ??= InitializeCoreAsync(token);
|
||||
}
|
||||
|
||||
private async Task InitializeCoreAsync(CancellationToken token)
|
||||
{
|
||||
if (IsReady) return;
|
||||
var config = Config;
|
||||
// LastValidationError 只用于设置页的历史详情,不能冒充本次启动的失败重新弹窗。
|
||||
if (loader.InferenceDevice != config.InferenceDevice)
|
||||
{
|
||||
FallBack(config.InferenceDevice, "运行库加载",
|
||||
string.IsNullOrWhiteSpace(loader.FailureReason)
|
||||
? "所选运行库无法加载或依赖不完整,请在硬件加速设置中重新检测并补齐依赖。"
|
||||
: loader.FailureReason,
|
||||
loader.StatusText);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
var selected = config.GetEngineSettings(config.InferenceDevice);
|
||||
var found = await Task.Run(() => devices.GetDevices(config.InferenceDevice, loader.RuntimeDirectory), token);
|
||||
var device = found.FirstOrDefault(d => d.Id == selected.DeviceId)
|
||||
?? throw new InvalidOperationException("保存的推理设备不可用,请重新选择设备。");
|
||||
var runtime = ResolvedInferenceRuntime.Resolve(config, device, loader.RuntimeDirectory);
|
||||
var isValidated = runtime.Engine == InferenceDeviceType.Cpu
|
||||
|| (config.ValidationState == InferenceValidationState.None && config.VerifiedSignature == runtime.Fingerprint);
|
||||
_startupRevision = Interlocked.Read(ref _settingsRevision);
|
||||
Volatile.Write(ref _published, new(runtime, isValidated));
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogWarning(e, "[ONNX]推理设备初始化失败,回退 CPU");
|
||||
var reason = e.Message.Contains("设备不可用", StringComparison.Ordinal)
|
||||
? e.Message
|
||||
: "无法初始化保存的推理设备,请在硬件加速设置中重新选择设备。";
|
||||
FallBack(config.InferenceDevice, "设备初始化", reason, e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>仅由主实例的 MainWindowViewModel.OnLoaded 调用;重复调用共用同一任务。</summary>
|
||||
public Task ValidatePendingAsync(CancellationToken token = default)
|
||||
{
|
||||
if (!IsMainInstance) return Task.CompletedTask;
|
||||
lock (_initializationLock) return _validationTask ??= ValidatePendingCoreAsync(token);
|
||||
}
|
||||
|
||||
private async Task ValidatePendingCoreAsync(CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
await InitializeAsync(linked.Token);
|
||||
var published = Published;
|
||||
if (published.IsValidated)
|
||||
{
|
||||
if (!HasPendingRestart && Config.ValidationState == InferenceValidationState.PendingRestart)
|
||||
{
|
||||
Config.ValidationState = InferenceValidationState.None;
|
||||
configService.Save();
|
||||
SettingsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
return;
|
||||
}
|
||||
var runtime = published.Runtime;
|
||||
bool ownsSavedSettings;
|
||||
lock (_settingsLock)
|
||||
{
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
if (ownsSavedSettings) Config.ValidationState = InferenceValidationState.Validating;
|
||||
}
|
||||
// 验证中的状态必须先落盘,原生调用异常中断后下一次启动才能安全回退。
|
||||
if (ownsSavedSettings) configService.Save();
|
||||
try
|
||||
{
|
||||
// 缺图不是引擎故障:古树场景仍待接入,先通过独立 OCR 会话验证引擎。
|
||||
var factory = new BgiOnnxSessionFactory(logger, runtime);
|
||||
if (diagnostics.HasDomainTreeImage)
|
||||
await diagnostics.ValidateTreeAsync(factory, linked.Token).ConfigureAwait(false);
|
||||
else
|
||||
await diagnostics.ValidateOcrAsync(factory, linked.Token).ConfigureAwait(false);
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
lock (_settingsLock)
|
||||
{
|
||||
Volatile.Write(ref _published, published with { IsValidated = true });
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
// 即使验证期间保存了其他引擎,也保留本次成功记录;不覆盖新的待重启设置。
|
||||
Config.RecordValidatedEngine(runtime.Engine);
|
||||
if (ownsSavedSettings)
|
||||
{
|
||||
Config.VerifiedSignature = runtime.Fingerprint;
|
||||
Config.ValidationState = InferenceValidationState.None;
|
||||
Config.LastFailedEngine = null;
|
||||
Config.LastValidationError = "";
|
||||
}
|
||||
}
|
||||
configService.Save();
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// 正常退出取消友好验证并不说明引擎不可用,保留待验证设置供下次主实例加载。
|
||||
lock (_settingsLock)
|
||||
{
|
||||
ownsSavedSettings = _settingsRevision == _startupRevision;
|
||||
if (ownsSavedSettings) Config.ValidationState = InferenceValidationState.PendingRestart;
|
||||
}
|
||||
if (ownsSavedSettings) configService.Save();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
logger.LogWarning(e, "[ONNX]主窗口推理验证失败,回退 CPU");
|
||||
var validationError = e as InferenceValidationException;
|
||||
FallBack(runtime.Engine,
|
||||
validationError?.Scene ?? "模型验证",
|
||||
validationError?.UserReason ?? "加载或运行验证模型时发生错误,详细错误已记录到硬件加速设置和日志中。",
|
||||
e.ToString(),
|
||||
_startupRevision);
|
||||
}
|
||||
finally { SettingsChanged?.Invoke(this, EventArgs.Empty); }
|
||||
}
|
||||
|
||||
private void FallBack(InferenceDeviceType engine, string stage, string userReason, string technicalDetails,
|
||||
long? validationRevision = null)
|
||||
{
|
||||
lock (_settingsLock)
|
||||
{
|
||||
// 非主实例只能回退本进程的运行时快照,不能改写主实例共享的持久化设置。
|
||||
if (IsMainInstance)
|
||||
{
|
||||
// 验证期间用户可能已保存新的设置,旧验证结果不能覆盖下一次启动的选择。
|
||||
if (validationRevision == null || _settingsRevision == validationRevision)
|
||||
{
|
||||
Config.SwitchToCpu();
|
||||
}
|
||||
Config.LastFailedEngine = engine;
|
||||
}
|
||||
if (IsMainInstance)
|
||||
Config.LastValidationError = $"失败环节:{stage}\r\n失败原因:{userReason}\r\n\r\n技术详情:{technicalDetails}";
|
||||
StartupMessage = $"{engine} 加速验证失败,已自动切换为 CPU。\r\n\r\n" +
|
||||
$"失败环节:{stage}\r\n失败原因:{userReason}\r\n\r\n" +
|
||||
"软件仍可正常使用。你可以继续使用 CPU,或在首页的“硬件加速设置”中选择其他设备后重试。";
|
||||
var cpu = ResolvedInferenceRuntime.Cpu(Config.Cpu.CpuThreads, Config.PaddleOcrCpu.ToOptions(),
|
||||
loader.RuntimeDirectory);
|
||||
Volatile.Write(ref _published, new(cpu, true));
|
||||
}
|
||||
if (IsMainInstance) configService.Save();
|
||||
}
|
||||
|
||||
public void Apply(InferenceDeviceType engine, InferenceEngineSettings settings, bool cpuOcr, int cpuThreads,
|
||||
PaddleOcrCpuOptions? paddleOcrCpu = null)
|
||||
{
|
||||
if (!Enum.IsDefined(engine) || string.IsNullOrWhiteSpace(settings.DeviceId) || cpuThreads < 0 || cpuThreads > Environment.ProcessorCount)
|
||||
throw new ArgumentException("推理设置不符合预期。");
|
||||
if (paddleOcrCpu is { IsValid: false }) throw new ArgumentException("OCR CPU 线程策略参数不符合预期。");
|
||||
// TensorRT 已下线:任何调用方都不能再把生效引擎切回该引擎。
|
||||
if (!engine.IsSelectable()) throw new ArgumentException($"{engine} 推理引擎已停止提供,请选择其他引擎。");
|
||||
lock (_settingsLock)
|
||||
{
|
||||
_settingsRevision++;
|
||||
var config = Config;
|
||||
var target = config.GetEngineSettings(engine);
|
||||
target.DeviceId = settings.DeviceId;
|
||||
target.EnableModelCache = settings.EnableModelCache;
|
||||
config.Cpu.CpuThreads = cpuThreads;
|
||||
if (paddleOcrCpu != null) config.PaddleOcrCpu = PaddleOcrCpuConfig.FromOptions(paddleOcrCpu);
|
||||
config.CpuOcr = cpuOcr;
|
||||
config.InferenceDevice = engine;
|
||||
config.FormatVersion = 1;
|
||||
config.ValidationState = InferenceValidationState.PendingRestart;
|
||||
}
|
||||
configService.Save();
|
||||
SettingsChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
Task? validation;
|
||||
lock (_initializationLock) validation = _validationTask;
|
||||
if (validation != null) await validation;
|
||||
}
|
||||
|
||||
public void Dispose() => _lifetime.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Security.Cryptography;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public interface IOnnxRuntimeInstaller
|
||||
{
|
||||
string PluginsDirectory { get; }
|
||||
RuntimeInstallation Inspect(InferenceDeviceType engine);
|
||||
Task<IReadOnlyList<RuntimeDownloadPackage>> GetDownloadPlanAsync(InferenceDeviceType engine, bool dependencies, CancellationToken token);
|
||||
Task InstallAsync(InferenceDeviceType engine, IReadOnlyList<RuntimeDownloadPackage> packages, IProgress<RuntimeDownloadProgress>? progress, CancellationToken token);
|
||||
Task CleanupInstalledDownloadsAsync(CancellationToken token);
|
||||
}
|
||||
|
||||
public sealed class OnnxRuntimeInstaller : IOnnxRuntimeInstaller, IDisposable
|
||||
{
|
||||
private readonly HttpClient _client;
|
||||
private readonly bool _ownsClient;
|
||||
private readonly SemaphoreSlim _installationLock = new(1, 1);
|
||||
private readonly CancellationTokenSource _lifetime = new();
|
||||
public string BaseDirectory { get; }
|
||||
public string PluginsDirectory => Path.Combine(BaseDirectory, "Plugins", "OnnxRuntime");
|
||||
|
||||
public OnnxRuntimeInstaller(string baseDirectory, HttpClient? client = null)
|
||||
{
|
||||
BaseDirectory = Path.GetFullPath(baseDirectory);
|
||||
_ownsClient = client == null;
|
||||
_client = client ?? new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }) { Timeout = Timeout.InfiniteTimeSpan };
|
||||
}
|
||||
|
||||
public RuntimeInstallation Inspect(InferenceDeviceType engine) => OnnxRuntimePackageCatalog.Inspect(BaseDirectory, engine);
|
||||
|
||||
public async Task<IReadOnlyList<RuntimeDownloadPackage>> GetDownloadPlanAsync(InferenceDeviceType engine,
|
||||
bool dependencies, CancellationToken token)
|
||||
{
|
||||
if (engine == InferenceDeviceType.Cpu) return [];
|
||||
if (!dependencies)
|
||||
{
|
||||
var id = engine switch
|
||||
{
|
||||
InferenceDeviceType.DirectML => "Microsoft.ML.OnnxRuntime.DirectML",
|
||||
InferenceDeviceType.OpenVINO => "Intel.ML.OnnxRuntime.OpenVino",
|
||||
_ => "Microsoft.ML.OnnxRuntime.Gpu.Windows"
|
||||
};
|
||||
var packages = new List<RuntimeDownloadPackage> { await GetNugetPackageAsync(id, OnnxRuntimeLoader.RequiredVersion, token) };
|
||||
if (engine == InferenceDeviceType.DirectML) packages.Add(await GetNugetPackageAsync("Microsoft.AI.DirectML", "1.15.4", token));
|
||||
return packages;
|
||||
}
|
||||
if (engine != InferenceDeviceType.CUDA && engine != InferenceDeviceType.TensorRT) return [];
|
||||
var directory = Inspect(engine).Directory;
|
||||
bool Missing(string prefix) => OnnxRuntimePackageCatalog.DependencyFiles(engine)
|
||||
.Where(file => file.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)).Any(file => !File.Exists(Path.Combine(directory, file)));
|
||||
var result = new List<RuntimeDownloadPackage>();
|
||||
var cuda = await ReadJsonAsync("https://developer.download.nvidia.com/compute/cuda/redist/redistrib_12.8.0.json", token);
|
||||
foreach (var (component, prefix) in new[] { ("cuda_cudart", "cudart"), ("libcublas", "cublas"), ("cuda_nvrtc", "nvrtc"), ("libcufft", "cufft"), ("libcurand", "curand") })
|
||||
{
|
||||
if (!Missing(prefix)) continue;
|
||||
var entry = cuda[component]!;
|
||||
result.Add(GetNvidiaPackage("cuda", component, entry.Value<string>("version")!, entry["windows-x86_64"]!));
|
||||
}
|
||||
if (Missing("cudnn"))
|
||||
{
|
||||
var cudnn = await ReadJsonAsync("https://developer.download.nvidia.com/compute/cudnn/redist/redistrib_9.8.0.json", token);
|
||||
var entry = cudnn["cudnn"]!;
|
||||
result.Add(GetNvidiaPackage("cudnn", "cuDNN", entry.Value<string>("version")!, entry["windows-x86_64"]!["cuda12"]!));
|
||||
}
|
||||
if (engine == InferenceDeviceType.TensorRT && (Missing("nvinfer") || Missing("nvonnxparser")))
|
||||
result.Add(new("TensorRT 10.8.0.43", new(OnnxRuntimePackageCatalog.TensorRtUrl), 1844107899, 2_507_893_528, null, "SHA256"));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task InstallAsync(InferenceDeviceType engine, IReadOnlyList<RuntimeDownloadPackage> packages,
|
||||
IProgress<RuntimeDownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
if (packages.Count == 0) return;
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
token = linked.Token;
|
||||
await _installationLock.WaitAsync(token);
|
||||
var root = OnnxRuntimePackageCatalog.EngineDirectory(PluginsDirectory, engine);
|
||||
// 临时目录只用于保证下载和解压完整,安装后仍只有引擎的固定目录。
|
||||
var staging = Path.Combine(PluginsDirectory, $".{engine}.staging-{Guid.NewGuid():N}");
|
||||
var backup = Path.Combine(PluginsDirectory, $".{engine}.backup-{Guid.NewGuid():N}");
|
||||
var completedArchives = new List<string>();
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(PluginsDirectory);
|
||||
var required = packages.Sum(p => p.DownloadBytes + p.InstalledBytes);
|
||||
var disk = new DriveInfo(Path.GetPathRoot(root)!);
|
||||
if (disk.AvailableFreeSpace < required) throw new IOException($"磁盘空间不足,预计需要 {required / 1073741824d:F1} GB。");
|
||||
Directory.CreateDirectory(staging);
|
||||
var existing = Inspect(engine).Directory;
|
||||
if (Directory.Exists(existing))
|
||||
foreach (var file in Directory.EnumerateFiles(existing))
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (Path.GetExtension(file).Equals(".dll", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(file).Equals(".xml", StringComparison.OrdinalIgnoreCase))
|
||||
File.Copy(file, Path.Combine(staging, Path.GetFileName(file)), true);
|
||||
}
|
||||
var downloader = new RuntimePackageDownloader(_client);
|
||||
foreach (var package in packages)
|
||||
{
|
||||
var archive = await downloader.DownloadAsync(package, Path.Combine(PluginsDirectory, ".downloads"), progress, token);
|
||||
completedArchives.Add(archive);
|
||||
progress?.Report(new($"正在解压并校验 {package.Name}", 0, 0));
|
||||
try { await RuntimePackageDownloader.ExtractAsync(archive, staging, path => IncludeFile(engine, package, path), token); }
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// 包文件损坏后不能反复复用同一个下载缓存。
|
||||
File.Delete(archive);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
foreach (var file in OnnxRuntimePackageCatalog.ProviderFiles(engine))
|
||||
if (!File.Exists(Path.Combine(staging, file))) throw new InvalidDataException($"安装包缺少 {file}。");
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// 最终目录名保持不变。先把旧目录改名为备份,再提交暂存目录;提交失败时恢复旧目录。
|
||||
// 若文件被当前进程加载,由 IO 异常提示用户重启后重试。
|
||||
CommitRuntimeDirectory(staging, root, backup);
|
||||
// 完整安装后再清理完整包;取消或失败时保留缓存供重试、续传。
|
||||
foreach (var archive in completedArchives) TryDeleteDownload(archive);
|
||||
TryRemoveEmptyDownloadDirectory();
|
||||
progress?.Report(new("下载完成,已重新识别运行库;应用设置后重启验证。", 1, 1));
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
// 包内容损坏或文件清单不完整时不保留缓存,避免下次继续复用错误包。
|
||||
foreach (var archive in completedArchives) TryDeleteDownload(archive);
|
||||
TryRemoveEmptyDownloadDirectory();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 只删除本次安装的暂存目录。回滚失败时保留备份目录,避免再次破坏可恢复内容。
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(staging) && IsDirectChildOf(staging, PluginsDirectory))
|
||||
Directory.Delete(staging, true);
|
||||
}
|
||||
finally { _installationLock.Release(); }
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CleanupInstalledDownloadsAsync(CancellationToken token)
|
||||
{
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
await _installationLock.WaitAsync(linked.Token);
|
||||
try
|
||||
{
|
||||
foreach (var engine in Enum.GetValues<InferenceDeviceType>().Where(engine => engine != InferenceDeviceType.Cpu))
|
||||
{
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
CleanupAbandonedInstallationDirectories(engine);
|
||||
}
|
||||
|
||||
var cache = Path.Combine(PluginsDirectory, ".downloads");
|
||||
if (Directory.Exists(cache))
|
||||
{
|
||||
foreach (var path in Directory.EnumerateFiles(cache, "*.zip"))
|
||||
{
|
||||
linked.Token.ThrowIfCancellationRequested();
|
||||
// 兼容之前留下的已安装下载包,只清理与当前安装内容完全一致的包。
|
||||
var key = Path.GetFileNameWithoutExtension(path);
|
||||
if (key.Length != 64 || !key.All(Uri.IsHexDigit)) continue;
|
||||
try
|
||||
{
|
||||
if (await MatchesInstalledFilesAsync(path, linked.Token)) TryDeleteDownload(path);
|
||||
}
|
||||
catch (InvalidDataException) { /* 无法识别的包交由下载校验处理。 */ }
|
||||
catch (IOException) { /* 文件被占用时保留,下次刷新再清理。 */ }
|
||||
catch (UnauthorizedAccessException) { /* 缓存清理不能阻止设备识别。 */ }
|
||||
}
|
||||
}
|
||||
TryRemoveEmptyDownloadDirectory();
|
||||
}
|
||||
finally { _installationLock.Release(); }
|
||||
}
|
||||
|
||||
private void CleanupAbandonedInstallationDirectories(InferenceDeviceType engine)
|
||||
{
|
||||
if (!Directory.Exists(PluginsDirectory)) return;
|
||||
foreach (var directory in Directory.EnumerateDirectories(PluginsDirectory, $".{engine}.staging-*"))
|
||||
{
|
||||
try { if (IsDirectChildOf(directory, PluginsDirectory)) Directory.Delete(directory, true); }
|
||||
catch (IOException) { /* 清理失败不能影响当前安装。 */ }
|
||||
catch (UnauthorizedAccessException) { /* 清理失败不能影响当前安装。 */ }
|
||||
}
|
||||
// 固定目录存在时,备份已经不再承担回滚职责;无法删除则留待下次刷新。
|
||||
var root = OnnxRuntimePackageCatalog.EngineDirectory(PluginsDirectory, engine);
|
||||
if (!Directory.Exists(root)) return;
|
||||
foreach (var directory in Directory.EnumerateDirectories(PluginsDirectory, $".{engine}.backup-*"))
|
||||
{
|
||||
try { if (IsDirectChildOf(directory, PluginsDirectory)) Directory.Delete(directory, true); }
|
||||
catch (IOException) { /* 清理失败不能影响当前安装。 */ }
|
||||
catch (UnauthorizedAccessException) { /* 清理失败不能影响当前安装。 */ }
|
||||
}
|
||||
}
|
||||
|
||||
private static void CommitRuntimeDirectory(string staging, string root, string backup)
|
||||
{
|
||||
var originalMoved = false;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(root))
|
||||
{
|
||||
Directory.Move(root, backup);
|
||||
originalMoved = true;
|
||||
}
|
||||
Directory.Move(staging, root);
|
||||
}
|
||||
catch (Exception commitError) when (commitError is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
if (!originalMoved) throw;
|
||||
try
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, true);
|
||||
if (Directory.Exists(backup)) Directory.Move(backup, root);
|
||||
}
|
||||
catch (Exception rollbackError) when (rollbackError is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
throw new IOException($"运行库提交和回滚均失败,旧运行库备份保留在:{backup}",
|
||||
new AggregateException(commitError, rollbackError));
|
||||
}
|
||||
throw;
|
||||
}
|
||||
|
||||
if (!originalMoved) return;
|
||||
try { Directory.Delete(backup, true); }
|
||||
catch (IOException) { /* 旧运行库可能仍被其他进程占用,留待下次刷新清理。 */ }
|
||||
catch (UnauthorizedAccessException) { /* 新目录已经提交,备份留待下次刷新清理。 */ }
|
||||
}
|
||||
|
||||
private static bool IsDirectChildOf(string path, string parent)
|
||||
=> string.Equals(Path.GetDirectoryName(Path.GetFullPath(path)), Path.GetFullPath(parent),
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private async Task<bool> MatchesInstalledFilesAsync(string path, CancellationToken token)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(path);
|
||||
var nuget = new RuntimeDownloadPackage("cache", new Uri("https://api.nuget.org/"), 0, 0, null, "SHA256", "cache");
|
||||
foreach (var engine in Enum.GetValues<InferenceDeviceType>().Where(e => e != InferenceDeviceType.Cpu))
|
||||
{
|
||||
var directory = Inspect(engine).Directory;
|
||||
var entries = archive.Entries.Where(e => IncludeFile(engine, nuget, e.FullName.Replace('\\', '/'))).ToArray();
|
||||
if (entries.Length == 0) continue;
|
||||
var matched = true;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var file = Path.Combine(directory, Path.GetFileName(entry.FullName));
|
||||
if (!File.Exists(file) || new FileInfo(file).Length != entry.Length) { matched = false; break; }
|
||||
await using var input = entry.Open();
|
||||
await using var installed = File.OpenRead(file);
|
||||
var downloadedHash = await SHA256.HashDataAsync(input, token);
|
||||
var installedHash = await SHA256.HashDataAsync(installed, token);
|
||||
if (!CryptographicOperations.FixedTimeEquals(downloadedHash, installedHash))
|
||||
{ matched = false; break; }
|
||||
}
|
||||
if (matched) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void TryDeleteDownload(string path)
|
||||
{
|
||||
// 校验绝对路径后,仅删除下载缓存中的单个归档,不触及运行库目录或续传文件。
|
||||
var cache = Path.GetFullPath(Path.Combine(PluginsDirectory, ".downloads"));
|
||||
if (!string.Equals(Path.GetDirectoryName(Path.GetFullPath(path)), cache, StringComparison.OrdinalIgnoreCase)) return;
|
||||
try { File.Delete(path); }
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
private void TryRemoveEmptyDownloadDirectory()
|
||||
{
|
||||
var cache = Path.GetFullPath(Path.Combine(PluginsDirectory, ".downloads"));
|
||||
if (!cache.StartsWith(Path.GetFullPath(PluginsDirectory) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) return;
|
||||
try { if (Directory.Exists(cache) && !Directory.EnumerateFileSystemEntries(cache).Any()) Directory.Delete(cache); }
|
||||
catch (IOException) { }
|
||||
catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
private static bool IncludeFile(InferenceDeviceType engine, RuntimeDownloadPackage package, string path)
|
||||
{
|
||||
var name = Path.GetFileName(path);
|
||||
if (package.NugetId == "Microsoft.AI.DirectML") return path.Contains("x64", StringComparison.OrdinalIgnoreCase) && name.Equals("DirectML.dll", StringComparison.OrdinalIgnoreCase);
|
||||
if (package.NugetId != null)
|
||||
{
|
||||
if (!path.StartsWith("runtimes/win-x64/native/", StringComparison.OrdinalIgnoreCase)) return false;
|
||||
if (engine == InferenceDeviceType.OpenVINO) return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".xml", StringComparison.OrdinalIgnoreCase);
|
||||
return OnnxRuntimePackageCatalog.ProviderFiles(engine).Contains(name, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
return path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && (path.Contains("/bin/", StringComparison.OrdinalIgnoreCase) || path.Contains("/lib/", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private async Task<RuntimeDownloadPackage> GetNugetPackageAsync(string id, string version, CancellationToken token)
|
||||
{
|
||||
var lower = id.ToLowerInvariant();
|
||||
var registration = await ReadJsonAsync($"https://api.nuget.org/v3/registration5-gz-semver2/{lower}/{version}.json", token);
|
||||
var catalogUrl = new Uri(registration.Value<string>("catalogEntry")!);
|
||||
if (catalogUrl.Scheme != "https" || catalogUrl.Host != "api.nuget.org") throw new InvalidDataException("NuGet 元数据地址无效。");
|
||||
var catalog = await ReadJsonAsync(catalogUrl.AbsoluteUri, token);
|
||||
var entry = catalog;
|
||||
var size = entry.Value<long>("packageSize");
|
||||
var algorithm = entry.Value<string>("packageHashAlgorithm")!;
|
||||
if (algorithm != "SHA512") throw new InvalidDataException("NuGet 包摘要算法不符合预期。");
|
||||
return new($"{id} {version}", new($"https://api.nuget.org/v3-flatcontainer/{lower}/{version}/{lower}.{version}.nupkg"), size, size * 4,
|
||||
entry.Value<string>("packageHash"), algorithm, id);
|
||||
}
|
||||
|
||||
private static RuntimeDownloadPackage GetNvidiaPackage(string product, string component, string version, JToken entry)
|
||||
{
|
||||
var size = long.Parse(entry["size"]!.ToString(), System.Globalization.CultureInfo.InvariantCulture);
|
||||
var url = new Uri($"https://developer.download.nvidia.com/compute/{product}/redist/{entry.Value<string>("relative_path")}");
|
||||
if (url.Host != "developer.download.nvidia.com" || url.Scheme != "https") throw new InvalidDataException("NVIDIA 下载地址无效。");
|
||||
return new($"{component} {version}", url, size, size * 4, entry.Value<string>("sha256"), "SHA256");
|
||||
}
|
||||
|
||||
private async Task<JObject> ReadJsonAsync(string url, CancellationToken token)
|
||||
{
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token, _lifetime.Token);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
using var response = await _client.GetAsync(url, timeout.Token);
|
||||
response.EnsureSuccessStatusCode();
|
||||
return JObject.Parse(await response.Content.ReadAsStringAsync(timeout.Token));
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
_lifetime.Cancel();
|
||||
await _installationLock.WaitAsync();
|
||||
_installationLock.Release();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_ownsClient) _client.Dispose();
|
||||
_lifetime.Dispose();
|
||||
_installationLock.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Serilog;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>
|
||||
/// 主程序按推理类型选定原生运行库,在任何 ONNX 原生调用之前创建一次。
|
||||
/// 运行中的进程不切换、不卸载已选中的运行库。
|
||||
/// </summary>
|
||||
public interface IOnnxRuntimeSelection
|
||||
{
|
||||
InferenceDeviceType InferenceDevice { get; }
|
||||
string RuntimeDirectory { get; }
|
||||
string StatusText { get; }
|
||||
string FailureReason { get; }
|
||||
}
|
||||
|
||||
public sealed class OnnxRuntimeLoader : IOnnxRuntimeSelection
|
||||
{
|
||||
// 原生库必须与编译时引用的托管 ONNX Runtime 主次修订版一致,不再另外维护版本号。
|
||||
public static string RequiredVersion { get; } = GetRequiredVersion();
|
||||
private IntPtr _libraryHandle;
|
||||
private readonly Func<string, IntPtr> _loadLibrary;
|
||||
private readonly Func<IntPtr, string> _readRuntimeVersion;
|
||||
private readonly Action<IntPtr> _freeLibrary;
|
||||
|
||||
public string PluginsDirectory { get; }
|
||||
public string RuntimeDirectory { get; private set; }
|
||||
public InferenceDeviceType InferenceDevice { get; private set; }
|
||||
public string StatusText { get; private set; } = "内置 DirectML / CPU";
|
||||
public string FailureReason { get; private set; } = "";
|
||||
|
||||
public OnnxRuntimeLoader(HardwareAccelerationConfig config, string baseDirectory)
|
||||
: this(config, baseDirectory,
|
||||
path => LoadLibraryEx(path, IntPtr.Zero, 0x00000008), // LOAD_WITH_ALTERED_SEARCH_PATH
|
||||
ReadRuntimeVersion, NativeLibrary.Free)
|
||||
{
|
||||
}
|
||||
|
||||
internal OnnxRuntimeLoader(HardwareAccelerationConfig config, string baseDirectory,
|
||||
Func<string, IntPtr> loadLibrary, Func<IntPtr, string> readRuntimeVersion, Action<IntPtr> freeLibrary)
|
||||
{
|
||||
_loadLibrary = loadLibrary;
|
||||
_readRuntimeVersion = readRuntimeVersion;
|
||||
_freeLibrary = freeLibrary;
|
||||
PluginsDirectory = Path.Combine(Path.GetFullPath(baseDirectory), "Plugins", "OnnxRuntime");
|
||||
RuntimeDirectory = Path.GetFullPath(baseDirectory);
|
||||
InferenceDevice = config.InferenceDevice;
|
||||
var directoryName = InferenceDevice switch
|
||||
{
|
||||
InferenceDeviceType.DirectML or InferenceDeviceType.OpenVINO or
|
||||
InferenceDeviceType.CUDA or InferenceDeviceType.TensorRT => InferenceDevice.ToString(),
|
||||
_ => null
|
||||
};
|
||||
if (directoryName is null)
|
||||
{
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
return;
|
||||
}
|
||||
|
||||
var directory = OnnxRuntimePackageCatalog.RuntimeDirectory(PluginsDirectory, InferenceDevice);
|
||||
var libraryPath = Path.Combine(directory, "onnxruntime.dll");
|
||||
// DirectML 已随主程序提供,固定目录中的运行库仅用于可选替换。
|
||||
if (InferenceDevice == InferenceDeviceType.DirectML && !File.Exists(libraryPath)) return;
|
||||
|
||||
var previousPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process);
|
||||
string version = "";
|
||||
var versionMismatch = false;
|
||||
var deleteInvalidPlugin = false;
|
||||
try
|
||||
{
|
||||
var missingRuntimeFiles = OnnxRuntimePackageCatalog.ProviderFiles(InferenceDevice)
|
||||
.Where(file => !File.Exists(Path.Combine(directory, file)))
|
||||
.ToArray();
|
||||
if (missingRuntimeFiles.Length > 0)
|
||||
{
|
||||
deleteInvalidPlugin = Directory.Exists(directory);
|
||||
FailureReason = $"{directoryName} 运行库不完整,缺少 {string.Join("、", missingRuntimeFiles)}。请在硬件加速设置中重新下载运行库。";
|
||||
throw new FileNotFoundException($"运行库目录中缺少 {string.Join("、", missingRuntimeFiles)}。",
|
||||
Path.Combine(directory, missingRuntimeFiles[0]));
|
||||
}
|
||||
|
||||
// 只加入选中运行库的目录,不扫描加载其他目录中的 DLL。PATH 仅修改当前进程,
|
||||
// 也供 ONNX 原生代码随后加载 provider 的间接依赖使用。
|
||||
// 不从其他引擎安装目录借用同名依赖。CUDA 和 TensorRT 保持独立。
|
||||
var searchPaths = new[] { directory, previousPath ?? "" }
|
||||
.SelectMany(path => path.Split(Path.PathSeparator,
|
||||
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
|
||||
.Where(path => !path.StartsWith(PluginsDirectory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) || path.Equals(directory, StringComparison.OrdinalIgnoreCase))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase);
|
||||
Environment.SetEnvironmentVariable("PATH", string.Join(Path.PathSeparator, searchPaths),
|
||||
EnvironmentVariableTarget.Process);
|
||||
|
||||
// 与 ONNX Runtime 的 Windows provider 加载方式保持一致,使主 DLL 的同目录依赖优先加载。
|
||||
deleteInvalidPlugin = true;
|
||||
_libraryHandle = _loadLibrary(libraryPath);
|
||||
if (_libraryHandle == IntPtr.Zero)
|
||||
throw new Win32Exception(Marshal.GetLastWin32Error(), $"无法加载 {libraryPath},请检查架构及配套依赖。");
|
||||
|
||||
// 先直接读取稳定的 OrtApiBase 版本接口,不触发托管 NativeMethods 的静态初始化;
|
||||
// 版本不符时仍能释放失败的模块并回退到内置运行库。
|
||||
version = _readRuntimeVersion(_libraryHandle);
|
||||
if (version != RequiredVersion)
|
||||
{
|
||||
versionMismatch = true;
|
||||
throw new InvalidDataException($"原生运行库版本为 {version},必须为 {RequiredVersion}。");
|
||||
}
|
||||
|
||||
var missingDependencies = OnnxRuntimePackageCatalog.MissingDependencyFiles(InferenceDevice, directory);
|
||||
if (missingDependencies.Length > 0)
|
||||
{
|
||||
FailureReason = OnnxRuntimePackageCatalog.DescribeMissingDependencies(InferenceDevice, missingDependencies);
|
||||
throw new FileNotFoundException($"依赖不完整:缺少 {string.Join("、", missingDependencies)}。",
|
||||
Path.Combine(directory, missingDependencies[0]));
|
||||
}
|
||||
|
||||
NativeLibrary.SetDllImportResolver(typeof(InferenceSession).Assembly,
|
||||
(name, _, _) => name == "onnxruntime" ? _libraryHandle : IntPtr.Zero);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (_libraryHandle != IntPtr.Zero)
|
||||
{
|
||||
_freeLibrary(_libraryHandle);
|
||||
_libraryHandle = IntPtr.Zero;
|
||||
}
|
||||
|
||||
Environment.SetEnvironmentVariable("PATH", previousPath, EnvironmentVariableTarget.Process);
|
||||
if (versionMismatch)
|
||||
{
|
||||
var deleted = TryDeletePlugin(directory);
|
||||
FailureReason = $"{directoryName} 运行库版本为 {version},与当前程序编译使用的 ONNX Runtime {RequiredVersion} 不一致。" +
|
||||
(deleted
|
||||
? "已自动删除该插件并恢复默认 CPU 设置,如需继续使用请重新下载。"
|
||||
: "插件可能正被其他进程占用,无法自动删除;已恢复默认 CPU 设置,请关闭其他实例后手动删除。");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(FailureReason))
|
||||
FailureReason = $"{directoryName} 运行库无法加载,请在硬件加速设置中重新下载。";
|
||||
if (deleteInvalidPlugin)
|
||||
FailureReason += TryDeletePlugin(directory)
|
||||
? "已自动删除不完整或无法使用的插件,并恢复默认 CPU 设置。"
|
||||
: "插件可能正被其他进程占用,无法自动删除;已恢复默认 CPU 设置。";
|
||||
}
|
||||
InferenceDevice = InferenceDeviceType.Cpu;
|
||||
StatusText = $"内置运行库(CPU);{directoryName} 加载失败:{e.Message}";
|
||||
Log.Warning(e, "[ONNX]运行库 {Library} 加载失败,回退到 CPU", libraryPath);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解析器注册后,日志或状态更新异常也不能再卸载已对托管绑定公开的模块。
|
||||
RuntimeDirectory = directory;
|
||||
StatusText = $"{directoryName}(ONNX Runtime {version})";
|
||||
Log.Information("[ONNX]已加载运行库 {Library},版本 {Version}", libraryPath, version);
|
||||
// 句柄由本进程持有至退出。推理会话、OrtEnv 和托管静态函数指针仍可能引用它,
|
||||
// 不能在服务 Dispose 或设置页关闭时 Free,否则会产生悬空函数指针。
|
||||
}
|
||||
|
||||
private static string ReadRuntimeVersion(IntPtr libraryHandle)
|
||||
{
|
||||
var getApiBase = Marshal.GetDelegateForFunctionPointer<OrtGetApiBase>(
|
||||
NativeLibrary.GetExport(libraryHandle, "OrtGetApiBase"));
|
||||
var apiBase = getApiBase();
|
||||
if (apiBase == IntPtr.Zero) throw new InvalidDataException("原生运行库未提供 OrtApiBase。");
|
||||
|
||||
// OrtApiBase 依次包含 GetApi 和 GetVersionString 两个函数指针。
|
||||
var getVersion = Marshal.GetDelegateForFunctionPointer<OrtGetVersionString>(Marshal.ReadIntPtr(apiBase, IntPtr.Size));
|
||||
return Marshal.PtrToStringUTF8(getVersion()) ?? throw new InvalidDataException("无法读取原生运行库版本。");
|
||||
}
|
||||
|
||||
private static string GetRequiredVersion()
|
||||
{
|
||||
var version = typeof(InferenceSession).Assembly.GetName().Version
|
||||
?? throw new InvalidOperationException("无法读取编译时 ONNX Runtime 版本。");
|
||||
return version.ToString(3);
|
||||
}
|
||||
|
||||
private bool TryDeletePlugin(string directory)
|
||||
{
|
||||
var expected = Path.GetFullPath(OnnxRuntimePackageCatalog.EngineDirectory(PluginsDirectory, InferenceDevice));
|
||||
if (!string.Equals(Path.GetFullPath(directory), expected, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
try
|
||||
{
|
||||
Directory.Delete(expected, true);
|
||||
return !Directory.Exists(expected);
|
||||
}
|
||||
catch (IOException) { return false; }
|
||||
catch (UnauthorizedAccessException) { return false; }
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
|
||||
private delegate IntPtr OrtGetApiBase();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
|
||||
private delegate IntPtr OrtGetVersionString();
|
||||
|
||||
[DllImport("kernel32.dll", EntryPoint = "LoadLibraryExW", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr LoadLibraryEx(string libraryPath, IntPtr file, uint flags);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public sealed record RuntimeInstallation(InferenceInstallationState State, string Directory, string Description);
|
||||
public sealed record RuntimeDownloadPackage(string Name, Uri Url, long DownloadBytes, long InstalledBytes,
|
||||
string? Hash, string HashAlgorithm, string? NugetId = null);
|
||||
public sealed record RuntimeDownloadProgress(string Message, long Received, long Total)
|
||||
{
|
||||
public double Percentage => Total > 0 ? Math.Clamp(100d * Received / Total, 0, 100) : 0;
|
||||
}
|
||||
|
||||
/// <summary>固定的运行库依赖清单,CUDA/TRT 目录、安装状态和搜索路径完全独立。</summary>
|
||||
public static class OnnxRuntimePackageCatalog
|
||||
{
|
||||
public const string TensorRtUrl = "https://developer.download.nvidia.com/compute/machine-learning/tensorrt/10.8.0/zip/TensorRT-10.8.0.43.Windows.win10.cuda-12.8.zip";
|
||||
|
||||
public static string EngineDirectory(string pluginsDirectory, InferenceDeviceType engine) => Path.Combine(pluginsDirectory, engine.ToString());
|
||||
|
||||
// 每个引擎只使用一个固定目录,用户手工复制 DLL 后即可直接被识别。
|
||||
public static string RuntimeDirectory(string pluginsDirectory, InferenceDeviceType engine)
|
||||
=> EngineDirectory(pluginsDirectory, engine);
|
||||
|
||||
public static string[] ProviderFiles(InferenceDeviceType engine) => engine switch
|
||||
{
|
||||
InferenceDeviceType.CUDA => ["onnxruntime.dll", "onnxruntime_providers_shared.dll", "onnxruntime_providers_cuda.dll"],
|
||||
// ORT 的 TensorRT provider 通过 CUDA provider bridge 取得 GPU 基础设施;这里只部署 DLL,不会把 CUDA EP 加入会话。
|
||||
InferenceDeviceType.TensorRT => ["onnxruntime.dll", "onnxruntime_providers_shared.dll", "onnxruntime_providers_cuda.dll", "onnxruntime_providers_tensorrt.dll"],
|
||||
InferenceDeviceType.OpenVINO => ["onnxruntime.dll", "onnxruntime_providers_shared.dll", "onnxruntime_providers_openvino.dll", "openvino.dll", "openvino_c.dll", "tbb12.dll", "openvino_intel_cpu_plugin.dll"],
|
||||
InferenceDeviceType.DirectML => ["onnxruntime.dll", "DirectML.dll"],
|
||||
_ => []
|
||||
};
|
||||
|
||||
public static string[] DependencyFiles(InferenceDeviceType engine) => engine switch
|
||||
{
|
||||
InferenceDeviceType.CUDA => ["cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll", "cufft64_11.dll", "curand64_10.dll", "cudnn64_9.dll", "cudnn_ops64_9.dll", "cudnn_cnn64_9.dll", "cudnn_adv64_9.dll", "cudnn_graph64_9.dll", "cudnn_heuristic64_9.dll", "cudnn_engines_precompiled64_9.dll", "cudnn_engines_runtime_compiled64_9.dll", "nvrtc64_120_0.dll", "nvrtc-builtins64_128.dll"],
|
||||
// TensorRT 目录独立携带 CUDA provider bridge 的全部本机依赖;执行 provider 链仍然只有 TensorRT + CPU。
|
||||
InferenceDeviceType.TensorRT => ["cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll", "cufft64_11.dll", "curand64_10.dll", "cudnn64_9.dll", "cudnn_ops64_9.dll", "cudnn_cnn64_9.dll", "cudnn_adv64_9.dll", "cudnn_graph64_9.dll", "cudnn_heuristic64_9.dll", "cudnn_engines_precompiled64_9.dll", "cudnn_engines_runtime_compiled64_9.dll", "nvrtc64_120_0.dll", "nvrtc-builtins64_128.dll", "nvinfer_10.dll", "nvinfer_plugin_10.dll", "nvonnxparser_10.dll", "nvinfer_builder_resource_10.dll"],
|
||||
_ => []
|
||||
};
|
||||
|
||||
public static string[] MissingDependencyFiles(InferenceDeviceType engine, string directory)
|
||||
=> Array.FindAll(DependencyFiles(engine), file => !File.Exists(Path.Combine(directory, file)));
|
||||
|
||||
public static string DescribeMissingDependencies(InferenceDeviceType engine, IReadOnlyCollection<string> missing)
|
||||
{
|
||||
var components = new List<string>();
|
||||
if (missing.Any(file => file.StartsWith("cudart", StringComparison.OrdinalIgnoreCase))) components.Add("CUDA Runtime");
|
||||
if (missing.Any(file => file.StartsWith("cublas", StringComparison.OrdinalIgnoreCase))) components.Add("cuBLAS");
|
||||
if (missing.Any(file => file.StartsWith("cudnn", StringComparison.OrdinalIgnoreCase))) components.Add("cuDNN");
|
||||
if (missing.Any(file => file.StartsWith("nvrtc", StringComparison.OrdinalIgnoreCase))) components.Add("CUDA NVRTC");
|
||||
if (missing.Any(file => file.StartsWith("cufft", StringComparison.OrdinalIgnoreCase))) components.Add("cuFFT");
|
||||
if (missing.Any(file => file.StartsWith("curand", StringComparison.OrdinalIgnoreCase))) components.Add("cuRAND");
|
||||
if (missing.Any(file => file.StartsWith("nvinfer", StringComparison.OrdinalIgnoreCase)
|
||||
|| file.StartsWith("nvonnxparser", StringComparison.OrdinalIgnoreCase))) components.Add("TensorRT");
|
||||
if (components.Count == 0) components.AddRange(missing);
|
||||
return $"{engine} 缺少运行所需的 {string.Join("、", components.Distinct(StringComparer.OrdinalIgnoreCase))}。请在硬件加速设置中点击“补齐依赖”后重新应用。";
|
||||
}
|
||||
|
||||
public static RuntimeInstallation Inspect(string baseDirectory, InferenceDeviceType engine)
|
||||
{
|
||||
if (engine == InferenceDeviceType.Cpu) return new(InferenceInstallationState.Installed, baseDirectory, "内置,无需下载");
|
||||
var plugins = Path.Combine(baseDirectory, "Plugins", "OnnxRuntime");
|
||||
var directory = RuntimeDirectory(plugins, engine);
|
||||
if (engine == InferenceDeviceType.DirectML && !File.Exists(Path.Combine(directory, "onnxruntime.dll"))) directory = baseDirectory;
|
||||
foreach (var file in ProviderFiles(engine))
|
||||
if (!File.Exists(Path.Combine(directory, file))) return new(InferenceInstallationState.Missing, directory, $"DLL 未安装:缺少 {file}");
|
||||
var missing = MissingDependencyFiles(engine, directory);
|
||||
return missing.Length == 0
|
||||
? new(InferenceInstallationState.Installed, directory, "DLL 已安装,需通过模型验证确认可用")
|
||||
: new(InferenceInstallationState.MissingDependencies, directory, $"依赖不完整:{string.Join("、", missing)}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public enum PaddleOcrCpuMode
|
||||
{
|
||||
FollowGlobal = 0,
|
||||
RuntimeAuto = 1,
|
||||
GameplayPriority = 2,
|
||||
Custom = 3
|
||||
}
|
||||
|
||||
public sealed record PaddleOcrCpuThreadOptions(int IntraOpThreads, int InterOpThreads, bool ParallelExecution, bool AllowSpinning);
|
||||
|
||||
/// <summary>冻结用户设置,检测和识别会话共享相同的参数来源,但分别计算算子内线程数。</summary>
|
||||
public sealed record PaddleOcrCpuOptions
|
||||
{
|
||||
public PaddleOcrCpuMode Mode { get; init; }
|
||||
public int DetectionThreads { get; init; } = Math.Min(2, Environment.ProcessorCount);
|
||||
public int RecognitionThreads { get; init; } = Math.Min(2, Environment.ProcessorCount);
|
||||
public int InterOpThreads { get; init; } = 1;
|
||||
public bool ParallelExecution { get; init; }
|
||||
public bool AllowSpinning { get; init; } = true;
|
||||
|
||||
public bool IsValid => Enum.IsDefined(Mode)
|
||||
&& DetectionThreads >= 0 && DetectionThreads <= Environment.ProcessorCount
|
||||
&& RecognitionThreads >= 0 && RecognitionThreads <= Environment.ProcessorCount
|
||||
&& InterOpThreads >= 0 && InterOpThreads <= Environment.ProcessorCount;
|
||||
|
||||
public PaddleOcrCpuOptions Normalize() => this with
|
||||
{
|
||||
Mode = Enum.IsDefined(Mode) ? Mode : PaddleOcrCpuMode.FollowGlobal,
|
||||
DetectionThreads = Math.Clamp(DetectionThreads, 0, Environment.ProcessorCount),
|
||||
RecognitionThreads = Math.Clamp(RecognitionThreads, 0, Environment.ProcessorCount),
|
||||
InterOpThreads = Math.Clamp(InterOpThreads, 0, Environment.ProcessorCount)
|
||||
};
|
||||
|
||||
public PaddleOcrCpuThreadOptions? Resolve(bool detection, int? processorCount = null)
|
||||
{
|
||||
var count = Math.Max(1, processorCount ?? Environment.ProcessorCount);
|
||||
var intraOp = Mode switch
|
||||
{
|
||||
// PR #3722:Det 用一半线程,Rec 用四分之一并限制在 2~4。
|
||||
// 小于两个可用逻辑处理器时,不能为了满足下限而超额创建线程。
|
||||
PaddleOcrCpuMode.GameplayPriority => detection ? Math.Clamp(count / 2, Math.Min(2, count), count)
|
||||
: Math.Clamp(count / 4, Math.Min(2, count), Math.Min(4, count)),
|
||||
PaddleOcrCpuMode.Custom => Math.Clamp(detection ? DetectionThreads : RecognitionThreads, 0, count),
|
||||
_ => -1
|
||||
};
|
||||
if (intraOp < 0) return null;
|
||||
var parallel = Mode == PaddleOcrCpuMode.Custom && ParallelExecution;
|
||||
return new(intraOp, parallel ? Math.Clamp(InterOpThreads, 0, count) : 1, parallel, AllowSpinning);
|
||||
}
|
||||
|
||||
public string Describe(int inheritedThreads)
|
||||
{
|
||||
static string Threads(int count) => count == 0 ? "自动(ORT 默认)" : count.ToString();
|
||||
if (Mode == PaddleOcrCpuMode.RuntimeAuto) return "OCR 使用 ONNX Runtime 自动调度";
|
||||
var det = Resolve(true);
|
||||
var rec = Resolve(false);
|
||||
if (det == null || rec == null) return $"OCR 跟随全局线程设置:{Threads(inheritedThreads)}";
|
||||
var mode = Mode == PaddleOcrCpuMode.GameplayPriority ? "游戏流畅优先" : "自定义设置";
|
||||
return $"OCR {mode} · 文本检测 {Threads(det.IntraOpThreads)} / 文字识别 {Threads(rec.IntraOpThreads)} · "
|
||||
+ (det.ParallelExecution ? $"节点并行 {Threads(det.InterOpThreads)}" : "节点顺序执行")
|
||||
+ $" · 自旋{(det.AllowSpinning ? "开启" : "关闭")}";
|
||||
}
|
||||
|
||||
// 跟随全局设置时保留旧签名,避免新增默认参数使已有设备验证失效。
|
||||
internal string SignatureSuffix => Mode switch
|
||||
{
|
||||
PaddleOcrCpuMode.FollowGlobal => "",
|
||||
PaddleOcrCpuMode.RuntimeAuto => $"|PPOCR-CPU-v1|{(int)Mode}",
|
||||
PaddleOcrCpuMode.GameplayPriority => $"|PPOCR-CPU-v1|{(int)Mode}|{AllowSpinning}",
|
||||
_ => $"|PPOCR-CPU-v1|{(int)Mode}|{DetectionThreads}|{RecognitionThreads}|{InterOpThreads}|{ParallelExecution}|{AllowSpinning}"
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
public enum InferenceValidationState { None, PendingRestart, Validating }
|
||||
public enum InferenceInstallationState { Missing, MissingDependencies, Installed }
|
||||
public enum InferenceBenchmarkScene { Ocr, DomainTree }
|
||||
|
||||
public sealed record InferenceDeviceInfo(string Id, string Name, int Index, string ProviderDevice);
|
||||
|
||||
/// <summary>已经解析设备与运行库的不可变运行时。每个会话创建时绑定一个实例,后续设置变化不会影响已有会话。</summary>
|
||||
public sealed record ResolvedInferenceRuntime(
|
||||
InferenceDeviceType Engine, InferenceDeviceInfo Device, bool CpuOcr,
|
||||
int CpuThreads, bool EnableModelCache, string RuntimeDirectory)
|
||||
{
|
||||
public PaddleOcrCpuOptions PaddleOcrCpu { get; init; } = new();
|
||||
public static InferenceDeviceInfo CpuDevice { get; } = new("CPU", "处理器", 0, "CPU");
|
||||
public static string ModelCacheDirectory => Global.Absolute(Path.Combine("Cache", "Inference"));
|
||||
public string Description => $"{(Engine == InferenceDeviceType.Cpu ? "CPU" : Engine.ToString())} · {Device.Name}";
|
||||
public string OcrDescription => (CpuOcr ? "CPU(强制 OCR 使用 CPU)" : Description)
|
||||
+ (CpuOcr || Engine == InferenceDeviceType.Cpu ? " · " + PaddleOcrCpu.Describe(CpuThreads) : "");
|
||||
public string Fingerprint => InferenceRuntimeFingerprint.Compute(Engine, Device.Id, CpuOcr, CpuThreads,
|
||||
EnableModelCache, PaddleOcrCpu);
|
||||
|
||||
private string CacheFingerprint => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
|
||||
$"engine-cache-v1|{Engine}|{Device.Id}|{OnnxRuntimeLoader.RequiredVersion}|CUDA12.8|cuDNN9.8|TensorRT10.8")));
|
||||
|
||||
public string GetCachePath(BgiOnnxModel model)
|
||||
=> GetCachePathForModel(model.ModalPath, ModelCacheDirectory);
|
||||
|
||||
public string GetCachePathForModel(string modelPath, string cacheDirectory)
|
||||
{
|
||||
// 普通 engine/timing 缓存不再引用 _ctx.onnx;模型变化或设备变化不能复用旧缓存。
|
||||
using var stream = File.OpenRead(modelPath);
|
||||
var modelHash = Convert.ToHexString(SHA256.HashData(stream));
|
||||
// 合并并缩短目录指纹,避免 Windows 下引擎自身的长文件名叠加超长路径。
|
||||
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(CacheFingerprint + modelHash)))[..16];
|
||||
return Path.Combine(cacheDirectory, Engine.ToString(), key);
|
||||
}
|
||||
|
||||
public static ResolvedInferenceRuntime Resolve(HardwareAccelerationConfig config,
|
||||
InferenceDeviceInfo device, string runtimeDirectory)
|
||||
{
|
||||
var engine = config.InferenceDevice;
|
||||
return new(engine, device, config.CpuOcr, config.Cpu.CpuThreads,
|
||||
engine is InferenceDeviceType.OpenVINO or InferenceDeviceType.TensorRT
|
||||
&& config.GetEngineSettings(engine).EnableModelCache,
|
||||
runtimeDirectory) { PaddleOcrCpu = config.PaddleOcrCpu.ToOptions() };
|
||||
}
|
||||
|
||||
public static ResolvedInferenceRuntime Cpu(int threads = 0, PaddleOcrCpuOptions? paddleOcrCpu = null,
|
||||
string runtimeDirectory = "") => new(InferenceDeviceType.Cpu, CpuDevice, true, threads, false,
|
||||
runtimeDirectory) { PaddleOcrCpu = paddleOcrCpu ?? new() };
|
||||
}
|
||||
|
||||
/// <summary>只描述会影响验证结果的配置指纹,不要求构造完整、已解析的运行时。</summary>
|
||||
public static class InferenceRuntimeFingerprint
|
||||
{
|
||||
public static string Compute(HardwareAccelerationConfig config, InferenceDeviceType engine)
|
||||
{
|
||||
var settings = config.GetEngineSettings(engine);
|
||||
var enableModelCache = engine is InferenceDeviceType.OpenVINO or InferenceDeviceType.TensorRT
|
||||
&& settings.EnableModelCache;
|
||||
return Compute(engine, settings.DeviceId, config.CpuOcr, config.Cpu.CpuThreads, enableModelCache,
|
||||
config.PaddleOcrCpu.ToOptions());
|
||||
}
|
||||
|
||||
public static string Compute(InferenceDeviceType engine, string deviceId, bool cpuOcr, int cpuThreads,
|
||||
bool enableModelCache, PaddleOcrCpuOptions paddleOcrCpu)
|
||||
=> Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
|
||||
$"{engine}|{deviceId}|{cpuOcr}|{cpuThreads}|{enableModelCache}|{OnnxRuntimeLoader.RequiredVersion}{paddleOcrCpu.SignatureSuffix}")));
|
||||
}
|
||||
|
||||
public static class InferenceTestImages
|
||||
{
|
||||
// 使用秘境中的石化古树实机截图,供运行库验证与设置页测速共用。
|
||||
public const string DomainTreeRelativePath = @"Assets\Model\Domain\test_petrified_trees.jpg";
|
||||
public static string DomainTreePath => Global.Absolute(DomainTreeRelativePath);
|
||||
public static bool HasDomainTreeImage => File.Exists(DomainTreePath);
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
|
||||
/// <summary>可恢复的下载与解压。所有文件先校验、写入暂存目录,调用方负责可回滚地提交安装。</summary>
|
||||
public sealed class RuntimePackageDownloader(HttpClient client)
|
||||
{
|
||||
public async Task<string> DownloadAsync(RuntimeDownloadPackage package, string cacheDirectory,
|
||||
IProgress<RuntimeDownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
Directory.CreateDirectory(cacheDirectory);
|
||||
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(package.Url.AbsoluteUri)));
|
||||
var path = Path.Combine(cacheDirectory, key + ".zip");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
if (await VerifyHashAsync(path, package, token)) return path;
|
||||
File.Delete(path);
|
||||
}
|
||||
var partial = path + ".part";
|
||||
var offset = File.Exists(partial) ? new FileInfo(partial).Length : 0;
|
||||
if (offset > 0 && package.DownloadBytes > 0 && offset >= package.DownloadBytes)
|
||||
{
|
||||
if (offset == package.DownloadBytes && await VerifyHashAsync(partial, package, token))
|
||||
{
|
||||
File.Move(partial, path, true);
|
||||
return path;
|
||||
}
|
||||
File.Delete(partial);
|
||||
offset = 0;
|
||||
}
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, package.Url);
|
||||
if (offset > 0) request.Headers.Range = new RangeHeaderValue(offset, null);
|
||||
using var headersTimeout = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
headersTimeout.CancelAfter(TimeSpan.FromSeconds(30));
|
||||
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, headersTimeout.Token);
|
||||
response.EnsureSuccessStatusCode();
|
||||
headersTimeout.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
if (response.StatusCode == HttpStatusCode.PartialContent)
|
||||
{
|
||||
if (response.Content.Headers.ContentRange?.From != offset) throw new InvalidDataException("下载服务器返回了错误的续传位置。");
|
||||
}
|
||||
else offset = 0;
|
||||
var total = response.Content.Headers.ContentRange?.Length ?? (response.Content.Headers.ContentLength + offset) ?? package.DownloadBytes;
|
||||
await using (var input = await response.Content.ReadAsStreamAsync(token))
|
||||
await using (var output = new FileStream(partial, offset > 0 ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None, 81920, true))
|
||||
{
|
||||
var buffer = new byte[81920];
|
||||
var received = offset;
|
||||
var lastReport = Environment.TickCount64;
|
||||
int length;
|
||||
while ((length = await input.ReadAsync(buffer, token)) > 0)
|
||||
{
|
||||
await output.WriteAsync(buffer.AsMemory(0, length), token);
|
||||
received += length;
|
||||
if (Environment.TickCount64 - lastReport >= 150)
|
||||
{
|
||||
progress?.Report(new($"正在下载 {package.Name}", received, total));
|
||||
lastReport = Environment.TickCount64;
|
||||
}
|
||||
}
|
||||
progress?.Report(new($"正在校验 {package.Name}", received, total));
|
||||
}
|
||||
if (!await VerifyHashAsync(partial, package, token))
|
||||
{
|
||||
File.Delete(partial);
|
||||
throw new InvalidDataException($"{package.Name} 下载校验失败,请重新下载。");
|
||||
}
|
||||
File.Move(partial, path, true);
|
||||
return path;
|
||||
}
|
||||
|
||||
public static async Task<bool> VerifyHashAsync(string path, RuntimeDownloadPackage package, CancellationToken token)
|
||||
{
|
||||
if (package.DownloadBytes > 0 && new FileInfo(path).Length != package.DownloadBytes) return false;
|
||||
// TensorRT 官方 ZIP 未发布摘要,提取时逐文件核对中央目录的 CRC32 和长度。
|
||||
if (package.Hash == null) return true;
|
||||
using var hash = IncrementalHash.CreateHash(new HashAlgorithmName(package.HashAlgorithm));
|
||||
await using var stream = File.OpenRead(path);
|
||||
var buffer = new byte[81920];
|
||||
int length;
|
||||
while ((length = await stream.ReadAsync(buffer, token)) > 0) hash.AppendData(buffer, 0, length);
|
||||
var actual = hash.GetHashAndReset();
|
||||
var expected = package.HashAlgorithm == "SHA512" ? Convert.FromBase64String(package.Hash) : Convert.FromHexString(package.Hash);
|
||||
return CryptographicOperations.FixedTimeEquals(actual, expected);
|
||||
}
|
||||
|
||||
public static async Task ExtractAsync(string archivePath, string directory, Func<string, bool> include, CancellationToken token)
|
||||
{
|
||||
var crcs = ReadCrcs(archivePath);
|
||||
using var archive = ZipFile.OpenRead(archivePath);
|
||||
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var entry in archive.Entries)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var normalized = entry.FullName.Replace('\\', '/');
|
||||
if (!include(normalized)) continue;
|
||||
// 只提取已选的运行文件并平铺,拒绝路径穿越和重复的文件名。
|
||||
var name = Path.GetFileName(normalized);
|
||||
if (name.Length == 0 || normalized.Split('/').Contains("..") || !names.Add(name))
|
||||
throw new InvalidDataException($"压缩包包含不安全或重复的文件:{normalized}");
|
||||
if (!crcs.TryGetValue(entry.FullName, out var expected)) throw new InvalidDataException("压缩包校验目录缺失。");
|
||||
await using var source = entry.Open();
|
||||
await using var output = File.Create(Path.Combine(directory, name));
|
||||
var buffer = new byte[81920];
|
||||
uint crc = uint.MaxValue;
|
||||
long count = 0;
|
||||
int length;
|
||||
while ((length = await source.ReadAsync(buffer, token)) > 0)
|
||||
{
|
||||
await output.WriteAsync(buffer.AsMemory(0, length), token);
|
||||
count += length;
|
||||
for (var i = 0; i < length; i++) crc = CrcTable[(crc ^ buffer[i]) & 255] ^ (crc >> 8);
|
||||
}
|
||||
if (count != entry.Length || ~crc != expected) throw new InvalidDataException($"文件校验失败:{name}");
|
||||
}
|
||||
if (names.Count == 0) throw new InvalidDataException("压缩包中没有对应的 Windows x64 运行文件。");
|
||||
}
|
||||
|
||||
private static Dictionary<string, uint> ReadCrcs(string path)
|
||||
{
|
||||
using var stream = File.OpenRead(path);
|
||||
var tail = new byte[(int)Math.Min(stream.Length, 65557)];
|
||||
stream.Position = stream.Length - tail.Length;
|
||||
stream.ReadExactly(tail);
|
||||
var end = tail.Length - 22;
|
||||
while (end >= 0 && BinaryPrimitives.ReadUInt32LittleEndian(tail.AsSpan(end, 4)) != 0x06054b50) end--;
|
||||
if (end < 0) throw new InvalidDataException("ZIP 中央目录缺失。");
|
||||
long directoryOffset = BinaryPrimitives.ReadUInt32LittleEndian(tail.AsSpan(end + 16, 4));
|
||||
long entries = BinaryPrimitives.ReadUInt16LittleEndian(tail.AsSpan(end + 10, 2));
|
||||
if (directoryOffset == uint.MaxValue || entries == ushort.MaxValue)
|
||||
{
|
||||
var locator = end - 20;
|
||||
if (locator < 0 || BinaryPrimitives.ReadUInt32LittleEndian(tail.AsSpan(locator, 4)) != 0x07064b50)
|
||||
throw new InvalidDataException("ZIP64 校验目录缺失。");
|
||||
stream.Position = checked((long)BinaryPrimitives.ReadUInt64LittleEndian(tail.AsSpan(locator + 8, 8)));
|
||||
var zip64 = new byte[56];
|
||||
stream.ReadExactly(zip64);
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(zip64) != 0x06064b50) throw new InvalidDataException("ZIP64 校验目录损坏。");
|
||||
entries = checked((long)BinaryPrimitives.ReadUInt64LittleEndian(zip64.AsSpan(32, 8)));
|
||||
directoryOffset = checked((long)BinaryPrimitives.ReadUInt64LittleEndian(zip64.AsSpan(48, 8)));
|
||||
}
|
||||
if (entries > 1_000_000 || directoryOffset >= stream.Length) throw new InvalidDataException("ZIP 校验目录大小无效。");
|
||||
stream.Position = directoryOffset;
|
||||
var result = new Dictionary<string, uint>(StringComparer.Ordinal);
|
||||
var header = new byte[46];
|
||||
for (var i = 0; i < entries; i++)
|
||||
{
|
||||
stream.ReadExactly(header);
|
||||
if (BinaryPrimitives.ReadUInt32LittleEndian(header) != 0x02014b50) throw new InvalidDataException("ZIP 校验目录损坏。");
|
||||
var name = new byte[BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(28))];
|
||||
stream.ReadExactly(name);
|
||||
result.Add(Encoding.UTF8.GetString(name), BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(16)));
|
||||
stream.Position += BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(30)) + BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(32));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static readonly uint[] CrcTable = CreateCrcTable();
|
||||
private static uint[] CreateCrcTable()
|
||||
{
|
||||
var table = new uint[256];
|
||||
for (uint i = 0; i < table.Length; i++)
|
||||
{
|
||||
var value = i;
|
||||
for (var bit = 0; bit < 8; bit++) value = (value & 1) != 0 ? (value >> 1) ^ 0xedb88320 : value >> 1;
|
||||
table[i] = value;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -146,6 +146,12 @@ public static class Feature2DExtensions
|
||||
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
|
||||
#pragma warning restore CS8604 // 引用类型参数可能为 null。
|
||||
speedTimer.Record("模板生成KeyPoint");
|
||||
if (queryKeyPoints.Length == 0 || queryDescriptors.Empty())
|
||||
{
|
||||
// 查询图未检测到任何特征点时,空描述子会让 knnMatch 抛出 OpenCVException(type=0),直接按匹配失败处理
|
||||
return new Point2f();
|
||||
}
|
||||
|
||||
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
|
||||
speedTimer.Record("FlannMatch");
|
||||
|
||||
@@ -249,6 +255,12 @@ public static class Feature2DExtensions
|
||||
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
|
||||
#pragma warning restore CS8604 // 引用类型参数可能为 null。
|
||||
speedTimer.Record("模板生成KeyPoint");
|
||||
if (queryKeyPoints.Length == 0 || queryDescriptors.Empty())
|
||||
{
|
||||
// 查询图未检测到任何特征点时,空描述子会让 knnMatch 抛出 OpenCVException(type=0),直接按匹配失败处理
|
||||
return [];
|
||||
}
|
||||
|
||||
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
|
||||
speedTimer.Record("FlannMatch");
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recorder.Model;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
@@ -12,7 +12,6 @@ using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Fischless.WindowsInput;
|
||||
using Vanara.PInvoke;
|
||||
using Wpf.Ui.Violeta.Controls;
|
||||
|
||||
@@ -67,32 +66,17 @@ public class KeyMouseMacroPlayer
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(timeToWait), ct);
|
||||
}
|
||||
|
||||
// 每个事件都从 InputHub 取当前通道,不缓存:回放期间截图器停止时后端会被替换。
|
||||
// 扩展键标志由通道按真实键盘判断(Win32 见 ExtendedKeys),网页版由 WebSdk 后端映射
|
||||
var input = InputHub.Foreground;
|
||||
switch (e.Type)
|
||||
{
|
||||
case MacroEventType.KeyDown:
|
||||
var vkDown = (User32.VK)e.KeyCode!;
|
||||
if (InputBuilder.IsExtendedKey(vkDown))
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyDown(false, vkDown);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyDown(vkDown);
|
||||
}
|
||||
|
||||
input.Keyboard.KeyDown((User32.VK)e.KeyCode!);
|
||||
break;
|
||||
|
||||
case MacroEventType.KeyUp:
|
||||
|
||||
var vkUp = (User32.VK)e.KeyCode!;
|
||||
if (InputBuilder.IsExtendedKey(vkUp))
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyUp(false, vkUp);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyUp(vkUp);
|
||||
}
|
||||
|
||||
input.Keyboard.KeyUp((User32.VK)e.KeyCode!);
|
||||
break;
|
||||
|
||||
case MacroEventType.MouseDown:
|
||||
@@ -102,15 +86,15 @@ public class KeyMouseMacroPlayer
|
||||
switch (buttonMouseDown)
|
||||
{
|
||||
case MouseButtons.Left:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).LeftButtonDown();
|
||||
input.Mouse.MoveMouseTo(xMouseDown, yMouseDown).LeftButtonDown();
|
||||
break;
|
||||
|
||||
case MouseButtons.Right:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).RightButtonDown();
|
||||
input.Mouse.MoveMouseTo(xMouseDown, yMouseDown).RightButtonDown();
|
||||
break;
|
||||
|
||||
case MouseButtons.Middle:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseDown, yMouseDown).MiddleButtonDown();
|
||||
input.Mouse.MoveMouseTo(xMouseDown, yMouseDown).MiddleButtonDown();
|
||||
break;
|
||||
|
||||
case MouseButtons.None:
|
||||
@@ -135,15 +119,15 @@ public class KeyMouseMacroPlayer
|
||||
switch (buttonMouseUp)
|
||||
{
|
||||
case MouseButtons.Left:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).LeftButtonUp();
|
||||
input.Mouse.MoveMouseTo(xMouseUp, yMouseUp).LeftButtonUp();
|
||||
break;
|
||||
|
||||
case MouseButtons.Right:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).RightButtonUp();
|
||||
input.Mouse.MoveMouseTo(xMouseUp, yMouseUp).RightButtonUp();
|
||||
break;
|
||||
|
||||
case MouseButtons.Middle:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(xMouseUp, yMouseUp).MiddleButtonUp();
|
||||
input.Mouse.MoveMouseTo(xMouseUp, yMouseUp).MiddleButtonUp();
|
||||
break;
|
||||
|
||||
case MouseButtons.None:
|
||||
@@ -162,7 +146,7 @@ public class KeyMouseMacroPlayer
|
||||
break;
|
||||
|
||||
case MacroEventType.MouseMoveTo:
|
||||
Simulation.SendInput.Mouse.MoveMouseTo(ToVirtualDesktopX(e.MouseX), ToVirtualDesktopY(e.MouseY));
|
||||
input.Mouse.MoveMouseTo(ToVirtualDesktopX(e.MouseX), ToVirtualDesktopY(e.MouseY));
|
||||
break;
|
||||
|
||||
case MacroEventType.MouseWheel:
|
||||
@@ -170,7 +154,7 @@ public class KeyMouseMacroPlayer
|
||||
if (num != 0)
|
||||
{
|
||||
// 不支持多次的场景,但是不会出现这种情况
|
||||
Simulation.SendInput.Mouse.VerticalScroll(num);
|
||||
input.Mouse.VerticalScroll(num);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -190,7 +174,7 @@ public class KeyMouseMacroPlayer
|
||||
}
|
||||
}
|
||||
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(e.MouseX, e.MouseY);
|
||||
input.Mouse.MoveMouseBy(e.MouseX, e.MouseY);
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
@@ -66,7 +66,7 @@ public class Dispatcher
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清理所有实时任务
|
||||
/// 清理所有实时任务(清空任务期间的启用名单,不销毁触发器实例)
|
||||
/// </summary>
|
||||
public void ClearAllTriggers()
|
||||
{
|
||||
@@ -92,7 +92,8 @@ public class Dispatcher
|
||||
throw new ArgumentNullException(nameof(realtimeTimer.Name), "实时任务名称不能为空");
|
||||
}
|
||||
|
||||
if (!TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config))
|
||||
// 加入任务期间的启用名单。脚本不需要中途撤销,名单在下一次 clearAllTriggers、项目切换或任务结束时整体清空
|
||||
if (TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config) is null)
|
||||
{
|
||||
throw new ArgumentException($"添加实时任务失败: {realtimeTimer.Name}", nameof(realtimeTimer.Name));
|
||||
}
|
||||
@@ -280,31 +281,24 @@ public class Dispatcher
|
||||
{
|
||||
throw new NullReferenceException($"{nameof(soloTask.Config)}为空");
|
||||
}
|
||||
GridScreenName gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null) ?? throw new Exception("gridScreenName为空或错误");
|
||||
string? itemName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "itemName", (string?)null);
|
||||
GridScreenName? gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null);
|
||||
bool stopByItemSort = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "stopByItemSort", false);
|
||||
IEnumerable<string>? itemNames = ScriptObjectConverter.GetValue<string>((ScriptObject)soloTask.Config, "itemNames");
|
||||
CountInventoryItemParam param = new()
|
||||
{
|
||||
GridScreenName = gridScreenName,
|
||||
ItemName = itemName,
|
||||
StopByItemSort = stopByItemSort,
|
||||
ItemNames = itemNames?.ToList() ?? []
|
||||
};
|
||||
|
||||
var result = await new CountInventoryItem(param).Start(cancellationToken);
|
||||
if (param.ItemName != null)
|
||||
dynamic expando = new ExpandoObject();
|
||||
var expandoDict = (IDictionary<string, object>)expando;
|
||||
foreach (var kvp in (Dictionary<string, int>)result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
else
|
||||
{
|
||||
dynamic expando = new ExpandoObject();
|
||||
var expandoDict = (IDictionary<string, object>)expando;
|
||||
foreach (var kvp in (Dictionary<string, int>)result)
|
||||
{
|
||||
expandoDict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
return expandoDict;
|
||||
expandoDict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
return expandoDict;
|
||||
}
|
||||
default:
|
||||
throw new ArgumentException($"未知的任务名称: {soloTask.Name}", nameof(soloTask.Name));
|
||||
@@ -441,7 +435,7 @@ public class Dispatcher
|
||||
/// </summary>
|
||||
/// <param name="param">背包物品计数参数。</param>
|
||||
/// <param name="customCt">自定义取消令牌。</param>
|
||||
/// <returns>单物品返回数量;多物品返回名称到数量的脚本对象。</returns>
|
||||
/// <returns>返回名称到数量的脚本对象。</returns>
|
||||
public async Task<object?> RunCountInventoryItemTask(CountInventoryItemParam param, CancellationToken? customCt = null)
|
||||
{
|
||||
if (param == null)
|
||||
@@ -452,20 +446,13 @@ public class Dispatcher
|
||||
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
|
||||
object result = await new CountInventoryItem(param).Start(cancellationToken);
|
||||
|
||||
if (param.ItemName != null)
|
||||
dynamic expando = new ExpandoObject();
|
||||
var expandoDict = (IDictionary<string, object>)expando;
|
||||
foreach (var kvp in (Dictionary<string, int>)result)
|
||||
{
|
||||
return result;
|
||||
expandoDict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
dynamic expando = new ExpandoObject();
|
||||
var expandoDict = (IDictionary<string, object>)expando;
|
||||
foreach (var kvp in (Dictionary<string, int>)result)
|
||||
{
|
||||
expandoDict[kvp.Key] = kvp.Value;
|
||||
}
|
||||
|
||||
return expandoDict;
|
||||
}
|
||||
return expandoDict;
|
||||
}
|
||||
}
|
||||
@@ -435,10 +435,11 @@ public class Genshin
|
||||
/// <param name="materialName">目标成品材料名。</param>
|
||||
/// <param name="quantity">目标合成个数,必须大于 0。</param>
|
||||
/// <param name="materialType">材料筛选类型;为空时从物品模型 CSV 中读取。</param>
|
||||
/// <param name="bonusType">合成加成角色类型,可为“概率返还素材”或“概率额外产出”;为空时不切换加成。</param>
|
||||
/// <returns>合成执行结果。</returns>
|
||||
public async Task<CraftMaterialResult> CraftMaterial(string materialName, int quantity, string? materialType = null)
|
||||
public async Task<CraftMaterialResult> CraftMaterial(string materialName, int quantity, string? materialType = null, string? bonusType = null)
|
||||
{
|
||||
return await new CraftMaterialTask(materialName, quantity, materialType).Start(CancellationContext.Instance.Cts.Token);
|
||||
return await new CraftMaterialTask(materialName, quantity, materialType, bonusType).Start(CancellationContext.Instance.Cts.Token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
@@ -13,7 +13,6 @@ using BetterGenshinImpact.GameTask.Common;
|
||||
using Vanara.PInvoke;
|
||||
using static Vanara.PInvoke.User32;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
@@ -32,106 +31,21 @@ public class GlobalMethod
|
||||
|
||||
#region 键盘操作
|
||||
|
||||
// 鼠标键(VK_LBUTTON、VK_RBUTTON、VK_MBUTTON、VK_XBUTTON1、VK_XBUTTON2)由输入通道转成对应的鼠标键,
|
||||
// 扩展键的处理也在通道内部完成
|
||||
public static void KeyDown(string key)
|
||||
{
|
||||
var vk = KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key));
|
||||
switch (key)
|
||||
{
|
||||
case "VK_LBUTTON":
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
break;
|
||||
case "VK_RBUTTON":
|
||||
Simulation.SendInput.Mouse.RightButtonDown();
|
||||
break;
|
||||
case "VK_MBUTTON":
|
||||
Simulation.SendInput.Mouse.MiddleButtonDown();
|
||||
break;
|
||||
case "VK_XBUTTON1":
|
||||
Simulation.SendInput.Mouse.XButtonDown(0x0001);
|
||||
break;
|
||||
case "VK_XBUTTON2":
|
||||
Simulation.SendInput.Mouse.XButtonDown(0x0001);
|
||||
break;
|
||||
default:
|
||||
if (InputBuilder.IsExtendedKey(vk))
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyDown(false, vk);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyDown(vk);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
InputHub.Foreground.Keyboard.KeyDown(KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key)));
|
||||
}
|
||||
|
||||
public static void KeyUp(string key)
|
||||
{
|
||||
var vk = KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key));
|
||||
switch (key)
|
||||
{
|
||||
case "VK_LBUTTON":
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
break;
|
||||
case "VK_RBUTTON":
|
||||
Simulation.SendInput.Mouse.RightButtonUp();
|
||||
break;
|
||||
case "VK_MBUTTON":
|
||||
Simulation.SendInput.Mouse.MiddleButtonUp();
|
||||
break;
|
||||
case "VK_XBUTTON1":
|
||||
Simulation.SendInput.Mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
case "VK_XBUTTON2":
|
||||
Simulation.SendInput.Mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
default:
|
||||
if (InputBuilder.IsExtendedKey(vk))
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyUp(false, vk);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyUp(vk);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
InputHub.Foreground.Keyboard.KeyUp(KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key)));
|
||||
}
|
||||
|
||||
public static void KeyPress(string key)
|
||||
{
|
||||
var vk = KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key));
|
||||
switch (key)
|
||||
{
|
||||
case "VK_LBUTTON":
|
||||
Simulation.SendInput.Mouse.LeftButtonClick();
|
||||
break;
|
||||
case "VK_RBUTTON":
|
||||
Simulation.SendInput.Mouse.RightButtonClick();
|
||||
break;
|
||||
case "VK_MBUTTON":
|
||||
Simulation.SendInput.Mouse.MiddleButtonClick();
|
||||
break;
|
||||
case "VK_XBUTTON1":
|
||||
Simulation.SendInput.Mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
case "VK_XBUTTON2":
|
||||
Simulation.SendInput.Mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
default:
|
||||
if (InputBuilder.IsExtendedKey(vk))
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyPress(false, vk);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.Keyboard.KeyPress(vk);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
InputHub.Foreground.Keyboard.KeyPress(KeyBindingsSettingsPageViewModel.MappingKey(ToVk(key)));
|
||||
}
|
||||
|
||||
private static User32.VK ToVk(string key)
|
||||
@@ -177,7 +91,7 @@ public class GlobalMethod
|
||||
var realDpi = TaskContext.Instance().DpiScale;
|
||||
x = (int)(x * realDpi / _dpi);
|
||||
y = (int)(y * realDpi / _dpi);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
|
||||
InputHub.Foreground.Mouse.MoveMouseBy(x, y);
|
||||
}
|
||||
|
||||
public static void MoveMouseTo(int x, int y)
|
||||
@@ -202,52 +116,52 @@ public class GlobalMethod
|
||||
|
||||
public static void LeftButtonClick()
|
||||
{
|
||||
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(60).LeftButtonUp();
|
||||
InputHub.Foreground.Mouse.LeftButtonDown().Sleep(60).LeftButtonUp();
|
||||
}
|
||||
|
||||
public static void LeftButtonDown()
|
||||
{
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
InputHub.Foreground.Mouse.LeftButtonDown();
|
||||
}
|
||||
|
||||
public static void LeftButtonUp()
|
||||
{
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
InputHub.Foreground.Mouse.LeftButtonUp();
|
||||
}
|
||||
|
||||
public static void RightButtonClick()
|
||||
{
|
||||
Simulation.SendInput.Mouse.RightButtonDown().Sleep(60).RightButtonUp();
|
||||
InputHub.Foreground.Mouse.RightButtonDown().Sleep(60).RightButtonUp();
|
||||
}
|
||||
|
||||
public static void RightButtonDown()
|
||||
{
|
||||
Simulation.SendInput.Mouse.RightButtonDown();
|
||||
InputHub.Foreground.Mouse.RightButtonDown();
|
||||
}
|
||||
|
||||
public static void RightButtonUp()
|
||||
{
|
||||
Simulation.SendInput.Mouse.RightButtonUp();
|
||||
InputHub.Foreground.Mouse.RightButtonUp();
|
||||
}
|
||||
|
||||
public static void MiddleButtonClick()
|
||||
{
|
||||
Simulation.SendInput.Mouse.MiddleButtonClick();
|
||||
InputHub.Foreground.Mouse.MiddleButtonClick();
|
||||
}
|
||||
|
||||
public static void MiddleButtonDown()
|
||||
{
|
||||
Simulation.SendInput.Mouse.MiddleButtonDown();
|
||||
InputHub.Foreground.Mouse.MiddleButtonDown();
|
||||
}
|
||||
|
||||
public static void MiddleButtonUp()
|
||||
{
|
||||
Simulation.SendInput.Mouse.MiddleButtonUp();
|
||||
InputHub.Foreground.Mouse.MiddleButtonUp();
|
||||
}
|
||||
|
||||
public static void VerticalScroll(int scrollAmountInClicks)
|
||||
{
|
||||
Simulation.SendInput.Mouse.VerticalScroll(scrollAmountInClicks);
|
||||
InputHub.Foreground.Mouse.VerticalScroll(scrollAmountInClicks);
|
||||
}
|
||||
|
||||
#endregion 鼠标操作
|
||||
@@ -271,6 +185,15 @@ public class GlobalMethod
|
||||
|
||||
#region 文字输入操作
|
||||
|
||||
/// <summary>
|
||||
/// 通过本机剪贴板 + Ctrl+V 输入文字。
|
||||
/// <para>
|
||||
/// 注意:云原神网页版(WebSdk 后端)尚未适配。写本机剪贴板对云端无效,Ctrl+V 粘贴不到内容。
|
||||
/// 需要时可以在 <c>InputHub.Backend is WebSdkInputBackend web</c> 分支里,把"写本机剪贴板"换成
|
||||
/// <c>web.Sdk.Invoke("sendClipboard", text)</c> 后再发 Ctrl+V,或直接调用 <c>web.Sdk.Invoke("sendIme", text)</c>。
|
||||
/// 两种方式都未实测。
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static void InputText(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
@@ -286,12 +209,13 @@ public class GlobalMethod
|
||||
// 将要输入的文本复制到剪贴板
|
||||
UIDispatcherHelper.Invoke(() => Clipboard.SetDataObject(text));
|
||||
|
||||
// 模拟Ctrl+V粘贴操作
|
||||
Simulation.SendInput.Keyboard.KeyDown(false, VK.VK_CONTROL);
|
||||
// 通过剪贴板 + Ctrl+V 输入文字,只面向键鼠后端。
|
||||
// 手柄场景用不到文字输入,这里不做手柄适配;将来如果需要,请单独实现,不要依赖 Ctrl 的映射。
|
||||
InputHub.Foreground.Keyboard.KeyDown(VK.VK_CONTROL);
|
||||
Sleep(20);
|
||||
Simulation.SendInput.Keyboard.KeyPress(VK.VK_V);
|
||||
InputHub.Foreground.Keyboard.KeyPress(VK.VK_V);
|
||||
Sleep(20);
|
||||
Simulation.SendInput.Keyboard.KeyUp(false, VK.VK_CONTROL);
|
||||
InputHub.Foreground.Keyboard.KeyUp(VK.VK_CONTROL);
|
||||
|
||||
// 等待一小段时间确保粘贴完成
|
||||
Sleep(100);
|
||||
|
||||
@@ -19,7 +19,7 @@ public class Http
|
||||
|
||||
private void CheckHttpPermission(string url)
|
||||
{
|
||||
var currentProject = TaskContext.Instance().CurrentScriptProject;
|
||||
var currentProject = RunnerContext.Instance.CurrentScriptProject;
|
||||
if (!currentProject?.AllowJsHTTP ?? false)
|
||||
{
|
||||
throw new UnauthorizedAccessException("当前JS脚本不允许使用HTTP请求,请在调度器通用设置中启用“JS HTTP权限”");
|
||||
|
||||
@@ -26,7 +26,7 @@ public class Notification
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentProject = TaskContext.Instance().CurrentScriptProject;
|
||||
var currentProject = RunnerContext.Instance.CurrentScriptProject;
|
||||
return _config.NotificationConfig.JsNotificationEnabled &&
|
||||
(currentProject?.AllowJsNotification ?? true);
|
||||
}
|
||||
|
||||
@@ -1,33 +1,36 @@
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence.Simulator;
|
||||
|
||||
/// <summary>
|
||||
/// JS 脚本中的 new PostMessage(),走后台通道。
|
||||
/// 每次调用时从 InputHub 取通道,后端切换后自动生效;网页版下与前台通道相同
|
||||
/// </summary>
|
||||
public class PostMessage
|
||||
{
|
||||
private readonly PostMessageSimulator _postMessageSimulator = TaskContext.Instance().PostMessageSimulator;
|
||||
private static IInputChannel Channel => InputHub.Background;
|
||||
|
||||
public void KeyDown(string key)
|
||||
{
|
||||
_postMessageSimulator.KeyDownBackground(ToVk(key));
|
||||
Channel.Keyboard.KeyDown(ToVk(key));
|
||||
}
|
||||
|
||||
public void KeyUp(string key)
|
||||
{
|
||||
_postMessageSimulator.KeyUpBackground(ToVk(key));
|
||||
Channel.Keyboard.KeyUp(ToVk(key));
|
||||
}
|
||||
|
||||
public void KeyPress(string key)
|
||||
{
|
||||
_postMessageSimulator.KeyPressBackground(ToVk(key));
|
||||
Channel.Keyboard.KeyPress(ToVk(key));
|
||||
}
|
||||
|
||||
public void Click()
|
||||
{
|
||||
_postMessageSimulator.LeftButtonClick();
|
||||
Channel.Mouse.LeftButtonClick();
|
||||
}
|
||||
|
||||
private static User32.VK ToVk(string key)
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.Core.Script.Utils;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.GameTask.Model.Area.Converter;
|
||||
using Compunet.YoloSharp;
|
||||
using Compunet.YoloSharp.Data;
|
||||
using Compunet.YoloSharp.Metadata;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public sealed class YoloPredictorFactory(string rootPath)
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建基于 ONNX 模型的 YOLO 预测器
|
||||
/// </summary>
|
||||
/// <param name="modelPath">相对于脚本工程根目录的模型路径</param>
|
||||
/// <param name="options">可选推理配置;未指定的属性使用 <see cref="YoloConfiguration"/> 默认值</param>
|
||||
/// <remarks>
|
||||
/// <paramref name="options"/> 使用 <see cref="YoloConfiguration"/> 的属性名,作为预测器的基准配置
|
||||
/// 支持以下常用项:
|
||||
/// <list type="bullet">
|
||||
/// <item><description><c>confidence</c>:置信度阈值(默认 0.3)</description></item>
|
||||
/// <item><description><c>iou</c>:NMS 的 IoU 阈值(默认 0.45)</description></item>
|
||||
/// <item><description><c>keepAspectRatio</c>:是否保持宽高比并留边(默认 true)</description></item>
|
||||
/// <item><description><c>applyAutoOrient</c>:是否根据图像方向标记校正图像(默认 true)/></description></item>
|
||||
/// <item><description><c>suppressParallelInference</c>:是否等待并发推理(默认 false)</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public ScriptYoloPredictor CreatePredictor(string modelPath, ScriptObject? options = null)
|
||||
{
|
||||
modelPath = ScriptUtils.NormalizePath(rootPath, modelPath);
|
||||
if (!modelPath.EndsWith(".onnx", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException("模型文件必须是.onnx");
|
||||
}
|
||||
|
||||
var configuration = MergeConfiguration(YoloConfiguration.Default, options);
|
||||
return new ScriptYoloPredictor(modelPath, configuration);
|
||||
}
|
||||
|
||||
internal static YoloConfiguration MergeConfiguration(YoloConfiguration baseConfiguration, ScriptObject? options)
|
||||
{
|
||||
var configuration = new YoloConfiguration();
|
||||
var properties = typeof(YoloConfiguration)
|
||||
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
|
||||
.Where(p => p.CanWrite);
|
||||
|
||||
foreach (var property in properties)
|
||||
{
|
||||
property.SetValue(configuration, property.GetValue(baseConfiguration));
|
||||
|
||||
var propertyName = options?.PropertyNames.FirstOrDefault(name =>
|
||||
string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
if (propertyName is null) continue;
|
||||
|
||||
var value = options!.GetProperty(propertyName);
|
||||
if (value is not Undefined and not null)
|
||||
{
|
||||
property.SetValue(configuration, Convert.ChangeType(value, property.PropertyType));
|
||||
}
|
||||
}
|
||||
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class ScriptYoloPredictor : IDisposable
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly YoloConfiguration _configuration;
|
||||
private readonly string _modelPath;
|
||||
private BgiYoloPredictor? _bgiPredictor;
|
||||
private bool _disposed;
|
||||
|
||||
internal ScriptYoloPredictor(string modelPath, YoloConfiguration configuration)
|
||||
{
|
||||
_modelPath = modelPath;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对当前游戏画面做检测(可选择使用自定义检测参数)
|
||||
/// </summary>
|
||||
public List<YoloRegion> Detect(ScriptObject? options = null)
|
||||
{
|
||||
return RunDetection(options is null ? _configuration : YoloPredictorFactory.MergeConfiguration(_configuration, options));
|
||||
}
|
||||
|
||||
private List<YoloRegion> RunDetection(YoloConfiguration configuration)
|
||||
{
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
return GetInnerPredictor(YoloTask.Detect).Detect(ra.CacheImage, configuration).Select(box =>
|
||||
{
|
||||
var bounds = box.Bounds;
|
||||
return new YoloRegion(bounds.X, bounds.Y, bounds.Width, bounds.Height, box, ra);
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 对当前游戏画面做分类(可选择使用自定义推理参数)
|
||||
/// </summary>
|
||||
/// <returns>按置信度从高到低排列的分类结果,第一项为最可能的类别</returns>
|
||||
/// <remarks>
|
||||
/// 分类模型会返回全部类别;<see cref="YoloConfiguration.Confidence"/> 和
|
||||
/// <see cref="YoloConfiguration.IoU"/> 不会对分类结果进行筛选。
|
||||
/// </remarks>
|
||||
public List<YoloClassification> Classify(ScriptObject? options = null)
|
||||
{
|
||||
var configuration = options is null
|
||||
? _configuration
|
||||
: YoloPredictorFactory.MergeConfiguration(_configuration, options);
|
||||
|
||||
using var ra = TaskControl.CaptureToRectArea();
|
||||
return GetInnerPredictor(YoloTask.Classify).Classify(ra.CacheImage, configuration)
|
||||
.Select(classification => new YoloClassification(classification))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private YoloPredictor GetInnerPredictor(YoloTask expectedTask)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
var predictor = (_bgiPredictor ??= CreateBgiPredictor()).Predictor;
|
||||
if (predictor.Metadata.Task != expectedTask)
|
||||
{
|
||||
throw new InvalidOperationException($"当前模型的任务类型为 {predictor.Metadata.Task},不能执行 {expectedTask} 推理");
|
||||
}
|
||||
|
||||
return predictor;
|
||||
}
|
||||
}
|
||||
|
||||
private BgiYoloPredictor CreateBgiPredictor()
|
||||
{
|
||||
var cacheRelativePath = Path.Combine(BgiOnnxModel.ModelCacheRelativePath, "js",
|
||||
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(_modelPath))));
|
||||
var model = new BgiOnnxModel(Path.GetFileNameWithoutExtension(_modelPath), _modelPath, cacheRelativePath);
|
||||
var predictor = App.ServiceProvider.GetRequiredService<BgiOnnxFactory>().CreateYoloPredictor(model);
|
||||
try
|
||||
{
|
||||
var yolo = predictor.Predictor;
|
||||
if (yolo.Metadata.Task is not (YoloTask.Detect or YoloTask.Classify) || yolo.Metadata.Names.Length == 0)
|
||||
{
|
||||
throw new InvalidOperationException("模型必须是类别名非空的检测或分类模型");
|
||||
}
|
||||
|
||||
return predictor;
|
||||
}
|
||||
catch
|
||||
{
|
||||
predictor.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_bgiPredictor?.Dispose();
|
||||
_bgiPredictor = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class YoloRegion(int x, int y, int width, int height, YoloPrediction detection, Region owner)
|
||||
: Region(x, y, width, height, owner, new TranslationConverter(x, y), owner.DrawingBoard)
|
||||
{
|
||||
public int Id { get; } = detection.Name.Id;
|
||||
|
||||
public string Name { get; } = detection.Name.Name;
|
||||
|
||||
public float Confidence { get; } = detection.Confidence;
|
||||
}
|
||||
|
||||
public sealed class YoloClassification(Classification classification)
|
||||
{
|
||||
public int Id { get; } = classification.Name.Id;
|
||||
|
||||
public string Name { get; } = classification.Name.Name;
|
||||
|
||||
public float Confidence { get; } = classification.Confidence;
|
||||
}
|
||||
@@ -44,15 +44,16 @@ public class EngineExtend
|
||||
engine.AddHostObject("characterDevelopmentTask", new CharacterDevelopmentTask());
|
||||
engine.AddHostObject("log", new Log());
|
||||
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
|
||||
engine.AddHostObject("http", new Http()); // 限制文件访问
|
||||
engine.AddHostObject("http", new Http()); // 限制网络访问
|
||||
engine.AddHostObject("yolo", new YoloPredictorFactory(workDir)); // YOLO ONNX 推理
|
||||
engine.AddHostObject("notification", new Notification());
|
||||
|
||||
|
||||
// 任务调度器
|
||||
engine.AddHostObject("dispatcher", new Dispatcher(config));
|
||||
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
|
||||
engine.AddHostType("SoloTask", typeof(SoloTask));
|
||||
engine.AddHostType("AutoSkipConfig", typeof(AutoSkipConfig));
|
||||
|
||||
|
||||
// 添加取消令牌相关类型
|
||||
engine.AddHostType("CancellationTokenSource", typeof(CancellationTokenSource));
|
||||
engine.AddHostType("CancellationToken", typeof(CancellationToken));
|
||||
@@ -71,32 +72,32 @@ public class EngineExtend
|
||||
engine.AddHostType("GameCaptureRegion", typeof(GameCaptureRegion));
|
||||
engine.AddHostType("ImageRegion", typeof(ImageRegion));
|
||||
engine.AddHostType("Region", typeof(Region));
|
||||
|
||||
|
||||
engine.AddHostType("Pen", typeof(Pen));
|
||||
engine.AddHostType("Color", typeof(Color));
|
||||
|
||||
|
||||
engine.AddHostType("CombatScenes", typeof(CombatScenes));
|
||||
engine.AddHostType("Avatar", typeof(Avatar));
|
||||
|
||||
|
||||
|
||||
|
||||
engine.AddHostObject("OpenCvSharp", new HostTypeCollection("OpenCvSharp"));
|
||||
|
||||
engine.AddHostType("ServerTime", typeof(ServerTime));
|
||||
|
||||
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
|
||||
|
||||
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
|
||||
engine.AddHostType("AutoBossParam", typeof(AutoBossParam));
|
||||
engine.AddHostType("CountInventoryItemParam", typeof(CountInventoryItemParam));
|
||||
engine.AddHostType("GridScreenName", typeof(GridScreenName));
|
||||
engine.AddHostType("ItemIconRecognitionMode", typeof(ItemIconRecognitionMode));
|
||||
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
|
||||
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
|
||||
engine.AddHostType("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
|
||||
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
|
||||
engine.AddHostObject("strategyFile", new StrategyFile());
|
||||
//鼠标回调
|
||||
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
|
||||
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
|
||||
// 添加C#的类型
|
||||
engine.AddHostType(typeof(Task));
|
||||
|
||||
|
||||
// 新的BvPage类
|
||||
engine.AddHostType("BvPage", typeof(BvPage));
|
||||
engine.AddHostType("BvLocator", typeof(BvLocator));
|
||||
|
||||
@@ -238,7 +238,7 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
}
|
||||
var pathingTask = new PathExecutor(CancellationContext.Instance.Cts.Token);
|
||||
pathingTask.PartyConfig = GroupInfo?.Config.PathingConfig;
|
||||
if (pathingTask.PartyConfig is null || pathingTask.PartyConfig.AutoPickEnabled)
|
||||
if (!pathingTask.PartyConfig.Enabled || pathingTask.PartyConfig.AutoPickEnabled)
|
||||
{
|
||||
TaskTriggerDispatcher.Instance().AddTrigger("AutoPick", null);
|
||||
}
|
||||
|
||||
@@ -513,7 +513,7 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
|
||||
public static readonly Dictionary<string, string> RepoChannels = new()
|
||||
{
|
||||
{ "CNB", "https://cnb.cool/bettergi/bettergi-scripts-list" },
|
||||
{ "GitCode", "https://gitcode.com/huiyadanli/bettergi-scripts-list" },
|
||||
// { "GitCode", "https://gitcode.com/huiyadanli/bettergi-scripts-list" }, // 由于 10MB限制,下掉
|
||||
{ "GitHub", "https://github.com/babalae/bettergi-scripts-list" },
|
||||
};
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ using CommunityToolkit.Mvvm.Messaging;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Net;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.WebView;
|
||||
|
||||
@@ -68,6 +69,9 @@ public sealed class RepoWebBridge
|
||||
public async Task<string> GetUserConfigJson()
|
||||
{
|
||||
string userConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "User", "config.json");
|
||||
|
||||
// 保存有防抖,读取文件前先写入尚未落盘的改动
|
||||
App.GetService<IConfigService>()?.Flush();
|
||||
|
||||
if (!File.Exists(userConfigPath))
|
||||
{
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Simulator;
|
||||
|
||||
/// <summary>
|
||||
/// 按真实键盘的行为判断按键是否为扩展键(SendInput 的 KEYEVENTF_EXTENDEDKEY、按键消息 lParam 的第 24 位)。
|
||||
/// <para>
|
||||
/// 不使用 Fischless 的 InputBuilder.IsExtendedKey:它把左 Alt 以及泛指的 Alt / Ctrl 也算作扩展键,
|
||||
/// 发出去会被识别成右 Alt / 右 Ctrl。
|
||||
/// </para>
|
||||
/// 参考:https://learn.microsoft.com/windows/win32/inputdev/about-keyboard-input#extended-key-flag
|
||||
/// </summary>
|
||||
public static class ExtendedKeys
|
||||
{
|
||||
public static bool IsExtended(User32.VK key) => key switch
|
||||
{
|
||||
// 右侧 Ctrl / Alt;左侧和泛指的 Ctrl / Alt 不是扩展键
|
||||
User32.VK.VK_RCONTROL or User32.VK.VK_RMENU => true,
|
||||
|
||||
// 小键盘左侧的编辑区和方向键
|
||||
User32.VK.VK_INSERT or User32.VK.VK_DELETE
|
||||
or User32.VK.VK_HOME or User32.VK.VK_END
|
||||
or User32.VK.VK_PRIOR or User32.VK.VK_NEXT
|
||||
or User32.VK.VK_LEFT or User32.VK.VK_UP
|
||||
or User32.VK.VK_RIGHT or User32.VK.VK_DOWN => true,
|
||||
|
||||
// 小键盘 / 与 NumLock,Break(Ctrl+Pause)与 PrintScreen
|
||||
User32.VK.VK_DIVIDE or User32.VK.VK_NUMLOCK
|
||||
or User32.VK.VK_CANCEL or User32.VK.VK_SNAPSHOT => true,
|
||||
|
||||
// 左右 Win 与菜单键
|
||||
User32.VK.VK_LWIN or User32.VK.VK_RWIN or User32.VK.VK_APPS => true,
|
||||
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using System.Threading;
|
||||
using Fischless.WindowsInput;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// 用于扩展<seealso cref="Fischless.WindowsInput.InputSimulator"/>的功能
|
||||
/// </summary>
|
||||
public static class InputSimulatorExtension
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 模拟玩家操作
|
||||
/// </summary>
|
||||
/// <param name="action">动作</param>
|
||||
/// <param name="type">按键类型</param>
|
||||
public static void SimulateAction(this InputSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
|
||||
{
|
||||
var key = action.ToActionKey();
|
||||
switch (type)
|
||||
{
|
||||
case KeyType.KeyPress:
|
||||
KeyPress(self, key);
|
||||
break;
|
||||
case KeyType.KeyDown:
|
||||
KeyDown(self, key);
|
||||
break;
|
||||
case KeyType.KeyUp:
|
||||
KeyUp(self, key);
|
||||
break;
|
||||
case KeyType.Hold:
|
||||
HoldKeyPress(self, key);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void HoldKeyPress(InputSimulator self, KeyId key)
|
||||
{
|
||||
KeyDown(self, key);
|
||||
Thread.Sleep(1000);
|
||||
KeyUp(self, key);
|
||||
}
|
||||
|
||||
private static void KeyPress(InputSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.Mouse.LeftButtonClick();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.Mouse.RightButtonClick();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
self.Mouse.MiddleButtonClick();
|
||||
break;
|
||||
case KeyId.MouseSideButton1:
|
||||
self.Mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
case KeyId.MouseSideButton2:
|
||||
self.Mouse.XButtonClick(0x0001);
|
||||
break;
|
||||
default:
|
||||
var k = key.ToVK();
|
||||
// 解决 shift 之类的键位没法正常使用的问题
|
||||
if (InputBuilder.IsExtendedKey(k))
|
||||
{
|
||||
self.Keyboard.KeyPress(false, k);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.Keyboard.KeyPress(k);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyDown(InputSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.Mouse.LeftButtonDown();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.Mouse.RightButtonDown();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
self.Mouse.MiddleButtonDown();
|
||||
break;
|
||||
case KeyId.MouseSideButton1:
|
||||
self.Mouse.XButtonDown(0x0001);
|
||||
break;
|
||||
case KeyId.MouseSideButton2:
|
||||
self.Mouse.XButtonDown(0x0001);
|
||||
break;
|
||||
default:
|
||||
var k = key.ToVK();
|
||||
// 解决 shift 之类的键位没法正常使用的问题
|
||||
if (InputBuilder.IsExtendedKey(k))
|
||||
{
|
||||
self.Keyboard.KeyDown(false, k);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.Keyboard.KeyDown(k);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyUp(InputSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.Mouse.LeftButtonUp();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.Mouse.RightButtonUp();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
self.Mouse.MiddleButtonUp();
|
||||
break;
|
||||
case KeyId.MouseSideButton1:
|
||||
self.Mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
case KeyId.MouseSideButton2:
|
||||
self.Mouse.XButtonUp(0x0001);
|
||||
break;
|
||||
default:
|
||||
var k = key.ToVK();
|
||||
// 解决 shift 之类的键位没法正常使用的问题
|
||||
if (InputBuilder.IsExtendedKey(k))
|
||||
{
|
||||
self.Keyboard.KeyUp(false, k);
|
||||
}
|
||||
else
|
||||
{
|
||||
self.Keyboard.KeyUp(k);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using Fischless.WindowsInput;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
|
||||
/// <summary>
|
||||
/// 为<seealso cref="PostMessageSimulator"/>提供扩展功能
|
||||
/// </summary>
|
||||
public static class PostMessageSimulatorExtension
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 模拟玩家操作
|
||||
/// </summary>
|
||||
/// <param name="action">动作</param>
|
||||
/// <param name="type">按键类型</param>
|
||||
public static PostMessageSimulator SimulateAction(this PostMessageSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
|
||||
{
|
||||
var key = action.ToActionKey();
|
||||
switch (type)
|
||||
{
|
||||
case KeyType.KeyPress:
|
||||
KeyPress(self, key);
|
||||
break;
|
||||
case KeyType.KeyDown:
|
||||
KeyDown(self, key);
|
||||
break;
|
||||
case KeyType.KeyUp:
|
||||
KeyUp(self, key);
|
||||
break;
|
||||
case KeyType.Hold:
|
||||
HoldKeyPress(self, key);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
private static void HoldKeyPress(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
self.LongKeyPress(key.ToVK());
|
||||
}
|
||||
|
||||
private static void KeyPress(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.LeftButtonClick();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.RightButtonClick();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyPress(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyDown(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.LeftButtonDown();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.RightButtonDown();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyDown(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyUp(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.LeftButtonUp();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
self.RightButtonUp();
|
||||
break;
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyUp(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 模拟玩家操作(后台)
|
||||
/// </summary>
|
||||
/// <param name="action">动作</param>
|
||||
/// <param name="type">按键类型</param>
|
||||
public static PostMessageSimulator SimulateActionBackground(this PostMessageSimulator self, GIActions action, KeyType type = KeyType.KeyPress)
|
||||
{
|
||||
var key = action.ToActionKey();
|
||||
switch (type)
|
||||
{
|
||||
case KeyType.KeyPress:
|
||||
KeyPressBackground(self, key);
|
||||
break;
|
||||
case KeyType.KeyDown:
|
||||
KeyDownBackground(self, key);
|
||||
break;
|
||||
case KeyType.KeyUp:
|
||||
KeyUpBackground(self, key);
|
||||
break;
|
||||
case KeyType.Hold:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
private static void KeyPressBackground(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
self.LeftButtonClickBackground();
|
||||
break;
|
||||
case KeyId.MouseRightButton:
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyPressBackground(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyDownBackground(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
case KeyId.MouseRightButton:
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyDownBackground(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static void KeyUpBackground(PostMessageSimulator self, KeyId key)
|
||||
{
|
||||
switch (key)
|
||||
{
|
||||
case KeyId.None:
|
||||
case KeyId.Unknown:
|
||||
break;
|
||||
case KeyId.MouseLeftButton:
|
||||
case KeyId.MouseRightButton:
|
||||
case KeyId.MouseMiddleButton:
|
||||
case KeyId.MouseSideButton1:
|
||||
case KeyId.MouseSideButton2:
|
||||
break;
|
||||
default:
|
||||
self.KeyUpBackground(key.ToVK());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -25,6 +25,39 @@ public class PostMessageSimulator
|
||||
_hWnd = hWnd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按键消息的 lParam:重复次数 1,扫描码按 VK 计算;扩展键带第 24 位,判断规则与前台 SendInput 通道相同(见 ExtendedKeys);
|
||||
/// 抬起时带“之前为按下”和“状态转换”位
|
||||
/// </summary>
|
||||
public static nint MakeKeyLParam(User32.VK vk, bool keyUp)
|
||||
{
|
||||
var scan = User32.MapVirtualKey((uint)vk, 0) & 0xFFu;
|
||||
var lParam = 1u | (scan << 16);
|
||||
if (ExtendedKeys.IsExtended(vk))
|
||||
{
|
||||
lParam |= 1u << 24;
|
||||
}
|
||||
|
||||
if (keyUp)
|
||||
{
|
||||
lParam |= (1u << 30) | (1u << 31);
|
||||
}
|
||||
|
||||
// 与原实现 unchecked((nint)0xc01e0001) 一致:按无符号 32 位零扩展
|
||||
return unchecked((nint)lParam);
|
||||
}
|
||||
|
||||
public static int MakeLParam(int x, int y) => (y << 16) | (x & 0xFFFF);
|
||||
|
||||
/// <summary>
|
||||
/// 通知窗口已激活,游戏在后台时需要先发送它,按键和点击才会生效
|
||||
/// </summary>
|
||||
public PostMessageSimulator Activate()
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置并按下左键
|
||||
/// </summary>
|
||||
@@ -32,7 +65,7 @@ public class PostMessageSimulator
|
||||
/// <param name="y"></param>
|
||||
public PostMessageSimulator LeftButtonClick(int x, int y)
|
||||
{
|
||||
IntPtr p = (y << 16) | x;
|
||||
IntPtr p = MakeLParam(x, y);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, IntPtr.Zero, p);
|
||||
Thread.Sleep(100);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONUP, IntPtr.Zero, p);
|
||||
@@ -46,7 +79,7 @@ public class PostMessageSimulator
|
||||
/// <param name="y"></param>
|
||||
public PostMessageSimulator LeftButtonClickBackground(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
Activate();
|
||||
var p = MakeLParam(x, y);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, 1, p);
|
||||
Thread.Sleep(100);
|
||||
@@ -54,25 +87,15 @@ public class PostMessageSimulator
|
||||
return this;
|
||||
}
|
||||
|
||||
public static int MakeLParam(int x, int y) => (y << 16) | (x & 0xFFFF);
|
||||
|
||||
public PostMessageSimulator LeftButtonClick()
|
||||
{
|
||||
IntPtr p = (16 << 16) | 16;
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, IntPtr.Zero, p);
|
||||
Thread.Sleep(100);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONUP, IntPtr.Zero, p);
|
||||
return this;
|
||||
return LeftButtonClick(16, 16);
|
||||
}
|
||||
|
||||
public PostMessageSimulator LeftButtonClickBackground()
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
IntPtr p = (16 << 16) | 16;
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, IntPtr.Zero, p);
|
||||
Thread.Sleep(100);
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONUP, IntPtr.Zero, p);
|
||||
return this;
|
||||
Activate();
|
||||
return LeftButtonClick(16, 16);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -93,6 +116,24 @@ public class PostMessageSimulator
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置左键按下
|
||||
/// </summary>
|
||||
public PostMessageSimulator LeftButtonDown(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, IntPtr.Zero, MakeLParam(x, y));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置左键释放
|
||||
/// </summary>
|
||||
public PostMessageSimulator LeftButtonUp(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, WM_LBUTTONUP, IntPtr.Zero, MakeLParam(x, y));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 默认位置右键按下
|
||||
/// </summary>
|
||||
@@ -111,9 +152,35 @@ public class PostMessageSimulator
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置右键按下
|
||||
/// </summary>
|
||||
public PostMessageSimulator RightButtonDown(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, WM_RBUTTONDOWN, IntPtr.Zero, MakeLParam(x, y));
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置右键释放
|
||||
/// </summary>
|
||||
public PostMessageSimulator RightButtonUp(int x, int y)
|
||||
{
|
||||
User32.PostMessage(_hWnd, WM_RBUTTONUP, IntPtr.Zero, MakeLParam(x, y));
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator RightButtonClick()
|
||||
{
|
||||
IntPtr p = (16 << 16) | 16;
|
||||
return RightButtonClick(16, 16);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定位置右键点击
|
||||
/// </summary>
|
||||
public PostMessageSimulator RightButtonClick(int x, int y)
|
||||
{
|
||||
IntPtr p = MakeLParam(x, y);
|
||||
User32.PostMessage(_hWnd, WM_RBUTTONDOWN, IntPtr.Zero, p);
|
||||
Thread.Sleep(100);
|
||||
User32.PostMessage(_hWnd, WM_RBUTTONUP, IntPtr.Zero, p);
|
||||
@@ -122,64 +189,54 @@ public class PostMessageSimulator
|
||||
|
||||
public PostMessageSimulator KeyPress(User32.VK vk)
|
||||
{
|
||||
//User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, MakeKeyLParam(vk, false));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, MakeKeyLParam(vk, false));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, MakeKeyLParam(vk, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyPress(User32.VK vk, int ms)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, MakeKeyLParam(vk, false));
|
||||
Thread.Sleep(ms);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, MakeKeyLParam(vk, false));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, MakeKeyLParam(vk, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator LongKeyPress(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
Thread.Sleep(1000);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
return this;
|
||||
return KeyPress(vk, 1000);
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyDown(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, MakeKeyLParam(vk, false));
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyUp(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, MakeKeyLParam(vk, true));
|
||||
return this;
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyPressBackground(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_CHAR, (nint)vk, 0x1e0001);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
return this;
|
||||
Activate();
|
||||
return KeyPress(vk);
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyDownBackground(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYDOWN, (nint)vk, 0x1e0001);
|
||||
return this;
|
||||
Activate();
|
||||
return KeyDown(vk);
|
||||
}
|
||||
|
||||
public PostMessageSimulator KeyUpBackground(User32.VK vk)
|
||||
{
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
|
||||
User32.PostMessage(_hWnd, User32.WindowMessage.WM_KEYUP, (nint)vk, unchecked((nint)0xc01e0001));
|
||||
return this;
|
||||
Activate();
|
||||
return KeyUp(vk);
|
||||
}
|
||||
|
||||
public PostMessageSimulator Sleep(int ms)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
@@ -12,8 +12,7 @@ using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using BetterGenshinImpact.GameTask.Model.GameUI;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using Fischless.WindowsInput;
|
||||
using BetterGenshinImpact.Core.Mask;
|
||||
using Microsoft.ClearScript;
|
||||
using Microsoft.ClearScript.V8;
|
||||
using Microsoft.Extensions.Localization;
|
||||
@@ -40,7 +39,7 @@ namespace BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
public class AutoArtifactSalvageTask : ISoloTask
|
||||
{
|
||||
private readonly ILogger logger;
|
||||
private readonly InputSimulator input = Simulation.SendInput;
|
||||
private IInputChannel input => InputHub.Foreground;
|
||||
|
||||
private CancellationToken ct;
|
||||
|
||||
@@ -88,52 +87,9 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
artifactAffixStrDic = ArtifactAffix.DefaultStrDic.Select(kvp => new KeyValuePair<ArtifactAffixType, string>(kvp.Key, stringLocalizer.WithCultureGet(cultureInfo, kvp.Value))).ToFrozenDictionary();
|
||||
}
|
||||
|
||||
public static async Task OpenInventory(GridScreenName gridScreenName, InputSimulator input, ILogger logger, CancellationToken ct)
|
||||
public static async Task OpenInventory(GridScreenName gridScreenName, IInputChannel input, ILogger logger, CancellationToken ct)
|
||||
{
|
||||
RecognitionObject? recognitionObjectChecked;
|
||||
RecognitionObject? recognitionObjectUnchecked;
|
||||
|
||||
switch (gridScreenName)
|
||||
{
|
||||
case GridScreenName.Weapons:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagWeaponChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagWeaponUnchecked");
|
||||
break;
|
||||
case GridScreenName.Artifacts:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagArtifactChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagArtifactUnchecked");
|
||||
break;
|
||||
case GridScreenName.CharacterDevelopmentItems:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagCharacterDevelopmentItemChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagCharacterDevelopmentItemUnchecked");
|
||||
break;
|
||||
case GridScreenName.Food:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagFoodChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagFoodUnchecked");
|
||||
break;
|
||||
case GridScreenName.Materials:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagMaterialChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagMaterialUnchecked");
|
||||
break;
|
||||
case GridScreenName.Gadget:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagGadgetChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagGadgetUnchecked");
|
||||
break;
|
||||
case GridScreenName.Quest:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagQuestChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagQuestUnchecked");
|
||||
break;
|
||||
case GridScreenName.PreciousItems:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagPreciousItemChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagPreciousItemUnchecked");
|
||||
break;
|
||||
case GridScreenName.Furnishings:
|
||||
recognitionObjectChecked = ElementRecognition.Get("BagFurnishingChecked");
|
||||
recognitionObjectUnchecked = ElementRecognition.Get("BagFurnishingUnchecked");
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException($"背包不支持的界面:{gridScreenName.GetDescription()}");
|
||||
}
|
||||
var (recognitionObjectChecked, recognitionObjectUnchecked) = GetTabRecognitionObjects(gridScreenName);
|
||||
|
||||
// B键打开背包
|
||||
input.SimulateAction(GIActions.OpenInventory);
|
||||
@@ -187,6 +143,81 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
await Delay(800, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 取背包分类 tab 的选中/未选中元素识别对象。
|
||||
/// </summary>
|
||||
/// <param name="gridScreenName">目标背包分类。</param>
|
||||
/// <returns>(选中元素, 未选中元素)。</returns>
|
||||
/// <exception cref="NotSupportedException">不支持分类时抛出。</exception>
|
||||
private static (RecognitionObject Checked, RecognitionObject Unchecked) GetTabRecognitionObjects(GridScreenName gridScreenName)
|
||||
{
|
||||
return gridScreenName switch
|
||||
{
|
||||
GridScreenName.Weapons => (ElementRecognition.Get("BagWeaponChecked"), ElementRecognition.Get("BagWeaponUnchecked")),
|
||||
GridScreenName.Artifacts => (ElementRecognition.Get("BagArtifactChecked"), ElementRecognition.Get("BagArtifactUnchecked")),
|
||||
GridScreenName.CharacterDevelopmentItems => (ElementRecognition.Get("BagCharacterDevelopmentItemChecked"), ElementRecognition.Get("BagCharacterDevelopmentItemUnchecked")),
|
||||
GridScreenName.Food => (ElementRecognition.Get("BagFoodChecked"), ElementRecognition.Get("BagFoodUnchecked")),
|
||||
GridScreenName.Materials => (ElementRecognition.Get("BagMaterialChecked"), ElementRecognition.Get("BagMaterialUnchecked")),
|
||||
GridScreenName.Gadget => (ElementRecognition.Get("BagGadgetChecked"), ElementRecognition.Get("BagGadgetUnchecked")),
|
||||
GridScreenName.Quest => (ElementRecognition.Get("BagQuestChecked"), ElementRecognition.Get("BagQuestUnchecked")),
|
||||
GridScreenName.PreciousItems => (ElementRecognition.Get("BagPreciousItemChecked"), ElementRecognition.Get("BagPreciousItemUnchecked")),
|
||||
GridScreenName.Furnishings => (ElementRecognition.Get("BagFurnishingChecked"), ElementRecognition.Get("BagFurnishingUnchecked")),
|
||||
_ => throw new NotSupportedException($"背包不支持的界面:{gridScreenName.GetDescription()}")
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在已打开的背包界面内,切换到目标分类 tab(不返回主界面)。
|
||||
/// 已在目标 tab 则直接返回;否则点击未选中按钮并等待切换完成。
|
||||
/// </summary>
|
||||
/// <param name="targetTab">目标背包分类。</param>
|
||||
/// <param name="input">输入模拟器。</param>
|
||||
/// <param name="logger">日志记录器。</param>
|
||||
/// <param name="ct">取消令牌。</param>
|
||||
public static async Task SwitchInventoryTab(GridScreenName targetTab, IInputChannel input, ILogger logger, CancellationToken ct)
|
||||
{
|
||||
var (checkedObj, uncheckedObj) = GetTabRecognitionObjects(targetTab);
|
||||
|
||||
// 已在目标 tab 则直接返回
|
||||
using (var ra0 = CaptureToRectArea())
|
||||
using (var checkedBtn0 = ra0.Find(checkedObj))
|
||||
{
|
||||
if (checkedBtn0.IsExist())
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 查找并点击未选中按钮
|
||||
bool clicked = false;
|
||||
for (int attempt = 0; attempt < 5; attempt++)
|
||||
{
|
||||
using var ra = CaptureToRectArea();
|
||||
using var uncheckedBtn = ra.Find(uncheckedObj);
|
||||
if (uncheckedBtn.IsExist())
|
||||
{
|
||||
uncheckedBtn.Click();
|
||||
clicked = true;
|
||||
break;
|
||||
}
|
||||
await Delay(300, ct);
|
||||
}
|
||||
|
||||
if (!clicked)
|
||||
{
|
||||
logger.LogError("未找到背包中{name}菜单按钮,切换分类失败", targetTab.GetDescription());
|
||||
return;
|
||||
}
|
||||
|
||||
// 等待目标 tab 变为选中状态
|
||||
var switched = await NewRetry.WaitForElementAppear(checkedObj, retryAction: null, ct, maxAttemptCount: 5, retryInterval: 500);
|
||||
if (!switched)
|
||||
{
|
||||
logger.LogWarning("切换到{name}后未能确认已选中,继续尝试扫描", targetTab.GetDescription());
|
||||
}
|
||||
await Delay(800, ct);
|
||||
}
|
||||
|
||||
public async Task Start(CancellationToken ct)
|
||||
{
|
||||
this.ct = ct;
|
||||
@@ -307,34 +338,31 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
ra5.ClickTo(315, 190);
|
||||
await Delay(1000, ct);
|
||||
// 遍历套装Grid勾选套装
|
||||
using InferenceSession session = GridIconsAccuracyTestTask.LoadModel(out Dictionary<string, float[]> prototypes);
|
||||
using IItemIconRecognizer iconRecognizer = ItemIconRecognizerFactory.CreateConfigured();
|
||||
ArtifactSetFilterScreen gridScreen = new ArtifactSetFilterScreen(new GridParams(new Rect(40, 100, 1300, 852), 2, 3, 40, 40, 0.024), this.logger, this.ct);
|
||||
string drawKey = "ArtifactSetFilter";
|
||||
var drawRectList = new List<RectDrawable>();
|
||||
var drawTextList = new List<TextDrawable>();
|
||||
gridScreen.OnBeforeScroll += () => { VisionContext.Instance().DrawContent.RemoveRect(drawKey); drawRectList.Clear(); drawTextList.Clear(); };
|
||||
var drawShapes = new List<MaskWindowDrawingShape>();
|
||||
gridScreen.OnBeforeScroll += () => { TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.Clear(drawKey); drawShapes.Clear(); };
|
||||
try
|
||||
{
|
||||
await foreach ((ImageRegion pageRegion, Rect itemRect) in gridScreen)
|
||||
{
|
||||
using ImageRegion itemRegion = pageRegion.DeriveCrop(itemRect);
|
||||
using Mat img125 = GetGridIconsTask.CropResizeArtifactSetFilterGridIcon(itemRegion);
|
||||
(string? predName, _) = GridIconsAccuracyTestTask.Infer(img125, session, prototypes);
|
||||
string? predName = iconRecognizer.Recognize(img125);
|
||||
if (predName == null)
|
||||
{
|
||||
var rectDrawable = itemRegion.SelfToRectDrawable(drawKey);
|
||||
drawRectList.Add(rectDrawable);
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(drawKey, drawRectList);
|
||||
drawTextList.Add(new TextDrawable("识别失败", new System.Windows.Point(rectDrawable.Rect.X + rectDrawable.Rect.Width / 3, rectDrawable.Rect.Y)));
|
||||
VisionContext.Instance().DrawContent.TextList.GetOrAdd(drawKey, drawTextList);
|
||||
var rect = itemRegion.SelfToMaskWindowDrawingRect();
|
||||
drawShapes.Add(rect);
|
||||
drawShapes.Add(new MaskWindowDrawingText("识别失败", new System.Windows.Point(rect.Bounds.X + rect.Bounds.Width / 3, rect.Bounds.Y)));
|
||||
itemRegion.DrawingBoard.Set(drawKey, drawShapes);
|
||||
}
|
||||
else
|
||||
{
|
||||
var rectDrawable = itemRegion.SelfToRectDrawable(drawKey, System.Drawing.Pens.Lime);
|
||||
drawRectList.Add(rectDrawable);
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(drawKey, drawRectList);
|
||||
drawTextList.Add(new TextDrawable(predName, new System.Windows.Point(rectDrawable.Rect.X + rectDrawable.Rect.Width / 3, rectDrawable.Rect.Y)));
|
||||
VisionContext.Instance().DrawContent.TextList.GetOrAdd(drawKey, drawTextList);
|
||||
var rect = itemRegion.SelfToMaskWindowDrawingRect(System.Drawing.Pens.Lime);
|
||||
drawShapes.Add(rect);
|
||||
drawShapes.Add(new MaskWindowDrawingText(predName, new System.Windows.Point(rect.Bounds.X + rect.Bounds.Width / 3, rect.Bounds.Y)));
|
||||
itemRegion.DrawingBoard.Set(drawKey, drawShapes);
|
||||
if (this.artifactSetFilter.Contains(predName))
|
||||
{
|
||||
itemRegion.Click();
|
||||
@@ -345,7 +373,7 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
}
|
||||
finally
|
||||
{
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.ClearAll();
|
||||
}
|
||||
// 点击确认筛选
|
||||
using var confirmFilterBtnRegion = CaptureToRectArea();
|
||||
@@ -381,7 +409,7 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
GridParams gridParams = GridParams.Templates[GridScreenName.ArtifactSalvage];
|
||||
GridScreen gridScreen = new GridScreen(gridParams, this.logger, this.ct); // 圣遗物分解Grid有4行9列
|
||||
gridScreen.OnAfterTurnToNewPage += GridScreen.DrawItemsAfterTurnToNewPage;
|
||||
gridScreen.OnBeforeScroll += () => VisionContext.Instance().DrawContent.ClearAll();
|
||||
gridScreen.OnBeforeScroll += () => TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.ClearAll();
|
||||
try
|
||||
{
|
||||
await foreach ((ImageRegion pageRegion, Rect itemRect) in gridScreen)
|
||||
@@ -442,7 +470,7 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
}
|
||||
finally
|
||||
{
|
||||
VisionContext.Instance().DrawContent.ClearAll();
|
||||
TaskContext.Instance().Runtime?.MaskWindowDrawingBoard.ClearAll();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="1星圣遗物" xml:space="preserve">
|
||||
<value>Manufatti.*da.*1★?</value>
|
||||
</data>
|
||||
<data name="2星圣遗物" xml:space="preserve">
|
||||
<value>Manufatti.*da.*2★?</value>
|
||||
</data>
|
||||
<data name="3星圣遗物" xml:space="preserve">
|
||||
<value>Manufatti.*da.*3★?</value>
|
||||
</data>
|
||||
<data name="4星圣遗物" xml:space="preserve">
|
||||
<value>Manufatti.*da.*4★?</value>
|
||||
</data>
|
||||
<data name="元素充能效率" xml:space="preserve">
|
||||
<value>Ricarica di energia</value>
|
||||
</data>
|
||||
<data name="元素精通" xml:space="preserve">
|
||||
<value>Maestria elementale</value>
|
||||
</data>
|
||||
<data name="冰元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Cryo</value>
|
||||
</data>
|
||||
<data name="岩元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Geo</value>
|
||||
</data>
|
||||
<data name="快速选择" xml:space="preserve">
|
||||
<value>Selezione.*rapida</value>
|
||||
</data>
|
||||
<data name="攻击力" xml:space="preserve">
|
||||
<value>ATT</value>
|
||||
</data>
|
||||
<data name="暴击伤害" xml:space="preserve">
|
||||
<value>DAN da CRIT</value>
|
||||
</data>
|
||||
<data name="暴击率" xml:space="preserve">
|
||||
<value>Tasso di CRIT</value>
|
||||
</data>
|
||||
<data name="水元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Hydro</value>
|
||||
</data>
|
||||
<data name="治疗加成" xml:space="preserve">
|
||||
<value>Bonus di guarigione</value>
|
||||
</data>
|
||||
<data name="火元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Pyro</value>
|
||||
</data>
|
||||
<data name="物理伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN fisici</value>
|
||||
</data>
|
||||
<data name="生命值" xml:space="preserve">
|
||||
<value>PS</value>
|
||||
</data>
|
||||
<data name="草元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Dendro</value>
|
||||
</data>
|
||||
<data name="防御力" xml:space="preserve">
|
||||
<value>DIF</value>
|
||||
</data>
|
||||
<data name="雷元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Electro</value>
|
||||
</data>
|
||||
<data name="风元素伤害加成" xml:space="preserve">
|
||||
<value>Bonus DAN da Anemo</value>
|
||||
</data>
|
||||
</root>
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"info": {
|
||||
"authors": [
|
||||
{
|
||||
"links": "https://github.com/1004452714",
|
||||
"name": "DarkFlameMaster"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"enable_monster_loot_split": false,
|
||||
"last_modified_time": 1790158274226,
|
||||
"map_match_method": "TemplateMatch",
|
||||
"map_name": "Teyvat",
|
||||
"name": "不灭衍生造物前往",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport",
|
||||
"x": 7164.0811,
|
||||
"y": 9309.9551
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 7165.3457,
|
||||
"y": 9326.8311
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 7165.3096,
|
||||
"y": 9347.4238
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 4,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 7213.6914,
|
||||
"y": 9415.123
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"info": {
|
||||
"authors": [
|
||||
{
|
||||
"links": "https://github.com/1004452714",
|
||||
"name": "DarkFlameMaster"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"enable_monster_loot_split": false,
|
||||
"last_modified_time": 1786528552840,
|
||||
"map_match_method": "SIFT",
|
||||
"map_name": "Teyvat",
|
||||
"name": "嵌合翼骏狮前往",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport",
|
||||
"x": 8250.2588,
|
||||
"y": 8158.9434
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 8284.0762,
|
||||
"y": 8123.4551
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,94 +1,94 @@
|
||||
{
|
||||
"info": {
|
||||
"name": "无相之草前往",
|
||||
"type": "collect",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Tool_tingsu",
|
||||
"links": ""
|
||||
"links": "https://github.com/1004452714",
|
||||
"name": "DarkFlameMaster"
|
||||
}
|
||||
],
|
||||
"version": "1.0",
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"map_name": "Teyvat",
|
||||
"bgi_version": "0.52.0",
|
||||
"enable_monster_loot_split": false,
|
||||
"last_modified_time": 1788835720032,
|
||||
"map_match_method": "TemplateMatch",
|
||||
"map_name": "Teyvat",
|
||||
"name": "无相之草前往",
|
||||
"tags": [],
|
||||
"last_modified_time": 1753788793031,
|
||||
"enable_monster_loot_split": false
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"x": 4036.58203125,
|
||||
"y": -2464.6328125,
|
||||
"move_mode": "walk",
|
||||
"type": "teleport",
|
||||
"move_mode": "walk",
|
||||
"action": "",
|
||||
"action_params": ""
|
||||
"x": 4036.583,
|
||||
"y": -2464.6309
|
||||
},
|
||||
{
|
||||
"action": "log_output",
|
||||
"action_params": "洞口会小概率坐标识别错,为追求稳定,不使用四叶印",
|
||||
"id": 2,
|
||||
"x": 4032.9716796875,
|
||||
"y": -2476.08203125,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": "",
|
||||
"action_params": ""
|
||||
"type": "path",
|
||||
"x": 4026.0117,
|
||||
"y": -2474.8037
|
||||
},
|
||||
{
|
||||
"action": "stop_flying",
|
||||
"action_params": "1000",
|
||||
"id": 3,
|
||||
"x": 4020.458984375,
|
||||
"y": -2489.951171875,
|
||||
"type": "path",
|
||||
"move_mode": "fly",
|
||||
"action": "stop_flying",
|
||||
"action_params": "1000"
|
||||
"type": "path",
|
||||
"x": 4015.2695,
|
||||
"y": -2483.1543
|
||||
},
|
||||
{
|
||||
"action": "combat_script",
|
||||
"action_params": "wait(1)",
|
||||
"id": 4,
|
||||
"x": 4004.5302734375,
|
||||
"y": -2468.169921875,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": "up_down_grab_leaf",
|
||||
"action_params": ""
|
||||
"type": "path",
|
||||
"x": 4011.8594,
|
||||
"y": -2472.1455
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 5,
|
||||
"x": 4003.3828125,
|
||||
"y": -2441.16796875,
|
||||
"move_mode": "run",
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": "up_down_grab_leaf",
|
||||
"action_params": ""
|
||||
"x": 3999.5293,
|
||||
"y": -2436.6504
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 6,
|
||||
"x": 3986.103515625,
|
||||
"y": -2428.77734375,
|
||||
"move_mode": "run",
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": "up_down_grab_leaf",
|
||||
"action_params": ""
|
||||
"x": 3977.2295,
|
||||
"y": -2414.6641
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"x": 3975.9375,
|
||||
"y": -2412.4384765625,
|
||||
"type": "path",
|
||||
"move_mode": "walk",
|
||||
"action": "up_down_grab_leaf",
|
||||
"action_params": ""
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"x": 3902.85546875,
|
||||
"y": -2437.8798828125,
|
||||
"type": "path",
|
||||
"move_mode": "fly",
|
||||
"action": "stop_flying",
|
||||
"action_params": ""
|
||||
"action_params": "",
|
||||
"id": 7,
|
||||
"move_mode": "fly",
|
||||
"type": "path",
|
||||
"x": 3923.5967,
|
||||
"y": -2431.9766
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 8,
|
||||
"move_mode": "run",
|
||||
"type": "path",
|
||||
"x": 3902.0371,
|
||||
"y": -2438.2422
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
{
|
||||
"info": {
|
||||
"authors": [
|
||||
{
|
||||
"links": "https://github.com/1004452714",
|
||||
"name": "DarkFlameMaster"
|
||||
}
|
||||
],
|
||||
"bgi_version": "0.45.0",
|
||||
"description": "",
|
||||
"enable_monster_loot_split": false,
|
||||
"last_modified_time": 1792010524557,
|
||||
"map_match_method": "TemplateMatch",
|
||||
"map_name": "Teyvat",
|
||||
"name": "游雪的护刃前往",
|
||||
"tags": [],
|
||||
"type": "collect",
|
||||
"version": "1.0"
|
||||
},
|
||||
"positions": [
|
||||
{
|
||||
"action": "force_tp",
|
||||
"action_params": "",
|
||||
"id": 1,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"point_ext_params": {
|
||||
"description": "",
|
||||
"misidentification": {
|
||||
"arrival_time": 0,
|
||||
"handling_mode": "mapRecognition",
|
||||
"type": [
|
||||
"unrecognized",
|
||||
"pathTooFar"
|
||||
]
|
||||
},
|
||||
"monster_tag": ""
|
||||
},
|
||||
"type": "teleport",
|
||||
"x": 6278.2637,
|
||||
"y": 7655.835
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 2,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"point_ext_params": {
|
||||
"description": "",
|
||||
"misidentification": {
|
||||
"arrival_time": 0,
|
||||
"handling_mode": "mapRecognition",
|
||||
"type": [
|
||||
"unrecognized",
|
||||
"pathTooFar"
|
||||
]
|
||||
},
|
||||
"monster_tag": ""
|
||||
},
|
||||
"type": "path",
|
||||
"x": 6248.4414,
|
||||
"y": 7674.5337
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 3,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"point_ext_params": {
|
||||
"description": "",
|
||||
"misidentification": {
|
||||
"arrival_time": 0,
|
||||
"handling_mode": "mapRecognition",
|
||||
"type": [
|
||||
"unrecognized",
|
||||
"pathTooFar"
|
||||
]
|
||||
},
|
||||
"monster_tag": ""
|
||||
},
|
||||
"type": "path",
|
||||
"x": 6228.9082,
|
||||
"y": 7706.9521
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 4,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 6214.4238,
|
||||
"y": 7720.5264
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 5,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 6206.293,
|
||||
"y": 7768.3086
|
||||
},
|
||||
{
|
||||
"action": "",
|
||||
"action_params": "",
|
||||
"id": 6,
|
||||
"locked": false,
|
||||
"move_mode": "walk",
|
||||
"type": "path",
|
||||
"x": 6202.0068,
|
||||
"y": 7781.3105
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -22,7 +22,8 @@ public static class AutoBossData
|
||||
["须弥"] = ["掣电树", "半永恒统辖矩阵", "翠翎恐蕈", "风蚀沙虫", "无相之草", "深罪浸礼者", "兆载永劫龙兽"],
|
||||
["枫丹"] = ["歌裴莉娅的葬送", "科培琉司的劫罚", "实验性场力发生装置", "魔像督军", "千年珍珠骏麟", "水形幻人", "铁甲熔火帝皇"],
|
||||
["纳塔"] = ["金焰绒翼龙暴君", "灵觉隐修的迷者", "秘源机兵·构型械", "秘源机兵·统御械", "熔岩辉龙像", "深邃摹结株", "贪食匿叶龙山王"],
|
||||
["挪德卡莱"] = ["蕴光月守宫", "深黯魇语之主", "超重型陆巡舰·机动战垒", "霜夜巡天灵主", "蕴光月幻蝶", "重拳出击鸭"]
|
||||
["挪德卡莱"] = ["蕴光月守宫", "深黯魇语之主", "超重型陆巡舰·机动战垒", "霜夜巡天灵主", "蕴光月幻蝶", "重拳出击鸭"],
|
||||
["至冬"] = ["不灭衍生造物", "嵌合翼骏狮", "游雪的护刃"]
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
@@ -53,6 +54,14 @@ public static class AutoBossData
|
||||
"蕴光月幻蝶"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 战斗后需要重新执行完整前往路线的 Boss。
|
||||
/// </summary>
|
||||
public static readonly HashSet<string> RerunRouteBosses =
|
||||
[
|
||||
"不灭衍生造物"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 判断 Boss 是否在支持列表中。
|
||||
/// </summary>
|
||||
@@ -82,4 +91,12 @@ public static class AutoBossData
|
||||
{
|
||||
return NoPathingSupportBosses.Contains(bossName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断 Boss 战斗后是否需要重新执行完整前往路线。
|
||||
/// </summary>
|
||||
public static bool ShouldRerunRoute(string bossName)
|
||||
{
|
||||
return RerunRouteBosses.Contains(bossName);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
|
||||
@@ -91,7 +92,12 @@ public class AutoBossParam : BaseTaskParam<AutoBossTask>
|
||||
/// 战斗超时
|
||||
/// </summary>
|
||||
public int Timeout { get; set; } = 240;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 每次成功领取奖励后的回调,仅供一条龙持久化累计成功次数。
|
||||
/// </summary>
|
||||
internal Action? RewardClaimedCallback { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 使用当前全局 AutoBoss 配置创建参数,主要用于 JS 无参构造和一条龙默认启动。
|
||||
/// </summary>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
using BetterGenshinImpact.Core.Input;
|
||||
using BetterGenshinImpact.Core.BgiVision;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
@@ -50,6 +50,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
private readonly Dictionary<string, int> _rewardSummary = new();
|
||||
private SwitchPartyTask? _switchPartyTask;
|
||||
private CancellationToken _ct;
|
||||
private int _successfulRewardCount;
|
||||
|
||||
private static readonly TimeSpan OriginalResinRecoveryInterval = TimeSpan.FromMinutes(8);
|
||||
private const int MaxQuickUseQuantity = 20;
|
||||
@@ -59,9 +60,23 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
private double AssetScale => TaskContext.Instance().SystemInfo.AssetScale;
|
||||
|
||||
private static RecognitionObject LoadRecognitionObject(string objectName)
|
||||
{
|
||||
return LoadRecognitionObject("AutoBoss", objectName);
|
||||
}
|
||||
|
||||
private static RecognitionObject LoadRecognitionObject(string taskName, string objectName)
|
||||
{
|
||||
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
return RecognitionAssets.Get("AutoBoss", objectName, captureRect.Width, captureRect.Height);
|
||||
return RecognitionAssets.Get(taskName, objectName, captureRect.Width, captureRect.Height);
|
||||
}
|
||||
|
||||
private static BvLocator[] BuildBigMapLocators(BvPage page)
|
||||
{
|
||||
return
|
||||
[
|
||||
page.Locator(LoadRecognitionObject("QuickTeleport", "MapScaleButton")),
|
||||
page.Locator(LoadRecognitionObject("QuickTeleport", "MapSettingsButton"))
|
||||
];
|
||||
}
|
||||
|
||||
private sealed record OriginalResinInfo(int Count, int Limit);
|
||||
@@ -101,6 +116,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
{
|
||||
_ct = ct;
|
||||
_rewardSummary.Clear();
|
||||
_successfulRewardCount = 0;
|
||||
Validate();
|
||||
LogScreenResolution();
|
||||
|
||||
@@ -130,8 +146,8 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
}
|
||||
finally
|
||||
{
|
||||
Simulation.ReleaseAllKey();
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
InputHub.ReleaseAll();
|
||||
InputHub.Foreground.Mouse.LeftButtonUp();
|
||||
Notify.Event("AutoBoss").Success($"{Name}结束");
|
||||
}
|
||||
|
||||
@@ -146,13 +162,12 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
// 1.切换队伍
|
||||
await Prepare();
|
||||
|
||||
var rewardCount = 0;
|
||||
var shouldNavigateToBoss = true;
|
||||
//2.根据剩余次数判断是否继续
|
||||
while (ShouldContinueBeforeRound(rewardCount))
|
||||
while (ShouldContinueBeforeRound())
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
_logger.LogInformation("{Name}:开始第 {Round} 次讨伐 {Boss}", Name, rewardCount + 1, _taskParam.BossName);
|
||||
_logger.LogInformation("{Name}:开始第 {Round} 次讨伐 {Boss}", Name, _successfulRewardCount + 1, _taskParam.BossName);
|
||||
|
||||
//3.树脂不足则退出
|
||||
if (!await EnsureResinBeforeRound())
|
||||
@@ -181,8 +196,9 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
break;
|
||||
}
|
||||
|
||||
rewardCount++;
|
||||
if (!ShouldContinueBeforeRound(rewardCount))
|
||||
_successfulRewardCount++;
|
||||
_taskParam.RewardClaimedCallback?.Invoke();
|
||||
if (!ShouldContinueBeforeRound())
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -206,11 +222,10 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
/// <summary>
|
||||
/// 判断本轮开始前是否还有继续讨伐的次数。
|
||||
/// </summary>
|
||||
/// <param name="rewardCount">本次任务已成功领取奖励的次数。</param>
|
||||
/// <returns>树脂耗尽模式始终返回 true;指定次数模式下未达到目标次数时返回 true。</returns>
|
||||
private bool ShouldContinueBeforeRound(int rewardCount)
|
||||
private bool ShouldContinueBeforeRound()
|
||||
{
|
||||
return !_taskParam.SpecifyRunCount || rewardCount < _taskParam.RunCount;
|
||||
return !_taskParam.SpecifyRunCount || _successfulRewardCount < _taskParam.RunCount;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -221,7 +236,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
{
|
||||
try
|
||||
{
|
||||
await OpenBigMapForResinCheck();
|
||||
await _returnMainUiTask.Start(_ct);
|
||||
|
||||
OriginalResinInfo originalResin;
|
||||
try
|
||||
@@ -266,72 +281,47 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用用户配置的打开地图按键进入大地图,识别右上角原粹树脂数量,并在结束后回到主界面。
|
||||
/// 打开大地图并通过树脂详情中的全部恢复时间反推当前原粹树脂。
|
||||
/// </summary>
|
||||
/// <returns>识别到的原粹树脂数量;识别失败时返回 null。</returns>
|
||||
private async Task<int?> TryRecognizeOriginalResinCountInBigMap()
|
||||
{
|
||||
try
|
||||
{
|
||||
await OpenBigMapForResinCheck();
|
||||
try
|
||||
{
|
||||
var originalResin = await RecognizeOriginalResinInfoFromBigMap();
|
||||
return originalResin.Count;
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException)
|
||||
{
|
||||
_logger.LogWarning("{Name}:战前原粹树脂预检失败,将继续通过领奖界面兜底,原因:{Reason}", Name, e.Message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await _returnMainUiTask.Start(_ct);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 释放输入并打开大地图界面,用于在右上角读取原粹树脂数量。
|
||||
/// </summary>
|
||||
private async Task OpenBigMapForResinCheck()
|
||||
{
|
||||
await new TpTask(_ct).OpenBigMapUi();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AutoBoss 专用大地图原粹树脂识别:点击右上角树脂图标后,通过全部恢复时间反推剩余树脂。
|
||||
/// </summary>
|
||||
/// <returns>当前剩余原粹树脂。</returns>
|
||||
private async Task<OriginalResinInfo> RecognizeOriginalResinInfoFromBigMap()
|
||||
{
|
||||
using var capture = CaptureToRectArea();
|
||||
using var resinIconSearchRegion = capture.DeriveCrop(ScaleRect(1200, 25, 580, 50));
|
||||
var resinIconRegion = resinIconSearchRegion.Find(LoadRecognitionObject("OriginalResinTopIcon"));
|
||||
if (resinIconRegion.IsEmpty())
|
||||
{
|
||||
throw new InvalidOperationException("未找到原粹树脂图标");
|
||||
}
|
||||
|
||||
var iconLeft = resinIconSearchRegion.X + resinIconRegion.Left;
|
||||
var iconRight = resinIconSearchRegion.X + resinIconRegion.Right;
|
||||
var iconBottom = resinIconSearchRegion.Y + resinIconRegion.Bottom;
|
||||
|
||||
resinIconRegion.Click();
|
||||
await Delay(500, _ct);
|
||||
var page = new BvPage(_ct);
|
||||
//树脂图标
|
||||
var resinIconLocator = page
|
||||
.Locator(LoadRecognitionObject("OriginalResinTopIcon"))
|
||||
.WithRoi(ScaleRect(1200, 25, 580, 50));
|
||||
|
||||
await page.Flow()
|
||||
.Do((Action)(() =>
|
||||
{
|
||||
using var capture = CaptureToRectArea();
|
||||
if (!Bv.IsInBigMapUi(capture))
|
||||
{
|
||||
InputHub.Foreground.SimulateAction(GIActions.OpenMap);
|
||||
}
|
||||
}))
|
||||
.UntilAny(BuildBigMapLocators(page))
|
||||
.WaitUntil(resinIconLocator)
|
||||
.Click().UntilAnyText(new[] { "全部恢复", "原粹树脂已完全恢复" }, ScaleRect(1180, 75, 620, 200))
|
||||
.Run();
|
||||
|
||||
//根据树脂图标位置偏移,计算出体力恢复时间的弹窗位置
|
||||
var resinIconRegion = (await resinIconLocator.WaitFor()).First();
|
||||
var detailRect = new Rect(resinIconRegion.Left - 13, resinIconRegion.Bottom + 29, 220, 150);
|
||||
|
||||
//根据弹窗位置 OCR 出当前树脂上限和全部恢复时间,反推当前原粹树脂
|
||||
using var clickedCapture = CaptureToRectArea();
|
||||
var resinLimit = RecognizeOriginalResinLimit(clickedCapture, iconRight);
|
||||
var fullRecoveryTime = RecognizeFullRecoveryTime(clickedCapture, iconLeft, iconBottom);
|
||||
var resinLimit = RecognizeOriginalResinLimit(clickedCapture, resinIconRegion.Right);
|
||||
var fullRecoveryTime = RecognizeFullRecoveryTime(clickedCapture, detailRect);
|
||||
var missingResin = (int)Math.Ceiling(fullRecoveryTime.TotalSeconds / OriginalResinRecoveryInterval.TotalSeconds);
|
||||
if (missingResin > resinLimit)
|
||||
{
|
||||
throw new InvalidOperationException($"计算缺失树脂 {missingResin} 超过树脂上限 {resinLimit}");
|
||||
}
|
||||
|
||||
var originalResin = resinLimit - missingResin;
|
||||
_logger.LogInformation("{Name}:剩余树脂 {Count}", Name, originalResin);
|
||||
return new OriginalResinInfo(originalResin, resinLimit);
|
||||
var originalResin = new OriginalResinInfo(resinLimit - missingResin, resinLimit);
|
||||
_logger.LogInformation("{Name}:剩余树脂 {Count}", Name, originalResin.Count);
|
||||
return originalResin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -361,14 +351,8 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
/// <summary>
|
||||
/// 读取树脂详情弹窗中的全部恢复时间;已完全恢复时返回零时长。
|
||||
/// </summary>
|
||||
private TimeSpan RecognizeFullRecoveryTime(ImageRegion capture, int resinIconLeft, int resinIconBottom)
|
||||
private TimeSpan RecognizeFullRecoveryTime(ImageRegion capture, Rect detailRect)
|
||||
{
|
||||
// 该偏移来自截图实际像素,不随 AssetScale 缩放。
|
||||
var detailRect = new Rect(
|
||||
resinIconLeft - 13,
|
||||
resinIconBottom + 29,
|
||||
220,
|
||||
150);
|
||||
using var detailRegion = capture.DeriveCrop(detailRect);
|
||||
var result = OcrFactory.Paddle.OcrResult(detailRegion.SrcMat);
|
||||
var text = string.Concat(result.Regions
|
||||
@@ -845,32 +829,6 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
return Regex.Replace(normalized, @"\s+", "");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 多次尝试识别当前队伍角色并初始化战斗场景。
|
||||
/// </summary>
|
||||
/// <returns>已成功识别队伍的战斗场景。</returns>
|
||||
/// <exception cref="Exception">连续多次识别队伍失败时抛出。</exception>
|
||||
private CombatScenes GetCombatScenesWithRetry()
|
||||
{
|
||||
const int maxRetries = 5;
|
||||
for (var attempt = 1; attempt <= maxRetries; attempt++)
|
||||
{
|
||||
_ct.ThrowIfCancellationRequested();
|
||||
var combatScenes = new CombatScenes().InitializeTeam(CaptureToRectArea());
|
||||
if (combatScenes.CheckTeamInitialized())
|
||||
{
|
||||
return combatScenes;
|
||||
}
|
||||
|
||||
if (attempt < maxRetries)
|
||||
{
|
||||
Sleep(1000, _ct);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception("识别队伍角色失败(已重试 5 次)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据当前队伍匹配战斗脚本,并切换到脚本中的首个角色。
|
||||
/// </summary>
|
||||
@@ -904,7 +862,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
}
|
||||
else
|
||||
{
|
||||
var combatScenes = GetCombatScenesWithRetry();
|
||||
var combatScenes = CombatScenes.GetCombatScenesWithRetry();
|
||||
FindCombatScriptAndSwitchAvatar(combatScenes);
|
||||
|
||||
var taskParam = BuildAutoFightParamForBoss();
|
||||
@@ -1221,9 +1179,9 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
// The main loop observes task failures; shutdown also cancels background tasks.
|
||||
}
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveRight, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveRight, KeyType.KeyUp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1259,7 +1217,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
{
|
||||
if (DateTime.UtcNow - lastInteractAt >= TimeSpan.FromMilliseconds(300))
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.PickUpOrInteract);
|
||||
InputHub.Foreground.SimulateAction(GIActions.PickUpOrInteract);
|
||||
lastInteractAt = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
@@ -1285,7 +1243,7 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
if (boxRegions.Count < 1)
|
||||
{
|
||||
_logger.LogWarning("{Name}:未找到征讨之花图标,调整视角重试", Name);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(ScaleX(200), 0);
|
||||
InputHub.Foreground.Mouse.MoveMouseBy(ScaleX(200), 0);
|
||||
await Delay(250, ct);
|
||||
continue;
|
||||
}
|
||||
@@ -1294,16 +1252,16 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
|
||||
if (icon.Y > halfHeight)
|
||||
{
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(0, (int)Math.Round(halfHeight));
|
||||
InputHub.Foreground.Mouse.MoveMouseBy(0, (int)Math.Round(halfHeight));
|
||||
await Delay(125, ct);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(centerX), 0);
|
||||
InputHub.Foreground.Mouse.MoveMouseBy((int)Math.Round(centerX), 0);
|
||||
await Delay(125, ct);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (icon.X < minTargetX || icon.X > maxTargetX)
|
||||
{
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(icon.X - centerX), 0);
|
||||
InputHub.Foreground.Mouse.MoveMouseBy((int)Math.Round(icon.X - centerX), 0);
|
||||
}
|
||||
|
||||
await Delay(250, ct);
|
||||
@@ -1326,22 +1284,22 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
{
|
||||
if (isMovingForward)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
isMovingForward = false;
|
||||
}
|
||||
|
||||
_logger.LogInformation("{Name}:检测到攀爬状态,尝试脱离", Name);
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
InputHub.Foreground.SimulateAction(GIActions.Drop);
|
||||
await Delay(1000, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyDown);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveLeft, KeyType.KeyDown);
|
||||
await Delay(800, ct);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isMovingForward)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
isMovingForward = true;
|
||||
}
|
||||
|
||||
@@ -1349,19 +1307,19 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
jumpCount++;
|
||||
if (jumpCount % 2 == 0)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.Jump);
|
||||
InputHub.Foreground.SimulateAction(GIActions.Jump);
|
||||
await Delay(100, ct);
|
||||
}
|
||||
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
isMovingForward = false;
|
||||
await Delay(200, ct);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
|
||||
InputHub.Foreground.SimulateAction(GIActions.MoveLeft, KeyType.KeyUp);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1556,6 +1514,13 @@ public class AutoBossTask : ISoloTask<Dictionary<string, int>>
|
||||
return;
|
||||
}
|
||||
|
||||
if (AutoBossData.ShouldRerunRoute(_taskParam.BossName))
|
||||
{
|
||||
_logger.LogInformation("{Name}:重新执行完整路线靠近首领", Name);
|
||||
await RunPathingFile($"{_taskParam.BossName}前往.json");
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("{Name}:重新靠近首领位置并等待 4 秒", Name);
|
||||
var routePath = BuildPathingAssetPath($"{_taskParam.BossName}前往.json");
|
||||
var originalTask = PathingTask.BuildFromFilePath(routePath) ?? throw new Exception($"路径文件解析失败:{routePath}");
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.View.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoCombo;
|
||||
|
||||
/// <summary>
|
||||
/// 自动连招行为树浮窗显隐服务:持有浮窗单例并管理其生命周期(重建、Show/Hide)
|
||||
/// </summary>
|
||||
public class AutoComboTreeWindowService : Singleton<AutoComboTreeWindowService>
|
||||
{
|
||||
private AutoComboTreeWindow? _window;
|
||||
|
||||
/// <summary>显示行为树浮窗(重复调用安全)</summary>
|
||||
public void Show()
|
||||
{
|
||||
// 独立任务在后台线程调用,统一调度到 UI 线程
|
||||
UIDispatcherHelper.Invoke(() =>
|
||||
{
|
||||
if (_window is null)
|
||||
{
|
||||
_window = new AutoComboTreeWindow();
|
||||
_window.Closed += (_, _) => _window = null;
|
||||
}
|
||||
|
||||
_window.Show();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>隐藏行为树浮窗(窗口未创建/已关闭时安全)</summary>
|
||||
public void Hide()
|
||||
{
|
||||
UIDispatcherHelper.Invoke(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
_window?.Hide();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 窗口已关闭或释放时忽略
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Loaded 100 of 552 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user