Compare commits

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

No files matched your search

-169
View File
@@ -1,169 +0,0 @@
---
name: "release-note-generator"
description: "基于 BetterGI 本地 git 历史和实际 diff,按 GitHub 已发布 Releases 的中文更新日志风格生成发布说明。用于生成 Release Note、版本更新日志、从上一个非 alpha 正式版本到 HEAD 的变更汇总;不得使用 git tag 作为版本依据。"
---
# Release Note Generator
基于本地 git 历史和实际代码 diff 生成 BetterGI 发布说明。发布说明的结构、分类和措辞应贴近 GitHub 已发布 Releases 的历史风格;生成具体内容时不依赖网络,所有变更信息从本地仓库获取。
## 触发时机
- 用户要求生成 Release Note / 更新日志
- 用户要求基于最近提交和实际代码变更做汇总
## 历史 Release 风格
已发布日志的稳定特征:
- 标题通常为 `## <version> <简短主题>`,例如 `0.61.0 原神6.6`、`0.61.2 优化`、`0.60.1 修复老问题`、`0.59 自动烹饪与BUG修复`。
- 大版本或内容较多时,标题下可有一句总览;补丁版本或内容很少时可以直接列 bullet。
- 分类标题使用项目语义,而不是 Conventional Commits 类型。常见分类包括:`版本适配` / `<月之X适配>`、`自动战斗`、`地图追踪`、`地图遮罩`、`独立任务`、`JS脚本` / `JS相关`、`实时任务`、`自动剧情`、`其他`。
- 版本适配类通常放在最前面,包含新角色识别、新地图、传送点/锚点、七圣召唤元数据等。
- `其他` 分类保留,用于 UI、通知、配置、稳定性、OCR、启动器、仓库、文档等无法归入核心模块的内容。
- 条目语言偏简洁直白,可以用“新增/修复/优化/支持/更新/回滚/适配”,不需要营销化。
- PR 号与作者使用纯文本,例如 `(#3132) @haokaiyang`;多个 PR 可以写在同一括号组里,例如 `(#3101 #3108)`。
- 不输出 GitHub 自动生成的 `Contributors`、`Assets`、reaction 等区块。
## 版本边界
禁止执行或参考 `git tag`、`git describe --tags`。版本边界和输出版本号都不能使用 tag 作为依据。
从 HEAD 向后遍历提交历史,匹配**明确以版本号发布为主题的提交**:
- 提交消息必须匹配以下模式之一(大小写不敏感):
- `Update version to X.Y.Z`
- `bump version to X.Y.Z`
- `release X.Y.Z`
- `vX.Y.Z`
- 版本号正则:`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?`
- 版本号**必须是提交消息的核心主题**,不能只是顺带提及(如 "fix: update package version to 1.0.19" 这种子包更新不算)
- 排除包含 `alpha` 的提交
- 排除仅更新子包/依赖版本的提交
### 通用规则
- 统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入
- 如果 HEAD 附近已经存在当前目标版本的正式版本提交,不要把它作为边界;继续向父提交方向寻找上一个正式版本提交
- 若未找到边界版本,明确说明并使用兜底范围
## 信息采集
### 提交列表
- 使用 `git -c i18n.logOutputEncoding=utf8 -c core.quotepath=false log` 获取提交序列
- 格式:`--pretty=format:"%H%x00%h%x00%an%x00%ae%x00%s%x00%b%x1e"`,字段用 `\x00` 分隔,commit 用 `\x1e` 分隔
- 先用 `git rev-list --count` 取总数,采集后校验一致性
- 读取 commit body,用于提取 `Co-authored-by`、正文中的 PR/Issue 号和补充说明
### Diff 查阅(必须)
- 对每个 commit 必须查阅实际 diff:`git diff <sha>~1..<sha>`
- **不允许仅基于 commit 消息生成说明**,必须结合实际代码改动理解变更内容
- 同一功能的新增 + 后续优化/修复应合并为一条,只记"新增 xxx"
### 作者信息
- 所有作者名前统一加 `@` 前缀
- 从 commit 的 `author email` 解析标识:
- `数字[email protected]` → `@login`
- `[email protected]` → `@login`
- `[email protected]` 等非 noreply 邮箱 → `@author name`(即提交中的 `an` 字段值前加 `@`)
- 从 commit body 的 `Co-authored-by: name <email>` 提取共同作者,并按同样规则解析
- 当作者为 `huiyadanli`(含邮箱 `[email protected]`)时省略 `@author`(项目维护者,无需标注)
- 不需要调用 GitHub API,纯本地解析
## 内容提炼规则
### 合并策略
- 同一功能在同一版本周期内先新增后优化/修复的,只保留"新增 xxx",不单独列优化
- 同一 issue/PR 的多个 commit 合并为一条记录
- 同一文件或模块的多次小改动合并为一条有意义的描述
- 可省略纯内部重构、CI、调试日志清理、无用户影响的格式化,但这些 commit 仍必须被检查并纳入内部覆盖记录
### 分类
优先使用以下历史 Release 常见分类,按顺序输出。只有对应分类下有变更时才输出该分类标题,无变更则跳过不输出。
分类来源于项目已发布 GitHub Releases,与项目实际使用习惯对齐:
| 分类名 | 对应项目模块 | 覆盖范围 |
|--------|-------------|---------|
| 版本适配 / `<月之X适配>` | `Assets/` `AutoFight/Assets/` `AutoGeniusInvokation/Assets/` `AutoTrackPath/Assets/` | 新角色识别数据、新地图添加、传送点/锚点数据更新、七圣召唤角色牌等元数据更新 |
| 自动战斗 | `GameTask/AutoFight` `GameTask/Macro` `GameTask/SkillCd` | 战斗策略、角色切换、技能释放与CD、一键宏、经验值拾取、战后拾取、游泳检测、角色数据(非版本适配类) |
| 地图追踪 | `GameTask/AutoPathing` `GameTask/AutoTrackPath` `GameTask/MapMask` | 路径执行与所有路径处理器(含莉奈娅挖矿、拾取、采矿等 Handler)、地图类型、传送逻辑、地图编辑器(MapPathingPage、MapEditorWebBridge) |
| 地图遮罩 | `GameTask/MapMask` `View/MaskWindow*` `ViewModel/MaskWindow*` `Core/Config/MaskWindowConfig*` | 地图遮罩、日志遮罩、遮罩指标栏、遮罩位置和实时展示 |
| 独立任务 | `GameTask/AutoLeyLineOutcrop` `GameTask/AutoDomain` `GameTask/AutoBoss` `GameTask/AutoStygianOnslaught` `GameTask/AutoCook` `GameTask/AutoWood` `GameTask/AutoFishing` `GameTask/FarmingPlan` `GameTask/AutoSkip` `GameTask/QuickSereniteaPot` | 地脉花、秘境、首领讨伐、幽境危战、烹饪、伐木、钓鱼、养成计划、自动剧情、快速尘歌壶等独立运行的任务 |
| JS脚本 | `Core/Script` `Core/BgiVision` | JS 脚本 API、BvLocator、HTML 遮罩、模块导入、v8 引擎、脚本项目 |
| 实时任务 | `GameTask/TaskTriggerDispatcher*` `GameTask/AutoPick` `GameTask/AutoEat` `GameTask/Common` | 自动拾取、自动吃药、自动跳过、实时触发器、进入游戏与界面检测等 |
| 其他 | — | 无法归入以上分类的杂项(必须保留,即使为空也输出) |
- 归类原则:按**变更所属的项目模块(代码所在目录)**划分,而非按变更类型(新增/修复/优化)或用户感知的子功能划分
- 当一个变更涉及多个模块时,归入其主要逻辑所在的模块
- 版本适配类命名:若能从变更或用户要求明确对应原神版本/月之版本,可用 `<月之X适配>`;否则使用 `版本适配`
- 仅当本轮有多个明确的新功能且难以归入既有模块时,才使用 `新功能`
- 若某项变更无法明确归入上述分类,放入"其他"
- 遇到历史分类未覆盖的新模块,允许 AI 自行新建分类(放在"其他"之前),但分类名必须是项目语义,不要使用 `feat/fix/refactor`
每条记录格式:
```
描述内容 (#PR号) @author
```
- PR 号和作者名均使用纯文本,不加超链接
- 当作者为 `huiyadanli` 时省略 `@author`(项目维护者,无需标注)
- 描述用自然语言,不直接复制 commit 原文
- 移除 `feat:`、`fix:` 等 Conventional Commits 前缀
- PR 号从 commit 消息中提取(如 `(#3111)`)
- 多人参与的记录:`@id1 @id2`
- 合并多个 PR 时格式为 `(#3101 #3108)`,不要写成多个分散条目
### 描述质量
生成后必须做后处理检查,确保表达准确:
- 描述要准确反映实际变更的范围和内容,不能缩小也不能夸大
- 如果 diff 显示新增了一张地图,就写"新增 xxx 地图",而不是"新增 xxx 传送点"
- 如果改动只涉及一个配置项,不要写成整体功能变更
- 面向用户的变更用用户视角描述(功能、体验、问题现象)
- 面向开发者的变更可以保留技术术语(接口、脚本引擎、配置项等)
- 去掉不必要的代码标识符(方法名、类名等),除非它是脚本开发者会直接使用的 API
- 纯内部重构、CI 变更等不影响使用的内容可以省略不列
- 主题句要概括本版本最重要的 2~4 个变化;不要把所有分类机械罗列一遍
- 重要新增功能优先写“新增 xxx”,后续修复/优化并入同一条描述
## 输出格式
输出到 `.claude/documents/ReleaseNotes-<version>.md`(文件名 ASCII)。
输出文件的版本号规则:取边界版本号的**次版本号(minor)加 1**,补丁版本归零。即 `major.(minor+1).0`。例如边界为 `0.60.1`,输出版本号为 `0.61.0`。
若用户明确指定版本号或发布主题,以用户指定为准;否则按上述规则推导。
```markdown
## <version> <版本主题>
<一句话版本主题>
### 分类名1
- 变更描述 (#PR号) @author
- 变更描述 @author
### 分类名2
- 变更描述 (#PR号) @author
### 其他
- 变更描述 @author
```
补丁版本或少量修复可以不分分类,直接输出 bullet;但如果使用分类,仍必须保留 `其他` 分类。
## 质量门槛
- 不允许遗漏检查区间内任意 commit;确认无用户影响的 commit 可以不输出
- 不允许仅基于 commit 标题,必须查阅实际 diff
- 同一功能的多次提交必须合并,不允许出现"新增 xxx""优化 xxx(同功能)"的冗余
- 优先使用历史 Release 分类,不允许自行发明无项目语义的分类名
- "其他"分类必须存在
- 不依赖网络,全部信息从本地 git 获取
- 输出前检查是否漏掉用户可见修复,尤其是同一新功能上线后的后续修复 commit
+22
View File
@@ -0,0 +1,22 @@
---
name: Bug report / 错误报告
about: Create a report to help us improve / 创建报告以帮助我们改进
title: "[bug]请补充标题内容"
labels: bug
---
<!--
请提供下述完整信息以便快速定位问题 / Please provide the following information to quickly locate the problem
-->
- 系统环境 / System Environment:
- BetterGI版本号 / BetterGI Version:
- 问题描述 / Description of the issue:
- 复现步骤 / Reproduction steps:
-74
View File
@@ -1,74 +0,0 @@
name: Bug report / 错误报告
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
title: "[bug] "
labels:
- BUG
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Checklist before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- label: 我愿意为了解决这个问题尽自己所能 / I am willing to do my part to help resolve this issue
- type: textarea
id: environment
attributes:
label: 系统环境
description: System environment,例如操作系统版本、运行时版本、显卡驱动版本
placeholder: Windows 11 24H2 (26100.3775) / .NET Desktop Runtime 8.0.15 / NVIDIA 572.83
validations:
required: true
- type: input
id: version
attributes:
label: BetterGI 版本号
description: BetterGI Version
placeholder: e.g. 0.58.0
validations:
required: true
- type: textarea
id: description
attributes:
label: 问题描述
description: Describe the actual behavior and impact
placeholder: 请描述实际出现的问题,以及这个问题对使用造成了什么影响 / Describe the actual behavior and impact
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望结果
description: Expected behavior
placeholder: 请描述你期望出现的正确行为或结果 / Describe the expected behavior or result
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
description: Reproduction steps
placeholder: |-
1. 打开…… / Open ...
2. 点击…… / Click ...
3. 出现…… / Observe ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: 日志与附件
description: Logs and attachments,可直接拖拽上传日志文件、压缩包、截图或视频
placeholder: |-
可在这里补充日志和附件说明 / Add logs and attachment notes here:
- 可直接粘贴关键日志片段 / Paste key log snippets directly
- 可拖拽上传日志文件或压缩包 / Drag and drop log files or archives
- 可拖拽上传截图、录屏或演示视频 / Drag and drop screenshots or videos
- 若附件较多,请说明对应的时间点、任务名称或异常现象 / If there are many files, explain the relevant timestamps or symptoms
- 提交前请注意移除账号、路径等隐私信息 / Remove private information before submitting
validations:
required: false
+2 -2
View File
@@ -1,9 +1,9 @@
blank_issues_enabled: false
contact_links:
- name: 官方文档 / Document
url: https://www.bettergi.com/doc.html
url: https://bgi.huiyadan.com/doc.html
about: 请在提出问题前阅读文档 / Read the document before submit the issue
- name: 常见问题 / FAQ
url: https://www.bettergi.com/faq.html
url: https://bgi.huiyadan.com/faq.html
about: 常见的用户提出的问题 / Common questions asked by users
+9
View File
@@ -0,0 +1,9 @@
---
name: I have feature requesting / 我有新功能请求
about: Your request may come as a surprise. / 你的请求也许成为惊喜
title: "[feature] "
labels: feature 功能请求
---
- Your feature requesting / 你的新功能请求
-52
View File
@@ -1,52 +0,0 @@
name: I have feature requesting / 我有功能需求
description: 提出新的功能想法 / Share a feature request
title: "[feature] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate request
required: true
- label: 我已确认当前版本中尚未提供该功能,或至少没有等价实现 / I have confirmed this feature, or an equivalent one, is not already available in the current version
required: true
- label: 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好 / I believe this request provides clear value to a broader group of users, not just my personal preference
required: true
- label: 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳 / I understand this request may not be accepted due to implementation cost, maintenance cost, or project direction
required: true
- type: textarea
id: request
attributes:
label: 功能请求
description: Feature Request
placeholder: 请简要说明你希望新增什么能力 / Briefly describe the capability you want to add
validations:
required: true
- type: textarea
id: scenario
attributes:
label: 使用场景
description: Use Case
placeholder: 这个功能要解决什么问题?在哪些场景下使用? / What problem does this feature solve, and when would it be used?
validations:
required: true
- type: textarea
id: impact
attributes:
label: 潜在影响
description: Potential Impact
placeholder: 请说明这个功能是否可能带来新的问题、维护成本、使用门槛或兼容性影响;如果没有,请填写“无” / Describe any potential downsides such as new issues, maintenance cost, usability barriers, or compatibility impact. Write "None" if there are no obvious downsides.
validations:
required: true
- type: textarea
id: extra
attributes:
label: 补充信息
description: Optional
placeholder: "可选,补充示意图、交互草图、参考链接或相关背景信息 / Optional: add mockups, interaction sketches, reference links, or other background information"
validations:
required: false
+5
View File
@@ -0,0 +1,5 @@
---
name: Feel free to express / 随便写写
about: Record something / 简单写写记录记录
---
-22
View File
@@ -1,22 +0,0 @@
name: Feel free to express / 自由描述
description: 记录你想反馈的内容 / Share general feedback
title: "[feedback] "
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复反馈 / I have searched existing issues and confirmed this is not duplicate feedback
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的反馈 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my feedback"
required: true
- type: textarea
id: description
attributes:
label: 描述
description: Description
placeholder: 请描述你想反馈的内容 / Describe what you want to share
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have a question / 我有疑问
about: Solve your problem / 解决你的疑问
title: "[question] "
labels: question
---
- Problem Description / 问题描述
- 请尽量提供问题相关的截图/日志等内容
-32
View File
@@ -1,32 +0,0 @@
name: I have a question / 我有疑问
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
title: "[question] "
labels:
- 问题咨询
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate question
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- type: textarea
id: question
attributes:
label: 问题描述
description: Problem Description
placeholder: 请清楚描述你的问题 / Clearly describe your question
validations:
required: true
- type: textarea
id: tried
attributes:
label: 已尝试内容
description: Screenshots / logs / what you already tried
placeholder: 可附上截图、日志,以及你已经尝试过的排查过程 / Add screenshots, logs, and what you have already tried
validations:
required: true
+9
View File
@@ -0,0 +1,9 @@
---
name: I have suggestions / 我有建议
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
title: "[suggestion] "
labels: suggestion
---
- Your suggestions / 你的建议
-32
View File
@@ -1,32 +0,0 @@
name: I have suggestions / 我有建议
description: 分享对项目的改进建议 / Share an improvement suggestion
title: "[suggestion] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate suggestion
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的建议 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my suggestion"
required: true
- type: textarea
id: suggestion
attributes:
label: 建议内容
description: Suggestion
placeholder: 请描述你的建议内容 / Describe your suggestion
validations:
required: true
- type: textarea
id: benefit
attributes:
label: 预期收益
description: Expected Benefit
placeholder: 这个建议会给用户或项目带来什么帮助? / What benefits would this suggestion bring to users or the project?
validations:
required: true
-229
View File
@@ -1,229 +0,0 @@
runtime:
languageMode: auto
dryRun: false
providers:
openAiCompatible:
enabled: true
baseUrl: https://api.openai.com/v1
model: gpt-5.4
apiStyle: responses
timeoutMs: 30000
issues:
autoProcessing:
skipCreatedBefore: auto
validation:
enabled: true
fallbackTemplateKey: normal
commentAnchor: issue-bot:validation
templates:
- key: bug
detect:
markers:
- bug
titlePrefixes:
- "[bug]"
requiredSections:
- id: environment
aliases:
- 系统环境
- System Environment
- id: version
aliases:
- BetterGI 版本号
- BetterGI Version
- id: description
aliases:
- 问题描述
- Description of the issue
- id: steps
aliases:
- 复现步骤
- Reproduction steps
labels:
whenValid:
- BUG
whenInvalid:
- 需要更多信息
- key: feature
detect:
markers:
- feature
titlePrefixes:
- "[feature]"
requiredSections:
- id: request
aliases:
- 功能请求
- Feature Request
- id: scenario
aliases:
- 使用场景
- Use Case
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: suggestion
detect:
markers:
- suggestion
titlePrefixes:
- "[suggestion]"
requiredSections:
- id: suggestion
aliases:
- 建议内容
- Suggestion
- id: benefit
aliases:
- 预期收益
- Expected Benefit
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: question
detect:
markers:
- question
titlePrefixes:
- "[question]"
requiredSections:
- id: question
aliases:
- 问题描述
- Problem Description
- id: tried
aliases:
- 已尝试内容
- What I Tried
labels:
whenValid:
- 问题咨询
whenInvalid:
- 需要更多信息
- key: normal
detect:
markers:
- normal
titlePrefixes:
- "[feedback]"
- "[normal]"
requiredSections:
- id: description
aliases:
- 描述
- Description
labels:
whenValid: []
whenInvalid:
- 需要更多信息
duplicateDetection:
enabled: true
bypassLabels:
- 跳过重复检测
duplicateLabel: 重复
searchResultLimit: 50
candidateLimit: 20
aiReviewMaxCandidates: 3
thresholds:
exact: 0.995
highConfidence: 0.93
reviewMin: 0.82
similarityComment:
enabled: false
commentAnchor: issue-bot:similar-issues
minScore: 0.3
maxCandidates: 3
labeling:
enabled: true
autoCreateMissing: true
managed:
- BUG
- 功能建议
- 问题咨询
- 需要更多信息
- 重复
definitions:
BUG:
color: d73a4a
description: 程序存在缺陷或异常行为。
功能建议:
color: a2eeef
description: 新功能建议或现有功能改进。
问题咨询:
color: d876e3
description: 使用问题、求助或咨询。
# 需要更多信息:
# color: fbca04
# description: 当前 Issue 缺少必要信息。
重复:
color: cfd3d7
description: 已存在相同或高度相似的问题。
keywordRules: []
aiClassification:
enabled: false
maxLabels: 3
minConfidence: 0.65
include: []
exclude:
- BUG
- 功能请求
- 重复
- 不会修复
- 使用问题
- 需要帮助
- 已完成
- 未解决
- 待确认
- P0
- P1
- 需要文档
- 优化点
- 急急急
prompt: 优先给 BetterGI Issue 选择能反映具体功能模块、子系统或使用场景的标签,例如一条龙、调度器、脚本、设置项、地图追踪;避免只选择宽泛的流程或状态标签。
sourceRepository:
owner: babalae
repo: better-genshin-impact
aiHelp:
enabled: true
triggerLabels: []
commentAnchor: issue-bot:ai
projectContext:
enabled: true
includeRepositoryMetadata: true
includeReadme: true
readmeMaxChars: 3000
profile:
name: BetterGI
aliases:
- BGI
- Better Genshin Impact
summary: BetterGI is a desktop automation assistant for Genshin Impact.
techStack:
- C#
- WPF
- .NET
commands:
enabled: true
mentions:
- "@bot"
- "@bettergi-repo-bot"
access: collaborators
fix:
enabled: true
commentAnchor: issue-bot:fix
refresh:
enabled: true
pullRequests:
review:
enabled: false
labeling:
enabled: false
summary:
enabled: false
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan_release_note:
if: github.repository_owner == 'babalae'
runs-on: macos-latest
steps:
@@ -7,7 +7,6 @@ on:
jobs:
mirrorchyan:
if: github.repository_owner == 'babalae'
runs-on: windows-latest
steps:
- name: 📥 Download release
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
repository: zaodonganqi/bettergi-script-web
repository: A-Little-AnQi/bettergi-script-web
- uses: actions/setup-node@v4
with:
node-version: 20
-55
View File
@@ -1,55 +0,0 @@
name: Repo Bot
on:
issues:
types:
- opened
- edited
- reopened
- labeled
issue_comment:
types:
- created
- edited
jobs:
repo-bot:
runs-on: ubuntu-latest
permissions:
issues: write
contents: read
steps:
- name: Detect GitHub App configuration
id: auth-mode
shell: bash
env:
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
run: |
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
echo "use_app=true" >> "$GITHUB_OUTPUT"
else
echo "use_app=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Create GitHub App token
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
- name: Run Repo Bot
uses: ddaodan/bettergi-github-bot@v1
env:
GITHUB_TOKEN: ${{ github.token }}
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
with:
config-path: .github/repo-bot.yml
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
+3 -11
View File
@@ -30,16 +30,8 @@ github_actions_cache/
# Rider
.idea
.trae
.claude
CLAUDE.md
__pycache__/
# Trae
.trae/*
!.trae/rules/
!.trae/rules/**
!.trae/skills/
!.trae/skills/**
# Claude
.claude/*
-86
View File
@@ -1,86 +0,0 @@
本项目使用了 WPF-UI、 CommunityToolkit.Mvvm、Microsoft.Xaml.Behaviors.Wpf 来实现 MVVM 架构。在编写代码的时候请注意:
### 主要依赖框架
#### UI 框架
- **WPF-UI (4.0.2)** - 现代化 WPF UI 框架
- **gong-wpf-dragdrop(3.2.1)** - 拖拽框架
#### MVVM 框架
- **CommunityToolkit.Mvvm (8.2.2)** - 微软官方 MVVM 工具包
- 所有 ViewModel 必须继承自 `ObservableObject`
- 使用 `[ObservableProperty]` 特性自动生成属性
- 使用 `[RelayCommand]` 特性自动生成命令
- **Microsoft.Xaml.Behaviors.Wpf(1.1.122)** - WPF 行为扩展库
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
### 基础架构
### ViewModel 编写规范
1. **继承规则**
```csharp
public partial class ExampleViewModel : ViewModel
{
[ObservableProperty]
private string _title = "";
[RelayCommand]
private void DoSomething()
{
// 实现逻辑
}
}
```
2. **属性命名**
- 私有字段使用下划线前缀: `_fieldName`
- 公共属性使用 PascalCase: `PropertyName`
- 使用 `[ObservableProperty]` 自动生成属性
3. **命令实现**
- 使用 `[RelayCommand]` 特性
- 异步命令使用 `[RelayCommand]` + `async Task`
### View 编写规范
1. **代码后置**
```csharp
public partial class ExamplePage : UserControl
{
public ExampleViewModel ViewModel { get; }
public ExamplePage(ExampleViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
InitializeComponent();
}
}
```
2. **XAML 绑定**
- 使用 `{Binding}` 语法绑定 ViewModel 属性
- 命令绑定: `Command="{Binding ExampleCommand}"`
- 避免在 XAML 中编写复杂逻辑
### 依赖注入规范
1. **服务注册**
```csharp
// 在 App.xaml.cs 中注册
services.AddView<ExamplePage, ExampleViewModel>();
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
-62
View File
@@ -1,62 +0,0 @@
---
name: "github-issue-triage"
description: "Reads GitHub issues, extracts reporter details and <=10MB attachments/images, then decides discuss/research vs direct fix vs implementation plan. Invoke when user shares an issue URL."
---
# GitHub Issue Triage
用于处理 GitHub issue 链接,并在结合当前仓库代码后给出执行路径。
## 触发时机
- 用户提供 GitHub issue URL,并希望你分析内容后继续行动
- 需要先读取 issue 创建者信息、附件或图片,再决定如何推进
- 需要判断是先讨论研究、直接修复,还是先制定方案
## 输入
- 必填:GitHub issue URL,例如 `https://github.com/<owner>/<repo>/issues/<id>`
- 可选:用户额外上下文(复现步骤、期望行为、优先级)
## 执行流程
1. 读取 issue 内容
- 获取标题、正文、标签、状态、创建者、创建时间
- 提取创建者在 issue 中提供的关键信息(正文 + 创建者本人评论)
- 区分“创建者信息”与“其他参与者讨论”
2. 收集附件与图片(限制 10MB)
- 从 issue 正文和创建者评论中提取附件/图片链接
- 对每个链接获取文件大小与类型,只有 `<= 10MB` 才下载
- 优先下载图片(png/jpg/jpeg/webp/gif)与问题复现相关附件
- 记录已下载与跳过原因(超限、类型不符、不可访问)
3. 结合代码库研判
- 先做高层语义检索定位相关模块,再做符号/关键字精查
- 找到与 issue 直接相关的代码路径、入口点、可能影响范围
- 判断是否已有类似问题处理逻辑、开关、兜底或已知限制
4. 路径决策
- 讨论研究问题:信息不足、无法稳定复现、需求存在歧义、外部依赖阻塞
- 直接修复问题:根因清晰、改动范围可控、验收标准明确
- 计划方案:涉及跨模块改造、兼容性权衡、需要分阶段实施
5. 执行动作
- 若“直接修复问题”:直接修改代码并完成必要验证
- 若“计划方案”:输出分步计划、影响面、风险与验证策略
- 若“讨论研究问题”:给出需要补充的信息与建议实验步骤
## 输出格式
- Issue 摘要:标题、创建者、关键诉求、复现线索
- 创建者信息提炼:仅保留创建者提供的有效信息
- 附件处理结果:下载清单(<=10MB)与跳过清单(含原因)
- 代码关联分析:相关模块、关键函数、潜在根因
- 决策结论:讨论研究 / 直接修复 / 计划方案
- 下一步:立即执行项
## 质量要求
- 必须优先依据创建者提供的信息,不被无关评论干扰
- 必须在代码层面给出证据,不做纯主观结论
- 决策应可执行,并且与当前仓库结构一致
@@ -1,142 +0,0 @@
---
name: "release-note-generator"
description: "Generates release notes from git commits/diffs and outputs one Chinese MD file. Invoke when user asks for release notes bounded by previous non-alpha version."
---
# Release Note Generator
用于基于当前仓库的 git 历史自动生成发布说明,确保不遗漏提交,并为每条变更记录追加提交人的 GitHub ID(`@id`)。默认输出一个 Markdown 文件到 `.trae/documents` 目录:变更内容。
## 触发时机
- 用户要求生成 Release Note / 更新日志
- 用户要求基于最近提交和实际代码变更做汇总
- 用户要求以“上一个非 alpha 版本”为边界统计变更
## 输入约定
- 默认分支当前 `HEAD`
- 版本边界规则:从最新提交向后遍历,遇到“提交信息包含版本号且不含 alpha”的最近一个提交作为边界
- 若用户指定分支、Tag 或版本正则,优先使用用户指定
- 未指定时,默认输出文档路径为:`.trae/documents/release_notes-<version>.md`
## 实战经验(本项目)
- 不直接依赖终端长输出:大量 `git log` 在终端中容易被截断,导致误判“提交缺失”
- 不用 `|` 等普通分隔符解析:提交标题可能包含分隔符,必须使用 NUL 分隔(`\x00`)保证可解析
- 统一 UTF-8:PowerShell 下中文提交信息可能乱码,调用 git 时需显式设置输出编码
- 避免在 `RunCommand` 的内联脚本中直接硬编码中文常量(标题、分类名、文件名):在 Windows/PowerShell 链路中可能被替换为 `?`
- 发布文件名使用 ASCII:不要在文件名中使用中文(如 `ReleaseNotes-变更内容-<version>.md`),否则编码异常时会变成非法字符 `?` 导致写文件失败
- 中文文案仅放在 Markdown 内容里,并在写入后做一次乱码校验:若出现 `???`、`### ??` 等占位符,必须重新生成
- 明确分支范围:优先使用 `HEAD` 可达历史,必要时用 `--first-parent` 辅助核对发布主线
- 先计数再明细:先取 `rev-list --count`,再逐条采集,最后做数量一致性校验
- 版本边界要可回退:目标版本不存在时,自动回退到最近可识别的“上一非 alpha 版本”并在结果中声明
## 日志采集方式(强制)
- 必须使用 Python 脚本拉取 commit 与 diff,不直接用终端拼接命令产出最终结果
- Python 内通过 `subprocess.run([...], check=True, capture_output=True, text=True, encoding="utf-8", errors="replace")` 调 git
- git 命令需附加编码参数:`-c i18n.logOutputEncoding=utf8 -c core.quotepath=false`
- 提交元数据推荐格式:`--pretty=format:%H%x00%h%x00%an%x00%ae%x00%ad%x00%s%x00`,按 `\x00` 解析
- diff 证据至少包含:
- 区间总览:`git diff --shortstat <base>..<head>`
- 文件变更:`git diff --name-status <base>..<head>`
- 行级统计:`git diff --numstat <base>..<head>`
- 必要时单提交详情:`git show --name-status --numstat --format= <sha>`
- Python 脚本需输出结构化数据(JSON/对象)后再生成 release note 文本
- 若通过终端执行 Python,优先将中文文案写成 `\\uXXXX` 形式或由程序运行期拼接,避免命令传输阶段损坏字符
## 执行流程
1. 获取提交序列(防遗漏)
- 从 `HEAD` 向后扫描提交,定位边界提交 `boundary_commit`
- 使用可识别 SemVer 的正则提取版本号(例如 `v1.2.3`、`1.2.3`)
- 判断“非 alpha”时使用大小写不敏感匹配:提交信息不包含 `alpha`
- 生成统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入变更列表
- 使用 Python 执行 git 并解析 NUL 分隔结果,禁止依赖终端显示内容做解析
2. 完整性校验(必须)
- 先取区间提交总数 `N`
- 再逐条收集区间内每个 commit 的详情
- 输出前校验“已收集条数 == N”,不一致则重新拉取,直到一致
- 若存在 merge,额外给出 `--first-parent` 视角的校验结果,避免发布主线理解偏差
3. 采集每条提交的证据
- 提交元数据:hash、标题、作者、时间
- 实际改动:由 Python 采集 `--name-status`、`--numstat`、`--shortstat` 与必要 diff 片段
- 将提交按功能模块归类(如 UI、任务、配置、脚本、基础设施等)
4. 提炼发布内容
- 先按用户指定分类规则归类;若未指定,使用更接近 GitHub Releases 页面的默认分类顺序:
1) 新功能
2) 地图遮罩
3) 独立任务
4) JS相关
5) 其他
- 分类名尽量贴近业务语义:例如“地图追踪”“自动剧情”“七圣召唤”等可作为二级小节并入对应一级分类
- 无法稳定归类的小变更统一放入“其他”
- 每条摘要都要可追溯到至少一个 commit
- 识别“变更最大点”并在首屏摘要中突出展示
- 主体正文只展示可读的变更描述,不在分类正文中堆叠 hash
- 完整提交清单放在文末,避免正文可读性下降
- 输出文案需去掉 Conventional Commits 前缀:至少移除 `feat:`、`fix:`(区分大小写不敏感),再写入分类正文与完整提交清单
5. 生成提交人 GitHub ID(逐条记录追加 `@id`)
- 必须以“当前方式”解析:对区间内每个 commit 逐条调用 GitHub 提交接口,禁止仅依赖本地 `author name`:
- 接口:`https://api.github.com/repos/<owner>/<repo>/commits/<sha>`
- 请求头至少包含:`Accept: application/vnd.github+json`、`User-Agent: <custom>`
- 解析顺序固定:优先 `author.login`,为空时取 `committer.login`
- 必须保证覆盖全量区间提交:
- 对每个 SHA 单独请求并记录结果
- 输出前校验“已解析 login 数 == 区间提交数”,不一致则进入回退链
- 回退链(仅当 API 某条未命中时):
- 先用“同区间内已解析结果”做映射回填(同 author email / 同 author name)
- 再解析 GitHub noreply 邮箱:
- `[email protected]` -> `@login`
- `[email protected]` -> `@login`
- 再回退 `.atom`:`https://github.com/<owner>/<repo>/commits/<branch>.atom` 按 SHA 匹配 `<entry>` 获取 `<author><name>`
- 最后才允许作者名标准化兜底,并明确标记为推断
- 为每条变更记录绑定对应作者的 `@id`
- 若一条汇总涉及多个 commit,按去重后多作者格式追加:`@id1 @id2`
## 输出格式(强制,需贴近 GitHub Releases 风格)
必须产出 1 个文件:
1. 变更内容文件(全中文)
- 文件路径:`.trae/documents/ReleaseNotes-<version>.md`(文件名必须 ASCII)
- 内容结构(推荐模板):
- 一级标题:`## <version> <版本主题>`(示例:`## 0.58 月之五适配`)
- 开场一句话:版本背景或问候语(可选,1~2 句)
- 分类正文:按以下顺序输出存在内容的分类:
- `新功能`
- `地图遮罩`
- `独立任务`
- `JS相关`
- `其他`(必须保留,即使只有 1 条)
- 分类内每条为单行 bullet,格式:
- `<变更描述> (#PR号可选) @githubId`
- 若某条由多人提交,使用:`@id1 @id2`
- 文末追加“完整提交清单”(倒序,不能缺项,每条带 `@id`)
- 在标题下方补充统计信息:`边界提交 / 区间 / 提交数 / shortstat`
补充要求:
- 变更内容文件必须全中文
- 仅内容全中文;文件名必须为 ASCII,避免 Windows 下出现 `?` 非法路径
- 风格贴近 GitHub Releases:简洁分段、先讲用户可感知变化,再给完整清单
- 正文优先使用自然语言,不直接复制 commit 原文
- 分类不允许缺失“其他”
- 内容中不保留 `feat:`、`fix:` 前缀
- 生成后必须执行乱码检查:若命中 `\\?{2,}` 或 `### \\?+`,视为失败并重生成
## 质量门槛
- 不允许遗漏区间内任意 commit
- 不允许仅基于 commit 标题,必须结合实际代码改动
- 每条变更记录必须带作者 `@id`,不允许只在末尾集中列出
- 必须通过 Python 脚本获取日志与 diff,禁止直接依赖终端长输出结果
- 解析 `@id` 时必须逐条调用 GitHub Commit API(`/repos/<owner>/<repo>/commits/<sha>`),不得以本地昵称直接替代
- 未找到边界版本时,必须明确说明并给出当前采用的兜底范围
- 分类默认遵循“新功能 / 地图遮罩 / 独立任务 / JS相关 / 其他”,其中“其他”必须出现
- Markdown 文件必须实际落盘到仓库中的 `.trae/documents` 目录
- 不允许输出出现乱码占位符(如 `???`、`??` 分类名);发现即判定为不合格
-86
View File
@@ -1,86 +0,0 @@
本项目使用了 WPF-UI、 CommunityToolkit.Mvvm、Microsoft.Xaml.Behaviors.Wpf 来实现 MVVM 架构。在编写代码的时候请注意:
### 主要依赖框架
#### UI 框架
- **WPF-UI (4.0.2)** - 现代化 WPF UI 框架
- **gong-wpf-dragdrop(3.2.1)** - 拖拽框架
#### MVVM 框架
- **CommunityToolkit.Mvvm (8.2.2)** - 微软官方 MVVM 工具包
- 所有 ViewModel 必须继承自 `ObservableObject`
- 使用 `[ObservableProperty]` 特性自动生成属性
- 使用 `[RelayCommand]` 特性自动生成命令
- **Microsoft.Xaml.Behaviors.Wpf(1.1.122)** - WPF 行为扩展库
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
### 基础架构
### ViewModel 编写规范
1. **继承规则**
```csharp
public partial class ExampleViewModel : ViewModel
{
[ObservableProperty]
private string _title = "";
[RelayCommand]
private void DoSomething()
{
// 实现逻辑
}
}
```
2. **属性命名**
- 私有字段使用下划线前缀: `_fieldName`
- 公共属性使用 PascalCase: `PropertyName`
- 使用 `[ObservableProperty]` 自动生成属性
3. **命令实现**
- 使用 `[RelayCommand]` 特性
- 异步命令使用 `[RelayCommand]` + `async Task`
### View 编写规范
1. **代码后置**
```csharp
public partial class ExamplePage : UserControl
{
public ExampleViewModel ViewModel { get; }
public ExamplePage(ExampleViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
InitializeComponent();
}
}
```
2. **XAML 绑定**
- 使用 `{Binding}` 语法绑定 ViewModel 属性
- 命令绑定: `Command="{Binding ExampleCommand}"`
- 避免在 XAML 中编写复杂逻辑
### 依赖注入规范
1. **服务注册**
```csharp
// 在 App.xaml.cs 中注册
services.AddView<ExamplePage, ExampleViewModel>();
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
-5
View File
@@ -17,8 +17,6 @@
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<bgivc:DomainNameToCascadingItemConverter x:Key="DomainNameConverter" />
<bgivc:AutoBossNameToCascadingItemConverter x:Key="AutoBossNameConverter" />
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
@@ -26,9 +24,6 @@
<bgivc:NotNullConverter x:Key="NotNullConverter" />
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
<bgivc:TrConverter x:Key="TrConverter" />
<bgivc:AdaptiveUniformGridColumnsConverter x:Key="AdaptiveUniformGridColumnsConverter" />
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
+9 -59
View File
@@ -52,7 +52,8 @@ public partial class App : Application
.UseElevated()
.UseSingleInstance("BetterGI")
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureServices((context, services) =>
.ConfigureServices(
(context, services) =>
{
// 提前初始化配置
var configService = new ConfigService();
@@ -73,37 +74,19 @@ public partial class App : Application
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21))
.WriteTo.Console(outputTemplate:
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
if (all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true })
if (all.MaskWindowConfig.MaskEnabled)
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
Log.Logger = loggerConfiguration.CreateLogger();
services.AddSingleton<IMissingTranslationReporter, SupabaseMissingTranslationReporter>();
services.AddSingleton<ITranslationService, JsonTranslationService>();
services.AddLogging(c => c.AddSerilog());
// if ("zh-Hans".Equals(all.OtherConfig.UiCultureInfoName, StringComparison.OrdinalIgnoreCase))
// {
// services.AddLogging(c => c.AddSerilog());
// }
// else
// {
// services.AddLogging(logging =>
// {
// logging.ClearProviders();
// logging.SetMinimumLevel(LogLevel.Debug);
// logging.AddFilter("Microsoft", LogLevel.Warning);
// logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);
// logging.Services.AddSingleton<ILoggerProvider, TranslatingSerilogLoggerProvider>();
// });
// }
services.AddLocalization();
@@ -151,7 +134,6 @@ public partial class App : Application
// services.AddSingleton<TcgViewModel>();
// My Services
services.AddSingleton<OverlayMetricsService>();
services.AddSingleton<TaskTriggerDispatcher>();
services.AddSingleton<NotificationService>();
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
@@ -165,15 +147,14 @@ public partial class App : Application
services.AddSingleton<MemoryFileCache>();
services.AddSingleton<IMihoyoMapApiService, MihoyoMapApiService>();
services.AddSingleton<IKongyingTavernApiService, KongyingTavernApiService>();
services.AddSingleton<IHoYoLabMapApiService, HoYoLabMapApiService>();
services.AddSingleton<IMaskMapPointService, MaskMapPointService>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
I18N.Culture = new CultureInfo("zh-Hans"); // #1846
}
)
@@ -211,7 +192,6 @@ public partial class App : Application
/// </summary>
protected override async void OnStartup(StartupEventArgs e)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
// Wine 平台适配
WinePlatformAddon.ApplyApplicationConfig();
base.OnStartup(e);
@@ -227,19 +207,10 @@ public partial class App : Application
}
catch (Exception ex)
{
// DEBUG only, no overhead
Debug.WriteLine(ex);
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
try
{
HandleException(ex);
}
catch (Exception ex2)
{
Debug.WriteLine(ex2);
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
}
if (Debugger.IsAttached)
{
Debugger.Break();
@@ -255,12 +226,12 @@ public partial class App : Application
base.OnExit(e);
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
// 释放控制台窗口
ConsoleHelper.FreeConsoleWindow();
}
@@ -284,12 +255,6 @@ public partial class App : Application
{
try
{
// 忽略V8引擎释放后pending的Task回调抛出的异常
if (IsV8EngineReleasedException(e.Exception))
{
return;
}
HandleException(e.Exception);
}
catch (Exception ex)
@@ -302,21 +267,6 @@ public partial class App : Application
}
}
private static bool IsV8EngineReleasedException(Exception? ex)
{
while (ex != null)
{
if (ex.Message?.Contains("V8 object has been released") == true)
{
return true;
}
ex = ex.InnerException;
}
return false;
}
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
+10 -25
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.62.0</Version>
<Version>0.55.2-alpha.1</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -43,9 +43,9 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.28" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.17" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.10" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="DeviceId" Version="6.9.0" />
@@ -54,7 +54,6 @@
<PackageReference Include="Emoji.Wpf" Version="0.3.4" />
<PackageReference Include="LibGit2Sharp" Version="0.31.0" />
<PackageReference Include="LazyCache" Version="2.4.0" />
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.6" />
<PackageReference Include="MailKit" Version="4.14.0" />
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
@@ -68,7 +67,7 @@
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.21.0" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="MimeKit" Version="4.15.1" />
<PackageReference Include="MimeKit" Version="4.14.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
@@ -85,19 +84,17 @@
<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.Drawing.Common" Version="10.0.0" />
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
<PackageReference Include="XamlAnimatedGif" Version="2.3.1" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.3.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.0" />
<PackageReference Include="WPF-UI" Version="4.2.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.2.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.2.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.2.0.1" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
@@ -131,9 +128,6 @@
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\LogParse\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -200,15 +194,6 @@
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoBoss\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\I18n\en.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
+14 -91
View File
@@ -21,12 +21,10 @@ public class BvLocator
{
private static readonly ILogger Logger = App.GetLogger<BvLocator>();
private readonly CancellationToken _cancellationToken;
private int? _timeout;
private int? _retryInterval;
public RecognitionObject RecognitionObject { get; }
public Func<List<Region>, Task>? RetryAction { get; set; }
public Action<List<Region>>? RetryAction { get; set; }
public static int DefaultTimeout { get; set; } = 10000;
@@ -100,21 +98,17 @@ public class BvLocator
public async Task<List<Region>> WaitFor(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
List<Region> results = [];
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
results = FindAll();
var b = results.Count > 0;
if (!b && RetryAction != null)
{
await RetryAction(results);
}
RetryAction?.Invoke(results);
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (retryRes)
{
@@ -156,21 +150,20 @@ public class BvLocator
public async Task WaitForDisappear(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
var results = FindAll();
var b = results.Count == 0;
if (!b && RetryAction != null)
if (!b)
{
await RetryAction(results);
RetryAction?.Invoke(results);
}
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (!retryRes)
{
@@ -212,77 +205,7 @@ public class BvLocator
public BvLocator WithRetryAction(Action<List<Region>>? action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = (results) =>
{
action(results);
return Task.CompletedTask;
};
}
RetryAction = action;
return this;
}
/// <summary>
/// 设置超时时间(毫秒)
/// </summary>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns></returns>
public BvLocator WithTimeout(int timeout)
{
if (timeout <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout), "timeout 必须大于 0");
}
_timeout = timeout;
return this;
}
/// <summary>
/// 设置重试间隔(毫秒)
/// </summary>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns></returns>
public BvLocator WithRetryInterval(int retryInterval)
{
if (retryInterval <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retryInterval), "retryInterval 必须大于 0");
}
_retryInterval = retryInterval;
return this;
}
/// <summary>
/// 为 JavaScript 提供的动态参数重载
/// 解决 ClearScript 无法将 JS 函数隐式转换为 Action 委托的问题
/// 支持同步和异步 JS 函数
/// </summary>
/// <param name="action">JS 回调函数</param>
/// <returns></returns>
public BvLocator WithRetryAction(dynamic action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = async (results) =>
{
var taskResult = action(results);
// 如果 JS 返回的是 Promise/Task,等待其完成
if (taskResult is Task task)
{
await task;
}
};
}
return this;
}
}
}
+9 -27
View File
@@ -1,6 +1,6 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -22,10 +22,7 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.GetGridIcons;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.MapMask;
using BetterGenshinImpact.GameTask.SkillCd;
using BetterGenshinImpact.GameTask.UseRedeemCode;
namespace BetterGenshinImpact.Core.Config;
@@ -130,6 +127,11 @@ public partial class AllConfig : ObservableObject
/// </summary>
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
/// <summary>
/// 自动烹饪配置
/// </summary>
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 自动打牌配置
/// </summary>
@@ -154,11 +156,6 @@ public partial class AllConfig : ObservableObject
/// 自动秘境配置
/// </summary>
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 自动首领讨伐配置
/// </summary>
public AutoBossConfig AutoBossConfig { get; set; } = new();
/// <summary>
@@ -175,24 +172,12 @@ public partial class AllConfig : ObservableObject
/// 自动吃药配置
/// </summary>
public AutoEatConfig AutoEatConfig { get; set; } = new();
/// <summary>
/// 自动地脉花配置
/// </summary>
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 地图遮罩
/// </summary>
public MapMaskConfig MapMaskConfig { get; set; } = new();
/// <summary>
/// 技能 CD 提示
/// </summary>
public SkillCdConfig SkillCdConfig { get; set; } = new();
/// <summary>
/// 自动使用
/// </summary>
@@ -272,18 +257,16 @@ public partial class AllConfig : ObservableObject
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
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;
@@ -291,7 +274,6 @@ public partial class AllConfig : ObservableObject
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
DevConfig.PropertyChanged += OnAnyPropertyChanged;
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -304,4 +286,4 @@ public partial class AllConfig : ObservableObject
{
NotificationService.Instance().RefreshNotifiers();
}
}
}
@@ -38,12 +38,6 @@ public partial class CommonConfig : ObservableObject
[ObservableProperty]
private bool _screenshotUidCoverEnabled = true;
/// <summary>
/// 是否保存奖励识别调试截图
/// </summary>
[ObservableProperty]
private bool _rewardRecognitionScreenshotEnabled;
/// <summary>
/// 退出时最小化至托盘
/// </summary>
@@ -86,22 +80,4 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _redeemCodeFeedsUpdateVersion = "20251013";
/// <summary>
/// 国服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeCnFeedsNotificationEnabled = true;
/// <summary>
/// 国际服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeGlobalFeedsNotificationEnabled;
/// <summary>
/// 当前看过的国际服兑换码推送版本
/// </summary>
[ObservableProperty]
private string _redeemCodeGlobalFeedsUpdateVersion = string.Empty;
}
@@ -47,10 +47,4 @@ public partial class GenshinStartConfig : ObservableObject
[ObservableProperty]
private bool _startGameWithCmd = false;
/// <summary>
/// 启动前自动关闭原神 HDR(删除原神 HDR 对应注册表键)
/// </summary>
[ObservableProperty]
private bool _autoDisableGenshinHdrEnabled = true;
}
@@ -14,10 +14,10 @@ public partial class HardwareAccelerationConfig : ObservableObject
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
/// <summary>
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
/// </summary>
[ObservableProperty]
private bool _cpuOcr = true;
private bool _cpuOcr = false;
#region 一般GPU加速设置
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -100,13 +100,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 技能CD提示开关
[ObservableProperty]
private string _skillCdEnabledHotkey = "";
[ObservableProperty]
private string _skillCdEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 截图
[ObservableProperty]
@@ -163,13 +156,6 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _autoFishingGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动烹饪开始/停止
[ObservableProperty]
private string _autoCookGameHotkey = "";
[ObservableProperty]
private string _autoCookGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动寻路
[ObservableProperty]
private string _autoTrackPathHotkey = "";
@@ -251,11 +237,4 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 地图遮罩开关
[ObservableProperty]
private string _mapMaskEnabledHotkey = "";
[ObservableProperty]
private string _mapMaskEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -1,8 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
@@ -12,23 +10,6 @@ namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class MaskWindowConfig : ObservableObject
{
// 指标栏布局和遮罩里其它元素一样按 1920x1080 折算比例保存,默认放在状态栏/日志上方以避开游戏底部 UI。
public const double DefaultMetricsLeftRatio = 20.0 / 1920;
public const double DefaultMetricsTopRatio = 744.0 / 1080;
public const double DefaultMetricsWidthRatio = 477.0 / 1920;
public const double DefaultMetricsHeightRatio = 58.0 / 1080;
// 这些是开发评审过程中曾下发过的默认布局;用户没有手动调整时迁移到最新默认值,避免旧默认继续挡住游戏 UI。
private static readonly (double Left, double Top, double Width, double Height)[] LegacyMetricsLayouts =
[
(4.0 / 1920, 4.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(600.0 / 1920, 16.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 58.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 58.0 / 1080)
];
/// <summary>
/// 方位提示是否启用
/// </summary>
@@ -83,13 +64,11 @@ public partial class MaskWindowConfig : ObservableObject
private bool _showFps = false;
/// <summary>
/// 显示遮罩指标栏
/// 作为原神子窗体
/// 有些bug没解决
/// </summary>
[ObservableProperty]
private bool _showOverlayMetrics = false;
// 配置文件里使用 string key 便于兼容旧版本,读取后由 EnsureOverlayMetricItems 约束回固定枚举集合。
public Dictionary<string, bool> OverlayMetricItems { get; set; } = OverlayMetricItemDefaults.CreateDefaultItems();
private bool _useSubform = false;
/// <summary>
/// 遮罩文本透明度 (0.0-1.0)
@@ -104,10 +83,10 @@ public partial class MaskWindowConfig : ObservableObject
private double _logTextBoxLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _logTextBoxTopRatio = 822.0 / 1080;
private double _logTextBoxTopRatio = 832.0 / 1080;
[ObservableProperty]
private double _logTextBoxWidthRatio = 480.0 / 1920;
private double _logTextBoxWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _logTextBoxHeightRatio = 188.0 / 1080;
@@ -116,92 +95,11 @@ public partial class MaskWindowConfig : ObservableObject
private double _statusListLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _statusListTopRatio = 790.0 / 1080;
private double _statusListTopRatio = 807.0 / 1080;
[ObservableProperty]
private double _statusListWidthRatio = 480.0 / 1920;
private double _statusListWidthRatio = 477.0 / 1920;
[ObservableProperty]
private double _statusListHeightRatio = 24.0 / 1080;
[ObservableProperty]
private double _metricsLeftRatio = DefaultMetricsLeftRatio;
[ObservableProperty]
private double _metricsTopRatio = DefaultMetricsTopRatio;
[ObservableProperty]
private double _metricsWidthRatio = DefaultMetricsWidthRatio;
[ObservableProperty]
private double _metricsHeightRatio = DefaultMetricsHeightRatio;
public void ResetOverlayMetricsLayout()
{
MetricsLeftRatio = DefaultMetricsLeftRatio;
MetricsTopRatio = DefaultMetricsTopRatio;
MetricsWidthRatio = DefaultMetricsWidthRatio;
MetricsHeightRatio = DefaultMetricsHeightRatio;
}
public void MigrateLegacyOverlayMetricsLayout()
{
if (LegacyMetricsLayouts.Any(layout =>
IsSameRatio(MetricsLeftRatio, layout.Left)
&& IsSameRatio(MetricsTopRatio, layout.Top)
&& IsSameRatio(MetricsWidthRatio, layout.Width)
&& IsSameRatio(MetricsHeightRatio, layout.Height)))
{
ResetOverlayMetricsLayout();
}
}
private static bool IsSameRatio(double left, double right)
{
return Math.Abs(left - right) < 0.0000001;
}
public void EnsureOverlayMetricItems()
{
// 旧配置可能缺少新指标或残留废弃指标,这里统一补默认项并移除非法 key,避免 UI 渲染任意字符串。
OverlayMetricItems ??= [];
// TriggerInterval 第一版展示的是配置值,现已替换为 PeakProcessingCost;保留用户原来的勾选状态。
const string legacyTriggerIntervalKey = "TriggerInterval";
var peakProcessingCostKey = OverlayMetricItem.PeakProcessingCost.ToString();
if (OverlayMetricItems.TryGetValue(legacyTriggerIntervalKey, out var legacyEnabled)
&& !OverlayMetricItems.ContainsKey(peakProcessingCostKey))
{
OverlayMetricItems[peakProcessingCostKey] = legacyEnabled;
}
foreach (var item in OverlayMetricItemDefaults.AllItems)
{
var key = item.ToString();
if (!OverlayMetricItems.ContainsKey(key))
{
OverlayMetricItems[key] = OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
}
var validKeys = OverlayMetricItemDefaults.AllItems.Select(item => item.ToString()).ToHashSet();
foreach (var key in OverlayMetricItems.Keys.Where(key => !validKeys.Contains(key)).ToList())
{
OverlayMetricItems.Remove(key);
}
}
public bool IsOverlayMetricEnabled(OverlayMetricItem item)
{
return OverlayMetricItems != null && OverlayMetricItems.TryGetValue(item.ToString(), out var enabled)
? enabled
: OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
public void SetOverlayMetricEnabled(OverlayMetricItem item, bool enabled)
{
EnsureOverlayMetricItems();
OverlayMetricItems[item.ToString()] = enabled;
OnPropertyChanged(nameof(OverlayMetricItems));
}
}
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.Helpers;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -46,13 +45,13 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private int _minResinToKeep = 0;
// 普通周日或限时奖励选项
// 领取每日奖励的好感数量
[ObservableProperty]
private string _sundayEverySelectedValue = "0";
// 每周秘境的全局限时奖励选项,单日留空时使用
// 领取每日奖励的好感数量
[ObservableProperty]
private string _sundayWeeklySelectedValue = "0";
private string _sundaySelectedValue = "0";
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
[ObservableProperty]
@@ -62,87 +61,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private List<string> _secretTreasureObjects = new();
// 地脉花一条龙模式(跳过部分准备流程)
[ObservableProperty]
private bool _leyLineOneDragonMode = false;
// 地脉花运行日期设置
[ObservableProperty]
private bool _leyLineRunMonday = true;
[ObservableProperty]
private bool _leyLineRunTuesday = true;
[ObservableProperty]
private bool _leyLineRunWednesday = true;
[ObservableProperty]
private bool _leyLineRunThursday = true;
[ObservableProperty]
private bool _leyLineRunFriday = true;
[ObservableProperty]
private bool _leyLineRunSaturday = true;
[ObservableProperty]
private bool _leyLineRunSunday = true;
// 地脉花每日类型与国家配置(为空则使用独立任务配置)
[ObservableProperty]
private string _leyLineMondayType = string.Empty;
[ObservableProperty]
private string _leyLineMondayCountry = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayType = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayType = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineThursdayType = string.Empty;
[ObservableProperty]
private string _leyLineThursdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineFridayType = string.Empty;
[ObservableProperty]
private string _leyLineFridayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayType = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSundayType = string.Empty;
[ObservableProperty]
private string _leyLineSundayCountry = string.Empty;
// 地脉花刷取次数(0 表示使用独立任务配置)
[ObservableProperty]
private int _leyLineRunCount = 0;
// 地脉花树脂耗尽模式
[ObservableProperty]
private bool _leyLineResinExhaustionMode = false;
// 地脉花刷取次数取小值(仅耗尽模式生效)
[ObservableProperty]
private bool _leyLineOpenModeCountMin = false;
#region 每周秘境配置
//周一
@@ -151,9 +69,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _mondayDomainName = string.Empty;
[ObservableProperty]
private string _mondaySelectedValue = "0";
//周二
@@ -162,9 +77,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _tuesdayDomainName = string.Empty;
[ObservableProperty]
private string _tuesdaySelectedValue = "0";
//周三
[ObservableProperty]
@@ -172,9 +84,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _wednesdayDomainName = string.Empty;
[ObservableProperty]
private string _wednesdaySelectedValue = "0";
//周四
[ObservableProperty]
@@ -182,9 +91,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _thursdayDomainName = string.Empty;
[ObservableProperty]
private string _thursdaySelectedValue = "0";
//周五
[ObservableProperty]
@@ -192,9 +98,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _fridayDomainName = string.Empty;
[ObservableProperty]
private string _fridaySelectedValue = "0";
//周六
[ObservableProperty]
@@ -202,9 +105,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _saturdayDomainName = string.Empty;
[ObservableProperty]
private string _saturdaySelectedValue = "0";
//周日
[ObservableProperty]
@@ -213,9 +113,6 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _sundayDomainName = string.Empty;
[ObservableProperty]
private string _sundaySelectedValue = "0";
// 完成后操作
[ObservableProperty]
private string _completionAction = string.Empty;
@@ -229,93 +126,21 @@ public partial class OneDragonFlowConfig : ObservableObject
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => (GetWeeklyPartyName(MondayPartyName), GetWeeklyDomainName(MondayDomainName), GetWeeklySelectedValue(MondaySelectedValue)),
DayOfWeek.Tuesday => (GetWeeklyPartyName(TuesdayPartyName), GetWeeklyDomainName(TuesdayDomainName), GetWeeklySelectedValue(TuesdaySelectedValue)),
DayOfWeek.Wednesday => (GetWeeklyPartyName(WednesdayPartyName), GetWeeklyDomainName(WednesdayDomainName), GetWeeklySelectedValue(WednesdaySelectedValue)),
DayOfWeek.Thursday => (GetWeeklyPartyName(ThursdayPartyName), GetWeeklyDomainName(ThursdayDomainName), GetWeeklySelectedValue(ThursdaySelectedValue)),
DayOfWeek.Friday => (GetWeeklyPartyName(FridayPartyName), GetWeeklyDomainName(FridayDomainName), GetWeeklySelectedValue(FridaySelectedValue)),
DayOfWeek.Saturday => (GetWeeklyPartyName(SaturdayPartyName), GetWeeklyDomainName(SaturdayDomainName), GetWeeklySelectedValue(SaturdaySelectedValue)),
DayOfWeek.Sunday => (GetWeeklyPartyName(SundayPartyName), GetWeeklyDomainName(SundayDomainName), GetWeeklySelectedValue(SundaySelectedValue)),
_ => (PartyName, DomainName, SundayWeeklySelectedValue)
DayOfWeek.Monday => (MondayPartyName, MondayDomainName,SundaySelectedValue),
DayOfWeek.Tuesday => (TuesdayPartyName, TuesdayDomainName,SundaySelectedValue),
DayOfWeek.Wednesday => (WednesdayPartyName, WednesdayDomainName,SundaySelectedValue),
DayOfWeek.Thursday => (ThursdayPartyName, ThursdayDomainName,SundaySelectedValue),
DayOfWeek.Friday => (FridayPartyName, FridayDomainName,SundaySelectedValue),
DayOfWeek.Saturday => (SaturdayPartyName, SaturdayDomainName,SundaySelectedValue),
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName,SundaySelectedValue),
_ => (PartyName, DomainName,SundaySelectedValue)
};
}
else
{
return (PartyName, DomainName, SundayEverySelectedValue);
return (PartyName, DomainName,SundayEverySelectedValue);
}
}
private string GetWeeklyPartyName(string partyName)
{
return string.IsNullOrWhiteSpace(partyName) ? PartyName : partyName;
}
private string GetWeeklyDomainName(string domainName)
{
return string.IsNullOrWhiteSpace(domainName) ? DomainName : domainName;
}
private string GetWeeklySelectedValue(string selectedValue)
{
return string.IsNullOrWhiteSpace(selectedValue) || selectedValue == "0" ? SundayWeeklySelectedValue : selectedValue;
}
public bool ShouldRunLeyLineToday()
{
if (!LeyLineRunMonday
&& !LeyLineRunTuesday
&& !LeyLineRunWednesday
&& !LeyLineRunThursday
&& !LeyLineRunFriday
&& !LeyLineRunSaturday
&& !LeyLineRunSunday)
{
return true;
}
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => LeyLineRunMonday,
DayOfWeek.Tuesday => LeyLineRunTuesday,
DayOfWeek.Wednesday => LeyLineRunWednesday,
DayOfWeek.Thursday => LeyLineRunThursday,
DayOfWeek.Friday => LeyLineRunFriday,
DayOfWeek.Saturday => LeyLineRunSaturday,
DayOfWeek.Sunday => LeyLineRunSunday,
_ => true
};
}
public (string type, string country) GetLeyLineConfigForToday(AutoLeyLineOutcropConfig fallback)
{
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
var (type, country) = dayOfWeek switch
{
DayOfWeek.Monday => (LeyLineMondayType, LeyLineMondayCountry),
DayOfWeek.Tuesday => (LeyLineTuesdayType, LeyLineTuesdayCountry),
DayOfWeek.Wednesday => (LeyLineWednesdayType, LeyLineWednesdayCountry),
DayOfWeek.Thursday => (LeyLineThursdayType, LeyLineThursdayCountry),
DayOfWeek.Friday => (LeyLineFridayType, LeyLineFridayCountry),
DayOfWeek.Saturday => (LeyLineSaturdayType, LeyLineSaturdayCountry),
DayOfWeek.Sunday => (LeyLineSundayType, LeyLineSundayCountry),
_ => (string.Empty, string.Empty)
};
if (string.IsNullOrWhiteSpace(type))
{
type = fallback.LeyLineOutcropType;
}
if (string.IsNullOrWhiteSpace(country))
{
country = fallback.Country;
}
return (type, country);
}
#endregion
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -121,4 +121,4 @@ public partial class OtherConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _uiCultureInfoName = "zh-Hans";
}
}
@@ -1,85 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
public enum OverlayMetricItem
{
GameFps,
ProcessingCost,
PeakProcessingCost,
CaptureCost,
TriggerCost,
SkippedTicks,
CpuUsage,
GpuUsage,
MemoryUsage
}
public static class OverlayMetricItemDefaults
{
// 显式顺序同时决定遮罩三行三列显示顺序和设置页复选框顺序,不要随手改回 Enum.GetValues。
public static IReadOnlyList<OverlayMetricItem> AllItems { get; } =
[
OverlayMetricItem.GameFps,
OverlayMetricItem.ProcessingCost,
OverlayMetricItem.PeakProcessingCost,
OverlayMetricItem.CaptureCost,
OverlayMetricItem.TriggerCost,
OverlayMetricItem.SkippedTicks,
OverlayMetricItem.GpuUsage,
OverlayMetricItem.CpuUsage,
OverlayMetricItem.MemoryUsage
];
public static Dictionary<string, bool> CreateDefaultItems()
{
return AllItems.ToDictionary(item => item.ToString(), IsEnabledByDefault);
}
public static bool IsEnabledByDefault(OverlayMetricItem item)
{
// 默认只开启低风险的常用实时指标;硬件传感器项由用户按需开启,读不到时也不会占位显示。
return item is OverlayMetricItem.GameFps
or OverlayMetricItem.ProcessingCost
or OverlayMetricItem.PeakProcessingCost
or OverlayMetricItem.CaptureCost
or OverlayMetricItem.SkippedTicks
or OverlayMetricItem.MemoryUsage;
}
public static string GetDisplayName(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏帧率",
OverlayMetricItem.ProcessingCost => "处理耗时",
OverlayMetricItem.PeakProcessingCost => "峰值耗时",
OverlayMetricItem.CaptureCost => "截图耗时",
OverlayMetricItem.TriggerCost => "触发器耗时",
OverlayMetricItem.SkippedTicks => "跳过次数",
OverlayMetricItem.CpuUsage => "CPU占用",
OverlayMetricItem.GpuUsage => "显卡占用",
OverlayMetricItem.MemoryUsage => "内存占用",
_ => item.ToString()
};
}
public static string GetToolTipText(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏当前渲染帧率。",
OverlayMetricItem.ProcessingCost => "BetterGI 每轮截图、识别和触发器处理的总耗时。",
OverlayMetricItem.PeakProcessingCost => "最近 5 秒内 BetterGI 单轮处理耗时的峰值。",
OverlayMetricItem.CaptureCost => "单次获取游戏画面的耗时。",
OverlayMetricItem.TriggerCost => "本轮实际执行触发器的总耗时。",
OverlayMetricItem.SkippedTicks => "上一轮未结束导致本秒跳过的调度次数。",
OverlayMetricItem.CpuUsage => "CPU 总占用率,读取不到时自动隐藏。",
OverlayMetricItem.GpuUsage => "显卡核心占用率,读取不到时自动隐藏。",
OverlayMetricItem.MemoryUsage => "系统内存占用率,读取不到时自动隐藏。",
_ => string.Empty
};
}
}
@@ -13,7 +13,7 @@ public partial class PathingPartyConfig : ObservableObject
{
// 配置是否启用,不启用会使用地图追踪内的条件配置
[ObservableProperty]
private bool _enabled = true;
private bool _enabled = false;
// 是否启用自动拾取
[ObservableProperty]
@@ -21,9 +21,6 @@ public partial class PathingPartyConfig : ObservableObject
// 切换到队伍的名称
[ObservableProperty]
private string _partyName = string.Empty;
[JsonIgnore]
public bool SkipPartySwitch { get; set; }
// 切换队伍前是否前往须弥七天神像
[ObservableProperty]
@@ -124,7 +121,7 @@ public partial class PathingPartyConfig : ObservableObject
//启用自动战斗配置
[ObservableProperty]
private bool _autoFightEnabled = true;
private bool _autoFightEnabled = false;
[ObservableProperty]
private AutoFightConfig _autoFightConfig = new();
@@ -50,10 +50,4 @@ public partial class ScriptConfig : ObservableObject
// 仓库新手教程是否已阅读
[ObservableProperty] private bool _guideStatus = false;
// 是否在启动时自动更新已订阅的脚本
[ObservableProperty] private bool _autoUpdateSubscribedScripts = false;
// 命令行启动时是否先自动更新已订阅脚本再执行命令
[ObservableProperty] private bool _autoUpdateBeforeCommandLineRun = false;
}
@@ -102,11 +102,6 @@ public partial class MouseKeyMonitor
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
if (SystemControl.IsGenshinImpactActive())
{
ChatUiHotkeyGuard.PrimeFromChatKey(e.KeyCode);
}
// 热键按下事件
HotKeyDown(sender, e);
@@ -44,14 +44,4 @@ public readonly record struct OcrVersionConfig(
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
public static OcrVersionConfig PpOcrV6 = new(
"PP-OCRv6",
OcrImgMode.BGR,
false,
new OcrNormalizeImage(
1.0f / 255.0f,
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Globalization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
@@ -100,9 +100,6 @@ public class OcrFactory : IDisposable
PaddleOcrModelConfig.V5 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5),
PaddleOcrModelConfig.V6 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V6),
PaddleOcrModelConfig.V4 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V4),
@@ -123,6 +120,7 @@ public class OcrFactory : IDisposable
};
}
public Task Unload()
{
if (_paddleOcrService is not IDisposable disposable)
@@ -13,17 +13,8 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
{
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
/// <summary>Gets or sets the detection side length limit used by the Python det preprocess.</summary>
public int LimitSideLen { get; set; } = 960;
/// <summary>Gets or sets the maximum size limit after resizing.</summary>
public int MaxSideLimit { get; set; } = 4000;
/// <summary>Gets or sets the side length limit type. Supports max/min/resize_long.</summary>
public string LimitType { get; set; } = "max";
/// <summary>Gets or sets the shortest side threshold used for tiny-image upscaling.</summary>
public int SmallImageLimitSideLen { get; set; } = 64;
/// <summary>Gets or sets the maximum size for resizing the input image.</summary>
public int? MaxSize { get; set; } = 960;
/// <summary>Gets or sets the size for dilation during preprocessing.</summary>
public int? DilatedSize { get; set; } = 2;
@@ -80,24 +71,20 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
var contours = dilated.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);
// PaddleOCR Python keeps ratio_h/ratio_w separately. Because we align det resize to that behavior,
// map contour points back with independent X/Y scales before building rotated rects.
var scaleX = 1.0 * src.Width / resizedSize.Width;
var scaleY = 1.0 * src.Height / resizedSize.Height;
// var size = src.Size();
var scaleRate = 1.0 * src.Width / resizedSize.Width;
var rects = contours
.Where(x => BoxScoreThreshold == null || GetScore(x, pred) > BoxScoreThreshold)
.Select(contour =>
contour.Select(point => new Point2f((float)(point.X * scaleX), (float)(point.Y * scaleY))).ToArray())
.Select(Cv2.MinAreaRect)
.Where(x => x.Size.Width > MinSize && x.Size.Height > MinSize)
.Select(rect =>
{
var minEdge = Math.Min(rect.Size.Width, rect.Size.Height);
Size2f newSize = new(
rect.Size.Width + UnclipRatio * minEdge,
rect.Size.Height + UnclipRatio * minEdge);
RotatedRect largerRect = new(rect.Center, newSize, rect.Angle);
(rect.Size.Width + UnclipRatio * minEdge) * scaleRate,
(rect.Size.Height + UnclipRatio * minEdge) * scaleRate);
RotatedRect largerRect = new(rect.Center * scaleRate, newSize, rect.Angle);
return largerRect;
})
.OrderBy(v => v.Center.Y)
@@ -120,14 +107,11 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
// Align with PaddleOCR Python DetResizeForTest:
// 1. tiny image padding when h + w < 64
// 2. keep current max/960 behavior for normal images
// 3. switch to limit_type=min for very small crops so det can see the text
using (var resized = MatResizeForDetection(padded))
// DetResizeForTest resize_long
using (var resized = MatResize(padded, MaxSize))
{
resizedSize = new Size(resized.Width, resized.Height);
padded = resized.Clone();
padded = MatPadding32(resized);
}
using (var _ = padded)
@@ -166,80 +150,19 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
/// <summary>
/// 按 PaddleOCR Python 的 DetResizeForTest 思路缩放图像:
/// 小图先补边,再按 max/min/resize_long 规则缩放,并对齐到 32 的倍数。
/// 按比例缩放图像,保持长边不超过 maxSize。
/// </summary>
/// <param name="src"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
private Mat MatResizeForDetection(Mat src)
private static Mat MatResize(Mat src, int? maxSize)
{
using var preprocessed = PrepareTinyImage(src);
if (maxSize == null) return src.Clone();
var size = preprocessed.Size();
var height = size.Height;
var width = size.Width;
var limitSideLen = LimitSideLen;
var limitType = LimitType;
if (Math.Min(height, width) < SmallImageLimitSideLen)
{
limitSideLen = SmallImageLimitSideLen;
limitType = "min";
}
var ratio = CalculateResizeRatio(width, height, limitSideLen, limitType);
var resizeHeight = (int)(height * ratio);
var resizeWidth = (int)(width * ratio);
if (Math.Max(resizeHeight, resizeWidth) > MaxSideLimit)
{
var maxSideRatio = 1.0 * MaxSideLimit / Math.Max(resizeHeight, resizeWidth);
resizeHeight = (int)(resizeHeight * maxSideRatio);
resizeWidth = (int)(resizeWidth * maxSideRatio);
}
resizeHeight = Math.Max((int)Math.Round(resizeHeight / 32.0) * 32, 32);
resizeWidth = Math.Max((int)Math.Round(resizeWidth / 32.0) * 32, 32);
if (resizeWidth <= 0 || resizeHeight <= 0)
{
throw new InvalidOperationException(
$"Invalid det resize target size: {resizeWidth}x{resizeHeight}, src={width}x{height}");
}
using var resized = preprocessed.Resize(new Size(resizeWidth, resizeHeight));
return MatPadding32(resized);
}
private static Mat PrepareTinyImage(Mat src)
{
if (src.Width + src.Height >= 64)
{
return src.Clone();
}
var newHeight = Math.Max(32, src.Height);
var newWidth = Math.Max(32, src.Width);
var padded = new Mat(newHeight, newWidth, src.Type(), Scalar.Black);
src.CopyTo(padded[new Rect(0, 0, src.Width, src.Height)]);
return padded;
}
private static double CalculateResizeRatio(int width, int height, int limitSideLen, string limitType)
{
return limitType switch
{
"max" => Math.Max(height, width) > limitSideLen
? 1.0 * limitSideLen / Math.Max(height, width)
: 1.0,
"min" => Math.Min(height, width) < limitSideLen
? 1.0 * limitSideLen / Math.Min(height, width)
: 1.0,
"resize_long" => 1.0 * limitSideLen / Math.Max(height, width),
_ => throw new ArgumentOutOfRangeException(nameof(limitType), limitType,
"limitType only supports max/min/resize_long")
};
var size = src.Size();
var longEdge = Math.Max(size.Width, size.Height);
var scaleRate = 1.0 * maxSize.Value / longEdge;
return scaleRate < 1.0 ? src.Resize(default, scaleRate, scaleRate) : src.Clone();
}
private static float GetScore(Point[] contour, Mat pred)
@@ -274,4 +197,4 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
public string GetConfigName => config.Name;
}
}
@@ -7,7 +7,6 @@ using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using YamlDotNet.Core;
@@ -101,7 +100,7 @@ public class PaddleOcrService : IOcrService, IDisposable
recognitionModel,
recognitionVersion,
recLabel ?? (() => DefaultRecLabelFunc(recognitionModel)),
preHeatImagePath ?? TestImagePath);
TestImagePath);
}
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
@@ -130,12 +129,6 @@ public class PaddleOcrService : IOcrService, IDisposable
BgiOnnxModel.PaddleOcrRecV5,
OcrVersionConfig.PpOcrV5);
public static readonly PaddleOcrModelType V6 = Create(
BgiOnnxModel.PaddleOcrDetV6,
OcrVersionConfig.PpOcrV6,
BgiOnnxModel.PaddleOcrRecV6,
OcrVersionConfig.PpOcrV6);
public static readonly PaddleOcrModelType V5Latin = Create(
BgiOnnxModel.PaddleOcrDetV5,
OcrVersionConfig.PpOcrV5,
@@ -253,7 +246,7 @@ public class PaddleOcrService : IOcrService, IDisposable
_localRecModel = modelsRec;
// 预热模型
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
// Debug输出结果
var preHeatResult = RunAll(preHeatImageMat, 1);
@@ -291,7 +284,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var str = _localRecModel.Run(mat).Text;
var time = Stopwatch.GetElapsedTime(startTime);
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
return str;
}
@@ -300,7 +293,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var result = RunAll(mat);
var time = Stopwatch.GetElapsedTime(startTime);
// Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
return result;
}
@@ -2,6 +2,7 @@ using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
@@ -94,33 +95,21 @@ public class Rec(
// .AsParallel()
.Select(src =>
{
Mat? channel3 = default;
try
using var channel3 = src.Channels() switch
{
channel3 = src.Channels() switch
{
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
return result;
}
finally
{
// Only dispose Mats created in this scope
if (channel3 != null && !ReferenceEquals(channel3, src))
{
channel3.Dispose();
}
}
return result;
})
.Select(inputTensor =>
{
@@ -152,46 +141,46 @@ public class Rec(
{
var resultArray = resultTensor.Item2;
var resultShape = resultTensor.Item1;
var labelCount = resultShape[2];
var charCount = resultShape[1];
GCHandle dataHandle = default;
try
{
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
var dataPtr = dataHandle.AddrOfPinnedObject();
var labelCount = resultShape[2];
var charCount = resultShape[1];
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
var batchOffset = i * charCount * labelCount;
for (var n = 0; n < charCount; ++n)
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
var rowOffset = batchOffset + n * labelCount;
var maxVal = float.MinValue;
var maxIndex = 0;
for (var c = 0; c < labelCount; c++)
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
for (var n = 0; n < charCount; ++n)
{
var value = resultArray[rowOffset + c];
if (value > maxVal)
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
var maxIdx = new int[2];
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
{
maxVal = value;
maxIndex = c;
score += (float)maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
}
lastIndex = maxIdx[1];
}
if (maxIndex > 0 && !(n > 0 && maxIndex == lastIndex))
{
score += maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIndex, labels));
}
lastIndex = maxIndex;
}
var text = sb.ToString();
return new OcrRecognizerResult(text, text.Length > 0 ? score / text.Length : 0);
})
.ToArray();
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
})
.ToArray();
}
finally
{
dataHandle.Free();
}
}).ToArray();
}
public string GetConfigName => config.Name;
}
}
@@ -407,11 +407,11 @@ public class BgiOnnxFactory
break;
case ProviderType.Cpu:
sessionOptions.AppendExecutionProvider_CPU();
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
// {
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
// }
if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
{
sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
}
break;
case ProviderType.Dnnl:
sessionOptions.AppendExecutionProvider_Dnnl();
@@ -44,29 +44,12 @@ public class BgiOnnxModel
/// </summary>
public static readonly BgiOnnxModel BgiWorld = Register("BgiTree", @"Assets\Model\World\bgi_world.onnx");
/// <summary>
/// 矿物识别模型
/// </summary>
public static readonly BgiOnnxModel BgiMine = Register("BgiMine", @"Assets\Model\Mine\bgi_mine.onnx");
/// <summary>
/// 角色识别
/// </summary>
public static readonly BgiOnnxModel BgiAvatarSide =
Register("BgiAvatarSide", @"Assets\Model\Common\avatar_side_classify_sim.onnx");
/// <summary>
/// Q技能冷却分类模型
/// </summary>
public static readonly BgiOnnxModel BgiQClassify =
Register("BgiQClassify", @"Assets\Model\Common\q_classify_sim.onnx");
/// <summary>
/// Silero 人声检测模型
/// </summary>
public static readonly BgiOnnxModel SileroVad =
Register("SileroVad", @"Assets\Model\Vad\silero_vad.onnx");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -79,12 +62,6 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrDetV5 =
Register("PpOcrDetV5", @"Assets\Model\PaddleOCR\Det\V5\PP-OCRv5_mobile_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 检测模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrDetV6 =
Register("PpOcrDetV6", @"Assets\Model\PaddleOCR\Det\V6\PP-OCRv6_small_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V4 识别模型
/// </summary>
@@ -103,12 +80,6 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrRecV5 =
Register("PpOcrRecV5", @"Assets\Model\PaddleOCR\Rec\V5\PP-OCRv5_mobile_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 识别模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrRecV6 =
Register("PpOcrRecV6", @"Assets\Model\PaddleOCR\Rec\V6\PP-OCRv6_small_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V5 拉丁文 识别模型
/// </summary>
@@ -168,4 +139,4 @@ public class BgiOnnxModel
RegisteredModels.Add(model);
return model;
}
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
@@ -8,9 +8,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
@@ -31,7 +31,7 @@ public class PickTextInference : ITextInference
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
_wordDictionary = JsonConvert.DeserializeObject<Dictionary<int, string>>(json) ??
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ??
throw new Exception("index_2_word.json deserialize failed");
}
@@ -116,4 +116,4 @@ public class PickTextInference : ITextInference
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
}
}
}
@@ -6,7 +6,7 @@ namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
public class TextInferenceFactory
{
public static readonly Lazy<ITextInference> Pick = new(() => Create(OcrEngineTypes.YapModel));
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
public static ITextInference Create(OcrEngineTypes type)
{
@@ -87,24 +87,4 @@ public static class CommonExtension
{
return list.ConvertAll(ToPoint2d);
}
/// <summary>
/// 将矩形钳位到指定尺寸范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, int maxWidth, int maxHeight)
{
int x1 = Math.Clamp(rect.X, 0, maxWidth);
int y1 = Math.Clamp(rect.Y, 0, maxHeight);
int x2 = Math.Clamp(rect.X + rect.Width, 0, maxWidth);
int y2 = Math.Clamp(rect.Y + rect.Height, 0, maxHeight);
return new Rect(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// 将矩形钳位到 Mat 范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, Mat mat)
{
return rect.ClampTo(mat.Cols, mat.Rows);
}
}
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
@@ -25,7 +24,7 @@ public static class Feature2DExtensions
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
{
Mat trainDescriptors = new();
var img = Bv.ImRead(trainImagePath, ImreadModes.Grayscale);
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
@@ -10,5 +10,4 @@ public enum PaddleOcrModelConfig
V5Latin = 4,
V5Eslav = 5,
V5Korean = 6,
V6 = 8,
}
}
@@ -1,99 +1,42 @@
using System;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using System.Threading;
namespace BetterGenshinImpact.Core.Script;
public class CancellationContext : Singleton<CancellationContext>
{
private readonly object _sync = new();
public CancellationTokenSource Cts { get; private set; } = new();
public CancellationTokenSource Cts { get; set; } = new();
public bool IsManualStop { get; private set; }
public bool IsCancellationRequested
{
get
{
lock (_sync)
{
return !disposed && Cts.IsCancellationRequested;
}
}
}
private bool disposed;
public void Set()
{
lock (_sync)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
public void ManualCancel()
{
CancellationTokenSource cts;
lock (_sync)
if (!disposed)
{
if (disposed)
{
return;
}
IsManualStop = true;
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
Cts.Cancel();
}
}
public void Cancel()
{
CancellationTokenSource cts;
lock (_sync)
if (!disposed)
{
if (disposed)
{
return;
}
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
Cts.Cancel();
}
}
public void Clear()
{
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
cts = Cts;
disposed = true;
}
cts.Dispose();
Cts.Dispose();
disposed = true;
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
@@ -12,13 +12,11 @@ public class AutoPathingScript
{
private object? _config = null;
private string _rootPath;
private readonly LimitedFile _autoPathingFile;
public AutoPathingScript(string rootPath, object? config)
{
_config = config;
_rootPath = rootPath;
_autoPathingFile = new LimitedFile(Global.Absolute(@"User\AutoPathing"));
}
public async Task Run(string json)
@@ -61,41 +59,7 @@ public class AutoPathingScript
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
public async Task RunFileFromUser(string path)
{
var json = await AutoPathingFile.ReadText(path);
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
await Run(json);
}
/// <summary>
/// 判断 AutoPathing 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => AutoPathingFile.IsExists(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => AutoPathingFile.IsFile(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => AutoPathingFile.IsFolder(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => AutoPathingFile.ReadPathSync(subPath);
/// <summary>
/// LimitedFile 实例,用于操作 AutoPathing 目录
/// </summary>
private LimitedFile AutoPathingFile => _autoPathingFile;
}
@@ -1,34 +0,0 @@
using Microsoft.ClearScript;
using System;
using System.Reflection;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class CustomHostFunctions : HostFunctions
{
/// <summary>
/// 创建指定维度的交错数组变量
/// </summary>
/// <typeparam name="T">数组元素类型</typeparam>
/// <param name="dimensions">数组维度</param>
/// <returns>交错数组变量</returns>
public object NewVarOfArr<T>(int dimensions)
{
try
{
Type arrayType = typeof(T);
for (int i = 0; i < dimensions; i++)
{
arrayType = arrayType.MakeArrayType();
}
MethodInfo newVarMethod = typeof(HostFunctions).GetMethod(nameof(newVar))!;
MethodInfo genericMethod = newVarMethod.MakeGenericMethod(arrayType);
return genericMethod.Invoke(this, new object?[] { null })!;
}
catch (Exception ex)
{
throw new InvalidOperationException($"创建维度为 {dimensions} 的数组失败: {ex.Message}", ex);
}
}
}
@@ -1,11 +1,9 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoWood;
@@ -18,12 +16,9 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -191,24 +186,13 @@ public class Dispatcher
return null;
}
return await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
case "AutoBoss":
var autoBossConfig = TaskContext.Instance().Config.AutoBossConfig;
if (taskSettingsPageViewModel.GetFightStrategy(autoBossConfig.StrategyName, out var autoBossPath))
{
return null;
}
return await new AutoBossTask(new AutoBossParam(autoBossPath)).Start(cancellationToken);
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
return null;
case "AutoFishing":
await new AutoFishingTask(AutoFishingTaskParam.BuildFromSoloTaskConfig(soloTask.Config)).Start(
cancellationToken);
return null;
case "AutoCook":
await new AutoCookTask().Start(cancellationToken);
return null;
case "AutoEat":
{
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodName", (string?)null);
@@ -281,15 +265,16 @@ public class Dispatcher
GridScreenName gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null) ?? throw new Exception("gridScreenName为空或错误");
string? itemName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "itemName", (string?)null);
IEnumerable<string>? itemNames = ScriptObjectConverter.GetValue<string>((ScriptObject)soloTask.Config, "itemNames");
CountInventoryItemParam param = new()
if (itemName != null && itemNames != null)
{
GridScreenName = gridScreenName,
ItemName = itemName,
ItemNames = itemNames?.ToList() ?? []
};
var result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时使用");
}
if (itemName == null && itemNames == null)
{
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时为空");
}
var result = await new CountInventoryItem(gridScreenName, itemName, itemNames).Start(cancellationToken);
if (itemName != null)
{
return result;
}
@@ -327,7 +312,7 @@ public class Dispatcher
/// <param name="param">秘境任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task<Dictionary<string, int>> RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
public async Task RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
{
if (param == null)
{
@@ -335,26 +320,9 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
return await new AutoDomainTask(param).Start(cancellationToken);
await new AutoDomainTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动首领讨伐任务
/// </summary>
/// <param name="param">自动首领讨伐任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task<Dictionary<string, int>> RunAutoBossTask(AutoBossParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动首领讨伐任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
return await new AutoBossTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动战斗任务
/// </summary>
@@ -369,76 +337,6 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
var factory = GameTask.AutoFight.Factory.CombatTaskFactoryProvider.GetFactory(param.CombatStrategyPath);
var fightTask = factory.CreateTask(param);
await fightTask.Start(cancellationToken);
}
/// <summary>
/// 运行自动地脉花任务
/// </summary>
/// <param name="param">自动地脉花任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoLeyLineOutcropTask(AutoLeyLineOutcropParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动地脉花任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoLeyLineOutcropTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动幽境危战任务
/// </summary>
/// <param name="param">自动幽境危战任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoStygianOnslaughtTask(AutoStygianOnslaughtParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动幽境危战任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoStygianOnslaughtTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行背包物品计数任务。
/// </summary>
/// <param name="param">背包物品计数参数。</param>
/// <param name="customCt">自定义取消令牌。</param>
/// <returns>单物品返回数量;多物品返回名称到数量的脚本对象。</returns>
public async Task<object?> RunCountInventoryItemTask(CountInventoryItemParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "背包物品计数参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
object result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
{
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;
}
await new AutoFightTask(param).Start(cancellationToken);
}
}
@@ -43,15 +43,6 @@ public class Genshin
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 通过 OCR 识别当前角色的 UID
/// </summary>
/// <returns>UID 数字,如果识别失败则返回 0</returns>
public Task<int> Uid()
{
return Task.FromResult(Bv.Uid());
}
public Lazy<NavigationInstance> LazyNavigationInstance { get; } = new(() =>
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
@@ -216,11 +207,6 @@ public class Genshin
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
public Point2f? GetPositionFromMapWithMatchingMethod(string matchingMethod)
{
return GetPositionFromMapWithMatchingMethod(nameof(MapTypes.Teyvat), matchingMethod);
}
public float GetCameraOrientation()
{
@@ -235,18 +221,14 @@ public class Genshin
/// <param name="cacheTimeMs">缓存时间,单位毫秒,默认900ms</param>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f? GetPositionFromMap(string mapName, int cacheTimeMs = 900)
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return GetPositionFromMapWithMatchingMethod(mapName,matchingMethod, cacheTimeMs);
}
public Point2f? GetPositionFromMapWithMatchingMethod(string mapName, string matchingMethod, int cacheTimeMs = 900)
{
var imageRegion = CaptureToRectArea();
if (!Bv.IsInMainUi(imageRegion))
{
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
}
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return MapManager.GetMap(mapName, matchingMethod)
.ConvertImageCoordinatesToGenshinMapCoordinates(LazyNavigationInstance.Value
.GetPositionStableByCache(imageRegion, mapName, matchingMethod, cacheTimeMs));
@@ -361,18 +343,6 @@ public class Genshin
await new GoToCraftingBenchTask().Start(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 在当前已打开的合成界面中合成指定材料。
/// </summary>
/// <param name="materialName">目标成品材料名。</param>
/// <param name="quantity">目标合成个数,必须大于 0。</param>
/// <param name="materialType">材料筛选类型;为空时从物品模型 CSV 中读取。</param>
/// <returns>合成执行结果。</returns>
public async Task<CraftMaterialResult> CraftMaterial(string materialName, int quantity, string? materialType = null)
{
return await new CraftMaterialTask(materialName, quantity, materialType).Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 返回主界面
/// </summary>
@@ -448,17 +418,4 @@ public class Genshin
throw new ArgumentException($"无效的分钟值: {minute},必须是 0-59 之间的整数字符", nameof(minute));
await new SetTimeTask().Start(h, m, CancellationContext.Instance.Cts.Token, skip);
}
// /// <summary>
// /// 莉奈娅挖矿,调试使用,暂时注释
// /// </summary>
// /// <param name="mineCount">射箭次数,默认1</param>
// /// <param name="scanRounds">大循环寻矿次数。不传则默认5;传单个数字时与射箭次数相同</param>
// public async Task StartMining(int? mineCount = null, int? scanRounds = null)
// {
// var actualMine = mineCount ?? 1;
// var actualScan = scanRounds ?? (mineCount ?? 5);
// if (actualScan < actualMine) actualScan = actualMine;
// await new LinneaMiningTask(actualScan, actualMine).Start(CancellationContext.Instance.Cts.Token);
// }
}
}
@@ -1,410 +0,0 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// HTML遮罩层 - JS脚本依赖类
/// 提供窗口管理与消息通信功能
/// </summary>
public class HtmlMask : IDisposable
{
private static readonly JsonSerializerOptions _jsonOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false
};
/// <summary>
/// 通信消息结构
/// </summary>
public class Message
{
public string Url { get; set; } = "";
public JsonElement? Data { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? RequestId { get; set; }
}
/// <summary>
/// 脚本到HTML的待推送队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _toHtmlQueues = new();
/// <summary>
/// HTML到脚本的消息队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _fromHtmlQueues = new();
/// <summary>
/// JS到HTML请求的等待句柄,用于request-response匹配
/// </summary>
private static readonly ConcurrentDictionary<string, TaskCompletionSource<string>> _jsPendingRequests = new();
/// <summary>
/// requestId到windowId的映射,用于窗口关闭时取消对应的pending请求
/// </summary>
private static readonly ConcurrentDictionary<string, string> _requestWindowMap = new();
private readonly string _workDir;
private readonly List<string> _openedWindows = [];
private readonly object _openedWindowsLock = new();
private bool _disposed;
public HtmlMask(string workDir)
{
_workDir = workDir;
}
#region 窗口管理
/// <summary>
/// 显示HTML遮罩窗口
/// </summary>
public string Show(string url, string? id = null)
{
try
{
if (string.IsNullOrWhiteSpace(url))
throw new ArgumentException("URL不能为空");
string finalUrl;
if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
finalUrl = url;
}
else
{
// 禁止 file:// 绝对路径,仅允许脚本目录下的相对路径
string absPath = ScriptUtils.NormalizePath(_workDir, url);
finalUrl = new Uri(absPath).AbsoluteUri;
}
string windowId = HtmlMaskWindow.Show(finalUrl, id, _workDir);
_toHtmlQueues[windowId] = new ConcurrentQueue<Message>();
_fromHtmlQueues[windowId] = new ConcurrentQueue<Message>();
lock (_openedWindowsLock) { _openedWindows.Add(windowId); }
return windowId;
}
catch (Exception ex)
{
TaskControl.Logger.LogError(ex, "打开HTML遮罩失败: {Url}", url);
throw;
}
}
/// <summary>
/// 关闭指定窗口
/// </summary>
public bool Close(string id)
{
lock (_openedWindowsLock) { _openedWindows.Remove(id); }
CleanupQueues(id);
return HtmlMaskWindow.Close(id);
}
/// <summary>
/// 关闭所有由本实例打开的窗口
/// </summary>
public void CloseAll()
{
List<string> windows;
lock (_openedWindowsLock)
{
windows = [.. _openedWindows];
_openedWindows.Clear();
}
foreach (var windowId in windows)
{
CleanupQueues(windowId);
HtmlMaskWindow.Close(windowId);
}
}
/// <summary>
/// 获取所有窗口ID
/// </summary>
public string[] GetWindowIds() => HtmlMaskWindow.GetWindowIds();
/// <summary>
/// 窗口是否存在
/// </summary>
public bool Exists(string id) => HtmlMaskWindow.Exists(id);
/// <summary>
/// 设置窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThrough(string windowId, bool enabled)
{
HtmlMaskWindow.SetClickThrough(windowId, enabled);
}
/// <summary>
/// 获取窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>true=点击穿透,false=可交互</returns>
public bool GetClickThrough(string windowId)
{
return HtmlMaskWindow.GetClickThrough(windowId);
}
/// <summary>
/// 切换窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public void ToggleClickThrough(string windowId)
{
HtmlMaskWindow.ToggleClickThrough(windowId);
}
#endregion
#region 消息通信
/// <summary>
/// 发送消息到HTML(单向推送)
/// </summary>
public void Send(string windowId, string url, string jsonData)
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData)
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 响应 HTML 页面通过 window.htmlMask.request(...) 发起的请求。
/// </summary>
/// <param name="windowId">HTML 遮罩窗口 ID。</param>
/// <param name="requestId">从 Receive/Poll/PollAll 返回消息的 requestId 字段取得,不能由脚本自行生成。</param>
/// <param name="jsonData">响应数据,必须是合法 JSON 字符串。</param>
public void Respond(string windowId, string requestId, string jsonData)
{
if (string.IsNullOrWhiteSpace(requestId))
throw new ArgumentException("requestId cannot be empty", nameof(requestId));
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = "/__response__",
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 发送请求到HTML并等待响应
/// </summary>
/// <param name="windowId">目标窗口ID</param>
/// <param name="url">接口路径</param>
/// <param name="jsonData">JSON数据</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Request(string windowId, string url, string jsonData, int timeoutMs = 0)
{
var requestId = Guid.NewGuid().ToString("N");
var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
_jsPendingRequests[requestId] = tcs;
_requestWindowMap[requestId] = windowId;
try
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
if (timeoutMs > 0)
{
using var cts = new System.Threading.CancellationTokenSource(timeoutMs);
await using var registration = cts.Token.Register(() =>
{
if (_jsPendingRequests.TryRemove(requestId, out var pending))
pending.TrySetResult(null!);
});
return await tcs.Task;
}
return await tcs.Task;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
_jsPendingRequests.TryRemove(requestId, out _);
_requestWindowMap.TryRemove(requestId, out _);
}
}
/// <summary>
/// 等待接收来自HTML的一条消息
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Receive(string windowId, int timeoutMs = 0)
{
if (!_fromHtmlQueues.TryGetValue(windowId, out var queue))
return null;
var sw = System.Diagnostics.Stopwatch.StartNew();
while (true)
{
if (queue.TryDequeue(out var message))
return JsonSerializer.Serialize(message, _jsonOptions);
if (_disposed || !_fromHtmlQueues.ContainsKey(windowId) || !HtmlMaskWindow.Exists(windowId))
return null;
if (timeoutMs > 0 && sw.ElapsedMilliseconds > timeoutMs)
return null;
await Task.Delay(50);
}
}
/// <summary>
/// 轮询来自HTML的消息(非阻塞)
/// </summary>
public string? Poll(string windowId)
{
if (_fromHtmlQueues.TryGetValue(windowId, out var queue) &&
queue.TryDequeue(out var message))
{
return JsonSerializer.Serialize(message, _jsonOptions);
}
return null;
}
/// <summary>
/// 批量获取来自HTML的所有消息
/// </summary>
public string PollAll(string windowId)
{
var messages = new List<Message>();
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var message))
{
messages.Add(message);
}
}
return JsonSerializer.Serialize(messages, _jsonOptions);
}
#endregion
#region 内部方法
/// <summary>
/// 将待推送队列中的消息通过回调逐一发出
/// </summary>
internal static void FlushPendingMessages(string windowId, Action<string> postAction)
{
if (_toHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var msg))
{
postAction(JsonSerializer.Serialize(msg, _jsonOptions));
}
}
}
/// <summary>
/// HTML端发来的消息入队,如果是JS请求的响应则直接resolve
/// </summary>
internal static void SendFromHtml(string windowId, string url, string data, string? requestId = null)
{
// 匹配JS端pending的request
if (requestId != null && _jsPendingRequests.TryRemove(requestId, out var tcs))
{
var parsed = ParseData(data);
tcs.TrySetResult(parsed != null ? parsed.Value.GetRawText() : "null");
return;
}
// 普通消息入队
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(data),
RequestId = requestId
});
}
}
private static JsonElement? ParseData(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.Clone();
}
catch
{
// 不是合法JSON,作为纯文本包装
return JsonSerializer.SerializeToElement(json, _jsonOptions);
}
}
private static void CleanupQueues(string windowId)
{
_toHtmlQueues.TryRemove(windowId, out _);
_fromHtmlQueues.TryRemove(windowId, out _);
// 取消该窗口关联的待响应请求
foreach (var kvp in _requestWindowMap)
{
if (kvp.Value == windowId && _jsPendingRequests.TryRemove(kvp.Key, out var tcs))
{
tcs.TrySetCanceled();
}
}
}
#endregion
public void Dispose()
{
if (_disposed) return;
_disposed = true;
CloseAll();
}
}
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
@@ -42,9 +40,6 @@ public class KeyMouseHook: IDisposable
private EventHandler<MouseEventExtArgs>? _mouseMoveExtHandler;
private EventHandler<MouseEventExtArgs>? _mouseWheelExtHandler;
private readonly object _mouseMoveLock = new();
private DateTime _lastProcessMouseMoveTime = DateTime.MinValue;
private readonly ILogger<KeyMouseHook> _logger = App.GetLogger<KeyMouseHook>();
/// <summary>
@@ -115,259 +110,182 @@ public class KeyMouseHook: IDisposable
}
}
private readonly System.Threading.Channels.Channel<Action> _eventChannel =
System.Threading.Channels.Channel.CreateBounded<Action>(
new System.Threading.Channels.BoundedChannelOptions(2048)
{
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
private readonly CancellationTokenSource _cts = new();
public KeyMouseHook()
{
// 启动后台事件处理器,确保不阻塞钩子线程
_ = Task.Run(async () =>
{
try
{
var reader = _eventChannel.Reader;
while (await reader.WaitToReadAsync(_cts.Token))
{
while (reader.TryRead(out var action))
{
try
{
action();
}
catch (Exception ex)
{
// 内部错误已在 action 闭包中通过 HandleCallbackException 处理
}
}
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex, "键鼠钩子后台处理器发生异常");
}
});
// 初始化事件处理程序
_keyDownHandler = (_, args) =>
{
if (_keyDownDataCallbacks.Count == 0 && _keyDownCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyDownDataCallbacksCopy = new List<ScriptObject>(_keyDownDataCallbacks);
var keyDownCodeCallbacksCopy = new List<ScriptObject>(_keyDownCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘按下回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
};
_keyUpHandler = (_, args) =>
{
if (_keyUpDataCallbacks.Count == 0 && _keyUpCodeCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var keyUpDataCallbacksCopy = new List<ScriptObject>(_keyUpDataCallbacks);
var keyUpCodeCallbacksCopy = new List<ScriptObject>(_keyUpCodeCallbacks);
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘释放回调");
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
};
_mouseDownExtHandler = (_, args) =>
{
if (_mouseDownCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseDownCallbacksCopy = new List<ScriptObject>(_mouseDownCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标按下回调");
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
};
_mouseUpExtHandler = (_, args) =>
{
if (_mouseUpCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseUpCallbacksCopy = new List<ScriptObject>(_mouseUpCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseUpCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
}))
foreach (var callback in mouseUpCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标释放回调");
try
{
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
};
_mouseMoveExtHandler = (_, args) =>
{
if (_mouseMoveCallbacks.Count == 0) return;
var now = DateTime.Now;
if ((now - _lastProcessMouseMoveTime).TotalMilliseconds < 10) return;
_lastProcessMouseMoveTime = now;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseMoveCallbacksCopy = new List<ScriptObject>(_mouseMoveCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
if (!_eventChannel.Writer.TryWrite(() =>
foreach (var callback in mouseMoveCallbacksCopy)
{
try
{
foreach (var callback in mouseMoveCallbacksCopy)
// 获取回调的间隔时间
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval))
{
try
// 获取上次调用时间
if (_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
lock (_mouseMoveLock)
// 计算时间差
var timeSpan = now - lastTime;
// 如果时间差大于等于间隔时间,则执行回调
if (timeSpan.TotalMilliseconds >= interval)
{
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval) &&
_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
var timeSpan = now - lastTime;
if (timeSpan.TotalMilliseconds >= interval)
{
callback.InvokeAsFunction(localX, localY);
_lastMouseMoveCallbackTimes[callback] = now;
}
}
callback.InvokeAsFunction(localX, localY);
// 更新上次调用时间
_lastMouseMoveCallbackTimes[callback] = now;
}
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标移动回调");
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
};
_mouseWheelExtHandler = (_, args) =>
{
if (_mouseWheelCallbacks.Count == 0) return;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
var mouseWheelCallbacksCopy = new List<ScriptObject>(_mouseWheelCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
var delta = args.Delta;
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseWheelCallbacksCopy)
{
try
{
callback.InvokeAsFunction(delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
}))
foreach (var callback in mouseWheelCallbacksCopy)
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标滚轮回调");
try
{
callback.InvokeAsFunction(args.Delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
};
@@ -458,8 +376,6 @@ public class KeyMouseHook: IDisposable
{
if (disposing)
{
_cts.Cancel();
_eventChannel.Writer.TryComplete();
// 移除所有事件监听器
if (_keyDownHandler != null)
{
@@ -1,7 +1,5 @@
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.Core.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenCvSharp;
@@ -15,7 +13,6 @@ public class LimitedFile(string rootPath)
{
/// <summary>
/// 读取指定文件夹内所有文件和文件夹的路径(非递归方式)。
/// 目录不存在时返回空数组
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
@@ -24,19 +21,19 @@ public class LimitedFile(string rootPath)
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
string normalizedFolderPath = NormalizePath(folderPath);
if (!Directory.Exists(fullPath))
// 确保目录存在
if (!Directory.Exists(normalizedFolderPath))
{
TaskControl.Logger.LogError("ReadPathSync 目录不存在: {Path}", fullPath);
return Array.Empty<string>();
Directory.CreateDirectory(normalizedFolderPath);
}
// 获取指定文件夹下的所有文件(非递归)
string[] files = Directory.GetFiles(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 获取指定文件夹下的所有子文件夹(非递归)
string[] directories = Directory.GetDirectories(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 合并文件和文件夹路径
string[] combined = files.Concat(directories).ToArray();
@@ -46,33 +43,12 @@ public class LimitedFile(string rootPath)
}
catch (Exception ex)
{
// 记录异常并返回空数组
TaskControl.Logger.LogError("ReadPathSync 异常: {Message}", ex.Message);
return Array.Empty<string>();
}
}
/// <summary>
/// 创建指定路径的目录,如果已存在则跳过
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>是否创建成功或目录已存在</returns>
public bool CreateDirectory(string folderPath)
{
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
// 如果目录不存在,自动创建
if (!Directory.Exists(fullPath)){Directory.CreateDirectory(fullPath);}
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("CreateDir 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定路径是否为文件夹。
/// </summary>
@@ -96,44 +72,6 @@ public class LimitedFile(string rootPath)
}
}
/// <summary>
/// 判断指定路径是否为文件
/// </summary>
/// <param name="path">文件路径(相对于根目录)</param>
/// <returns>如果是文件则返回 true,否则返回 false</returns>
public bool IsFile(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsFile 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定的文件或目录是否存在
/// </summary>
/// <param name="path">文件或目录路径(相对于根目录)</param>
/// <returns>如果存在返回 true,否则返回 false</returns>
public bool IsExists(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath) || Directory.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsExists 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// Normalize and validate a path.
/// </summary>
@@ -509,51 +447,4 @@ public class LimitedFile(string rootPath)
return true;
}
/// <summary>
/// 重命名文件或文件夹(相对于根目录)
/// </summary>
/// <param name="oldPath">原路径</param>
/// <param name="newPath">新路径</param>
/// <returns>是否重命名成功</returns>
public bool RenamePathSync(string oldPath, string newPath)
{
try
{
// 标准化路径
oldPath = NormalizePath(oldPath);
newPath = NormalizePath(newPath);
// 检查原路径是否存在
if (!File.Exists(oldPath) && !Directory.Exists(oldPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 原路径不存在 {Path}", oldPath);
return false;
}
//验证扩展名合法性
if (File.Exists(oldPath) && !IsValid(newPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 新文件路径不合法 {Path}", newPath);
return false;
}
// 确保目标目录存在
string? directoryPath = Path.GetDirectoryName(newPath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// 执行重命名
Directory.Move(oldPath, newPath);
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("RenamePathSync 异常: {Message}", ex.Message);
return false;
}
}
}
@@ -1,43 +0,0 @@
using System;
using System.Linq;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// 战斗策略文件访问类
/// 提供JS脚本环境访问 User\AutoFight 目录下战斗策略文件的方法
/// </summary>
public class StrategyFile
{
private readonly LimitedFile _strategyFile = new(Global.Absolute(@"User\AutoFight"));
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => _strategyFile.IsFolder(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => _strategyFile.IsFile(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => _strategyFile.IsExists(subPath);
/// <summary>
/// 读取 User\AutoFight 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的子目录路径,默认为根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => _strategyFile.ReadPathSync(subPath);
}
@@ -1,24 +1,18 @@
using System;
using System;
using System.Collections.Generic;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.BgiVision;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.Model.GameUI;
namespace BetterGenshinImpact.Core.Script;
@@ -77,33 +71,16 @@ public class EngineExtend
engine.AddHostType("ServerTime", typeof(ServerTime));
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("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
engine.AddHostObject("strategyFile", new StrategyFile());
//鼠标回调
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
// 添加C#的类型
engine.AddHostType(typeof(Task));
// 新的BvPage类
engine.AddHostType("BvPage", typeof(BvPage));
engine.AddHostType("BvLocator", typeof(BvLocator));
engine.AddHostType("BvImage", typeof(BvImage));
engine.AddHostObject("host", new CustomHostFunctions());
// HTML 遮罩
engine.AddHostObject("htmlMask", new HtmlMask(workDir));
// 导入 JavaScript 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.AllowCategoryMismatch;
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
if (searchPaths != null)
{
var normalizedPaths = new List<string>();
@@ -216,9 +216,6 @@ public partial class ScriptGroupProject : ObservableObject
}
JsScriptSettingsObject ??= new ExpandoObject();
// 清理配置中的无效值
CleanInvalidSettingsValues();
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
await Project.ExecuteAsync(JsScriptSettingsObject, pathingPartyConfig);
}
@@ -339,67 +336,6 @@ public partial class ScriptGroupProject : ObservableObject
{
OnPropertyChanged(nameof(ScheduleDesc));
}
/// <summary>
/// 清理 JsScriptSettingsObject 中不在 settings.json 定义的 Options 列表中的无效值
/// </summary>
private void CleanInvalidSettingsValues()
{
if (Project == null || JsScriptSettingsObject == null)
{
return;
}
try
{
// 加载 settings.json 中定义的配置项
var settingItems = Project.Manifest.LoadSettingItems(Project.ProjectPath);
if (settingItems.Count == 0)
{
return;
}
var settingsDict = JsScriptSettingsObject as IDictionary<string, object?>;
if (settingsDict == null)
{
return;
}
// 遍历所有 multi-checkbox 类型的配置项
foreach (var item in settingItems.Where(i => i.Type == "multi-checkbox"))
{
if (!settingsDict.ContainsKey(item.Name))
{
continue;
}
// 获取当前保存的值
var savedValue = settingsDict[item.Name];
List<string>? checkedValues = null;
if (savedValue is List<string> stringList)
{
checkedValues = stringList;
}
else if (savedValue is List<object> objectList)
{
checkedValues = objectList.Select(i => (string)i).ToList();
settingsDict[item.Name] = checkedValues;
}
// 清理不在 Options 列表中的无效值
if (checkedValues != null && item.Options != null)
{
checkedValues.RemoveAll(value => !item.Options.Contains(value));
}
}
}
catch (Exception ex)
{
// 清理失败不影响脚本执行,只记录日志
TaskControl.Logger.LogDebug(ex, "清理JS脚本配置中的无效值时发生异常");
}
}
}
public class ScriptGroupProjectExtensions
@@ -1,189 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DefaultDocumentLoader
{
private readonly string _scriptRootPath;
public PackageDocumentLoader(string scriptRootPath)
{
_scriptRootPath = Path.GetFullPath(scriptRootPath);
}
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
// ResolvePhysicalPath 可能因 sourceInfo 为空而失败,直接从脚本根目录兜底
if (targetPath == null || !File.Exists(targetPath))
{
var stripped = Regex.Replace(specifier, @"^(?:\.\.?/)+", "");
if (!Path.IsPathRooted(stripped))
{
var fullPath = Path.GetFullPath(Path.Combine(_scriptRootPath, stripped));
if (fullPath.StartsWith(_scriptRootPath, StringComparison.OrdinalIgnoreCase)
&& File.Exists(fullPath))
{
targetPath = fullPath;
}
}
}
if (targetPath == null || !File.Exists(targetPath))
{
throw new FileNotFoundException($"无法解析模块导入路径: '{specifier}'", specifier);
}
// 处理 JS 文件的重写
if (Path.GetExtension(targetPath).ToLower() == ".js")
{
var uri = new Uri(targetPath);
// 检查缓存
var cached = GetCachedDocument(uri);
if (cached != null) return cached;
string content = await File.ReadAllTextAsync(targetPath);
string processedCode = RewriteScriptCode(content, targetPath);
var documentInfo = new DocumentInfo(uri) { Category = ModuleCategory.Standard };
return CacheDocument(new StringDocument(documentInfo, processedCode), false);
}
throw new FileNotFoundException($"不支持的模块导入类型: '{specifier}' (仅支持 .js 文件)", specifier);
}
/// <summary>
/// js重写
/// </summary>
public string RewriteScriptCode(string code, string currentFilePath)
{
if (string.IsNullOrEmpty(code)) return code;
string result = code.Replace("../../../packages", "packages");
// 拦截资源导入
var resourceRegex = new Regex(@"import\s+([\w\d_*$]+|[\s\S]*?)\s+from\s+(['""])([^'""\n]+)(['""])");
result = resourceRegex.Replace(result, match =>
{
string importPart = match.Groups[1].Value.Trim();
string quote = match.Groups[2].Value;
string path = match.Groups[3].Value.Replace("../../../packages", "packages");
string? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
if (resourceFullPath != null && File.Exists(resourceFullPath))
{
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
bool isJs = resourceFullPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase);
bool isImage = IsImageFile(resourceFullPath);
// 图片 -> Mat
if (isImage)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadImageMatSync({quote}{normalizedPath}{quote});";
}
// 非 JS 资源 -> 文本内容
if (!isJs)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadTextSync({quote}{normalizedPath}{quote});";
}
}
return match.Value;
});
return result;
}
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
string? referrer = null;
if (sourceInfo.HasValue)
{
var sourceUri = sourceInfo.Value.Uri;
if (sourceUri != null && sourceUri.IsAbsoluteUri && sourceUri.IsFile)
{
referrer = sourceUri.LocalPath;
}
else if (!string.IsNullOrEmpty(sourceInfo.Value.Name))
{
if (Uri.TryCreate(sourceInfo.Value.Name, UriKind.Absolute, out var nameUri) && nameUri.IsFile)
{
referrer = nameUri.LocalPath;
}
}
}
return ResolvePathInternal(settings.SearchPath, referrer, specifier);
}
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
{
if (specifier.StartsWith("packages/", StringComparison.OrdinalIgnoreCase))
{
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
var packagesMatch = Regex.Match(specifier, @"^(?:\.\.\/)+(packages/.*)$");
if (packagesMatch.Success)
{
return ProbeFile(Path.Combine(_scriptRootPath, packagesMatch.Groups[1].Value));
}
if (specifier.StartsWith("."))
{
if (!string.IsNullOrEmpty(referrer))
{
string? dir = Path.GetDirectoryName(referrer);
if (dir != null)
{
return ProbeFile(Path.GetFullPath(Path.Combine(dir, specifier)));
}
}
}
if (!string.IsNullOrEmpty(searchPath))
{
var paths = searchPath.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var p in paths)
{
string combined = Path.Combine(p, specifier);
string? found = ProbeFile(combined);
if (found != null) return found;
}
}
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
private string? ProbeFile(string path)
{
try
{
var normalized = Path.GetFullPath(path);
if (File.Exists(normalized)) return normalized;
if (File.Exists(normalized + ".js")) return normalized + ".js";
}
catch { }
return null;
}
private static bool IsImageFile(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string ext = Path.GetExtension(path).ToLower();
string[] imageExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp" };
return imageExtensions.Contains(ext);
}
}
}
@@ -2,18 +2,13 @@ using BetterGenshinImpact.Core.Config;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.ClearScript.JavaScript;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Project;
@@ -34,7 +29,6 @@ public class ScriptProject
{
throw new DirectoryNotFoundException("脚本文件夹不存在:" + ProjectPath);
}
ManifestFile = Path.GetFullPath(Path.Combine(ProjectPath, "manifest.json"));
if (!File.Exists(ManifestFile))
{
@@ -52,7 +46,6 @@ public class ScriptProject
{
return null;
}
var stackPanel = new StackPanel
{
Margin = new Thickness(0, 0, 20, 0) // 给右侧滚动条留出位置
@@ -76,60 +69,33 @@ public class ScriptProject
return scrollViewer;
}
private IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig)
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
{
V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
// packages 依赖和资源重载
var loader = new PackageDocumentLoader(ProjectPath);
engine.DocumentSettings.Loader = loader;
// 添加 packages 到搜索路径
var libraries = new HashSet<string>(Manifest.Library ?? Array.Empty<string>())
{
".",
"./packages"
};
var libraryList = libraries.ToList();
EngineExtend.InitHost(engine, ProjectPath, libraryList.ToArray(), partyConfig);
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
return engine;
}
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig = null)
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig=null)
{
// 默认值
GlobalMethod.SetGameMetrics(1920, 1080);
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine(partyConfig);
// 使用自定义加载器解析脚本文件
var loader = (PackageDocumentLoader)engine.DocumentSettings.Loader;
if (context != null)
{
// 写入配置的内容
engine.AddHostObject("settings", context);
}
try
{
bool useModule = Manifest.Library.Length != 0 ||
code.Contains("import ", StringComparison.Ordinal) ||
code.Contains("export ", StringComparison.Ordinal);
if (useModule)
if (Manifest.Library.Length != 0)
{
// 清除Document缓存
DocumentLoader.Default.DiscardCachedDocuments();
string mainScriptPath = Path.Combine(ProjectPath, Manifest.Main);
string runtimeCode = loader.RewriteScriptCode(code, mainScriptPath);
var documentInfo = new DocumentInfo(new Uri(mainScriptPath)) { Category = ModuleCategory.Standard };
var evaluation = engine.Evaluate(documentInfo, runtimeCode);
var evaluation = engine.Evaluate(new DocumentInfo { Category = ModuleCategory.Standard }, code);
if (evaluation is Task task) await task;
}
else
@@ -145,16 +111,6 @@ public class ScriptProject
}
finally
{
// 终止代码执行
try
{
engine.Interrupt();
}
catch (Exception e)
{
TaskControl.Logger.LogError(e, "中断脚本执行异常:" + e.Message);
}
engine.Dispose();
}
}
@@ -169,4 +125,4 @@ public class ScriptProject
return code;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -84,7 +84,7 @@ public class FileAccessBridge
// if (!string.IsNullOrEmpty(directory))
// Directory.CreateDirectory(directory);
File.WriteAllText(fullPath, content, new UTF8Encoding(false));
File.WriteAllText(fullPath, content, Encoding.UTF8);
}
catch (Exception ex)
{
@@ -1,11 +1,13 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.Service;
using Serilog.Core;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script.WebView;
@@ -21,17 +23,4 @@ public class MapEditorWebBridge
{
TaskContext.Instance().Config.DevConfig.RecordMapName = mapName;
}
public async Task RunPathing(string json)
{
await ScriptService.StartGameTask();
SystemControl.ActivateWindow();
await new TaskRunner().RunThreadAsync(async () =>
{
var task = PathingTask.BuildFromJson(json);
var pathExecutor = new PathExecutor(CancellationContext.Instance.Cts.Token);
pathExecutor.PartyConfig = new PathingPartyConfig { AutoFightEnabled = false };
await pathExecutor.Pathing(task);
});
}
}
}
@@ -78,28 +78,6 @@ public sealed class RepoWebBridge
return await File.ReadAllTextAsync(userConfigPath);
}
/// <summary>
/// 获取当前仓库的已订阅脚本路径列表(JSON 数组)。
/// 相比 GetUserConfigJson() 更轻量,仅返回当前仓库的订阅路径。
/// </summary>
public string GetSubscribedScriptPaths()
{
try
{
var paths = ScriptRepoUpdater.GetSubscribedPathsForCurrentRepo();
if (paths.Count > 0)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(paths);
}
return "[]";
}
catch
{
return "[]";
}
}
public Task<string> GetFile(string relPath)
{
try
@@ -205,7 +183,7 @@ public sealed class RepoWebBridge
throw new FileNotFoundException("找不到原始 repo.json 文件");
}
string targetPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string targetPath = Path.Combine(ScriptRepoUpdater.ReposPath, "repo_updated.json");
File.Copy(repoJsonPath, targetPath, overwrite: true);
@@ -250,7 +228,10 @@ public sealed class RepoWebBridge
private static string GetRepoJsonPath()
{
string updatedRepoJsonPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
string updatedRepoJsonPath = Path.Combine(
Path.GetDirectoryName(Path.Combine(ScriptRepoUpdater.ReposPath, "bettergi-scripts-list-git"))!,
"repo_updated.json"
);
if (File.Exists(updatedRepoJsonPath))
{
@@ -264,7 +245,7 @@ public sealed class RepoWebBridge
return repoJson ?? throw new FileNotFoundException("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
}
internal static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
private static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
{
foreach (JObject item in array.OfType<JObject>())
{
@@ -282,7 +263,7 @@ public sealed class RepoWebBridge
}
}
internal static void ResetHasUpdateFlag(JObject node)
private static void ResetHasUpdateFlag(JObject node)
{
if (node["hasUpdate"] is { Type: JTokenType.Boolean } hasUpdate &&
(bool)hasUpdate)
@@ -28,9 +28,6 @@ public class Simulation
SendInput.Keyboard.KeyUp(key);
}
}
SendInput.Mouse.LeftButtonUp();
SendInput.Mouse.RightButtonUp();
SendInput.Mouse.MiddleButtonUp();
}
public static bool IsKeyDown(User32.VK key)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1018 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 284 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

@@ -1,83 +0,0 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model;
namespace BetterGenshinImpact.GameTask.AutoBoss.Assets;
public class AutoBossAssets : BaseAssets<AutoBossAssets>
{
public RecognitionObject OriginalResinTopIconRo;
public RecognitionObject RewardBoxRo;
public RecognitionObject OpenResinSupplementPaneButtonRo;
public RecognitionObject TransientResinInSupplementPaneRo;
public RecognitionObject FragileResinInSupplementPaneRo;
public RecognitionObject IncreaseResinUsageQuantityButtonRo;
#pragma warning disable CS8618
private AutoBossAssets() : base()
{
Initialization(systemInfo);
}
protected AutoBossAssets(ISystemInfo systemInfo) : base(systemInfo)
{
Initialization(systemInfo);
}
#pragma warning restore CS8618
private void Initialization(ISystemInfo systemInfo)
{
OriginalResinTopIconRo = new RecognitionObject
{
Name = "AutoBossOriginalResinTopIcon",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "original_resin_top_icon.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
RewardBoxRo = new RecognitionObject
{
Name = "AutoBossRewardBox",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "box.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
OpenResinSupplementPaneButtonRo = new RecognitionObject
{
Name = "AutoBossOpenResinSupplementPaneButton",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "open_resin_supplement_pane_button.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
TransientResinInSupplementPaneRo = new RecognitionObject
{
Name = "AutoBossTransientResinInSupplementPane",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "transient_resin_in_supplement_pane.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
FragileResinInSupplementPaneRo = new RecognitionObject
{
Name = "AutoBossFragileResinInSupplementPane",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "fragile_resin_in_supplement_pane.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
IncreaseResinUsageQuantityButtonRo = new RecognitionObject
{
Name = "AutoBossIncreaseResinUsageQuantityButton",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoBoss", "increase_resin_usage_quantity_button.png", systemInfo),
Threshold = 0.8,
DrawOnWindow = false
}.InitTemplate();
}
}
@@ -1,107 +0,0 @@
{
"info": {
"authors": [],
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1755828864835,
"map_name": "Teyvat",
"name": "未命名路径",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "walk",
"type": "teleport",
"x": 2289.0078125,
"y": -1197.31640625
},
{
"action": "combat_script",
"action_params": "wait(1.5)",
"id": 2,
"move_mode": "walk",
"type": "target",
"x": 2270.921875,
"y": -1181.94580078125
},
{
"action": "",
"action_params": "",
"id": 3,
"move_mode": "walk",
"type": "target",
"x": 2266.435546875,
"y": -1173.31787109375
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "walk",
"type": "path",
"x": 2238.7578125,
"y": -1184.73046875
},
{
"action": "",
"action_params": "",
"id": 5,
"move_mode": "fly",
"type": "path",
"x": 2215.11328125,
"y": -1197.294921875
},
{
"action": "",
"action_params": "",
"id": 6,
"move_mode": "walk",
"type": "path",
"x": 2191.3359375,
"y": -1214.46533203125
},
{
"action": "",
"action_params": "",
"id": 7,
"move_mode": "walk",
"type": "path",
"x": 2119.0048828125,
"y": -1231.728515625
},
{
"action": "",
"action_params": "",
"id": 8,
"move_mode": "walk",
"type": "path",
"x": 2117.5,
"y": -1254.09521484375
},
{
"action": "stop_flying",
"action_params": "",
"id": 9,
"move_mode": "fly",
"type": "path",
"x": 2114.4345703125,
"y": -1308.1357421875
},
{
"action": "",
"action_params": "",
"id": 10,
"move_mode": "run",
"type": "path",
"x": 2110.509765625,
"y": -1331.59130859375
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"name": "千年珍珠骏麟前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753791394637,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 4851.81982421875,
"y": 4802.15673828125,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 4837.4677734375,
"y": 4798.37158203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 4780.36767578125,
"y": 4788.42822265625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 4,
"x": 4766.72998046875,
"y": 4786.763671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,103 +0,0 @@
{
"info": {
"name": "半永恒统辖矩阵前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753788953823,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 5150.287109375,
"y": -2787.1591796875,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 5167.76123046875,
"y": -2787.11328125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 5192.0302734375,
"y": -2787.052734375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 5206.9306640625,
"y": -2786.9921875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 5215.41357421875,
"y": -2787.46875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 5234.9130859375,
"y": -2787.0947265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 5243.3876953125,
"y": -2793.0263671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 5254.2939453125,
"y": -2788.7001953125,
"type": "path",
"move_mode": "jump",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 5269.052734375,
"y": -2787.484375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"name": "前往古岩龙蜥",
"type": "collect",
"author": "柒叶子",
"version": "1.0",
"description": "前往古岩龙蜥",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch"
},
"positions": [
{
"id": 1,
"x": 1669.650390625,
"y": 341.86962890625,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 1674.890625,
"y": 345.15625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 1573.65234375,
"y": 254.67041015625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 1533.3095703125,
"y": 229.28857421875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 1485.296875,
"y": 208.9697265625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"authors": [
{
"links": "https://github.com/1004452714",
"name": "DarkFlameMaster"
}
],
"bgi_version": "0.52.0",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1775791356948,
"map_match_method": "SIFT",
"map_name": "Teyvat",
"name": "守望者・堕天",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "fly",
"type": "teleport",
"x": -227.951171875,
"y": 4109.8828125
},
{
"action": "",
"action_params": "",
"id": 2,
"move_mode": "fly",
"type": "path",
"x": -229.71484375,
"y": 4114.32080078125
},
{
"action": "stop_flying",
"action_params": "",
"id": 3,
"move_mode": "walk",
"type": "path",
"x": -250.228515625,
"y": 4167.486328125
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "run",
"type": "path",
"x": -261.037109375,
"y": 4195.42529296875
}
]
}
@@ -1,84 +0,0 @@
{
"info": {
"name": "实验性场力发生装置前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1753791496368,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 4144.181640625,
"y": 4423.85693359375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 4137.7529296875,
"y": 4420.017578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 4132.763671875,
"y": 4396.77880859375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 4159.6943359375,
"y": 4373.40283203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 4169.7021484375,
"y": 4349.689453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 4150.146484375,
"y": 4345.55419921875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 4131.76904296875,
"y": 4342.962890625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,76 +0,0 @@
{
"info": {
"name": "急冻树前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753707716845,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"action": "",
"move_mode": "walk",
"type": "teleport",
"x": -1638.53125,
"y": 2153.89794921875,
"action_params": ""
},
{
"id": 2,
"x": -1641.4697265625,
"y": 2151.00634765625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": -1649.2578125,
"y": 2128.595703125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": -1654.67578125,
"y": 2117.858154296875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": -1651.724609375,
"y": 2107.5087890625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 6,
"x": -1665.9697265625,
"y": 2100.76171875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,76 +0,0 @@
{
"info": {
"name": "恒常机关阵列前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753787243395,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": -4481.716796875,
"y": -2169.716796875,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": -4484.8984375,
"y": -2169.53125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": -4489.75,
"y": -2166.4501953125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": -4498.640625,
"y": -2160.86328125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": -4492.728515625,
"y": -2144.09765625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": -4471.73828125,
"y": -2128.3017578125,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"name": "掣电树前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753788008539,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 2080.2138671875,
"y": 107.275390625,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 2086.857421875,
"y": 95.4287109375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 2110.9052734375,
"y": 63.419921875,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 4,
"x": 2123.095703125,
"y": 49.15185546875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1 +0,0 @@
{"info":{"name":"","type":""},"positions":[{"x":-656.78515625,"y":-90.4169921875,"type":"teleport","move_mode":"walk"},{"x":-687.0263671875,"y":-96.19189453125,"type":"path","move_mode":"walk"},{"x":-719.9736328125,"y":-94.6748046875,"type":"path","move_mode":"walk"},{"x":-754.28125,"y":-91.27001953125,"type":"path","move_mode":"walk"},{"x":-781.6640625,"y":-96.474609375,"type":"path","move_mode":"walk"},{"x":-809.107421875,"y":-119.3671875,"type":"path","move_mode":"walk"},{"x":-833.240234375,"y":-132.7734375,"type":"path","move_mode":"walk"},{"x":-857.30859375,"y":-119.65185546875,"type":"path","move_mode":"walk"},{"x":-857.30078125,"y":-119.65380859375,"type":"path","move_mode":"walk"},{"x":-875.322265625,"y":-102.798828125,"type":"path","move_mode":"walk"},{"x":-889.1103515625,"y":-81.04638671875,"type":"path","move_mode":"walk"},{"x":-894.4716796875,"y":-54.01171875,"type":"path","move_mode":"walk"},{"x":-889.3955078125,"y":-26.36376953125,"type":"path","move_mode":"walk"},{"x":-896.947265625,"y":-4.6171875,"type":"path","move_mode":"walk"},{"x":-882.3173828125,"y":6.94140625,"type":"path","move_mode":"walk"},{"x":-864.560546875,"y":20.841796875,"type":"path","move_mode":"walk"},{"x":-855.5419921875,"y":44.05712890625,"type":"path","move_mode":"walk"}]}
@@ -1,121 +0,0 @@
{
"info": {
"name": "无相之水前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753787792567,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": -765.5771484375,
"y": -3557.05078125,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": -771.0966796875,
"y": -3562.517578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": -829.66015625,
"y": -3615.818359375,
"type": "path",
"move_mode": "fly",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": -865.271484375,
"y": -3620.0400390625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": "1500"
},
{
"id": 5,
"x": -868.1953125,
"y": -3604.36328125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": -872.5732421875,
"y": -3582.705078125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": -880.25390625,
"y": -3570.9833984375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": -892.919921875,
"y": -3565.12890625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": -916.8203125,
"y": -3558.5556640625,
"type": "path",
"move_mode": "fly",
"action": "",
"action_params": ""
},
{
"id": 10,
"x": -932.3837890625,
"y": -3555.0947265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 11,
"x": -960.7353515625,
"y": -3551.0908203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,75 +0,0 @@
{
"info": {
"name": "无相之火前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1753787370971,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": -3233.89453125,
"y": -3155.427734375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": -3224.46484375,
"y": -3113.1689453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": -3201.7431640625,
"y": -3095.697265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": -3183.052734375,
"y": -3082.67578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": -3180.9990234375,
"y": -3064.708984375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": -3179.1962890625,
"y": -3046.359375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,94 +0,0 @@
{
"info": {
"name": "无相之草前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753788793031,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 4036.58203125,
"y": -2464.6328125,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 4032.9716796875,
"y": -2476.08203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 4020.458984375,
"y": -2489.951171875,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": "1000"
},
{
"id": 4,
"x": 4004.5302734375,
"y": -2468.169921875,
"type": "path",
"move_mode": "walk",
"action": "up_down_grab_leaf",
"action_params": ""
},
{
"id": 5,
"x": 4003.3828125,
"y": -2441.16796875,
"type": "path",
"move_mode": "walk",
"action": "up_down_grab_leaf",
"action_params": ""
},
{
"id": 6,
"x": 3986.103515625,
"y": -2428.77734375,
"type": "path",
"move_mode": "walk",
"action": "up_down_grab_leaf",
"action_params": ""
},
{
"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": ""
}
]
}
@@ -1,84 +0,0 @@
{
"info": {
"name": "无相之雷前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1753708525378,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": -1867.1708984375,
"y": 1331.25390625,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": -1880.634765625,
"y": 1332.6240234375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": -1886.341796875,
"y": 1315.49609375,
"type": "path",
"move_mode": "jump",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": -1897.9521484375,
"y": 1312.71728515625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": -1906.6083984375,
"y": 1310.859375,
"type": "path",
"move_mode": "jump",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": -1925.8857421875,
"y": 1309.81689453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": -1939.40234375,
"y": 1308.43408203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,138 +0,0 @@
{
"info": {
"name": "歌裴莉娅的葬送前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1753791762596,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 3602.185546875,
"y": 3529.386474609375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 3617.0234375,
"y": 3515.871337890625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 3633.8837890625,
"y": 3500.517578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 3646.794921875,
"y": 3487.844482421875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 3661.6240234375,
"y": 3472.979248046875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 3685.3115234375,
"y": 3472.762939453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 3699.0478515625,
"y": 3486.41015625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 3712.1982421875,
"y": 3499.31689453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 3726.9365234375,
"y": 3513.27685546875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 10,
"x": 3742.3486328125,
"y": 3528.9443359375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 11,
"x": 3758.2509765625,
"y": 3545.006103515625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 12,
"x": 3773.4033203125,
"y": 3560.517822265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 13,
"x": 3787.8408203125,
"y": 3571.67578125,
"type": "target",
"move_mode": "walk",
"action": "combat_script",
"action_params": "keypress(F),wait(3),click,wait(2),keypress(F),wait(6)"
}
]
}
@@ -1,43 +0,0 @@
{
"info": {
"name": "冰封组曲快速前往",
"type": "collect",
"authors": [],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1755781802879,
"enable_monster_loot_split": false,
"map_match_method": ""
},
"positions": [
{
"id": 1,
"x": 3805.1650390625,
"y": 3592.691650390625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 3787.48046875,
"y": 3572.779541015625,
"type": "target",
"move_mode": "walk",
"action": "",
"action_params": ""
},{
"id": 13,
"x": 3787.8408203125,
"y": 3571.67578125,
"type": "target",
"move_mode": "walk",
"action": "combat_script",
"action_params": "keypress(F),wait(3),click,wait(2),keypress(F),wait(6)"
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"name": "水形幻人前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753791583765,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 5183.00537109375,
"y": 3375.525146484375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 5206.87890625,
"y": 3383.91845703125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 5221.623046875,
"y": 3389.093017578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 5239.80322265625,
"y": 3397.223388671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,148 +0,0 @@
{
"info": {
"name": "深罪浸礼者前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753789336063,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 6817.49609375,
"y": 383.68896484375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 6745.57421875,
"y": 370.45361328125,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": "1800"
},
{
"id": 3,
"x": 6761.9853515625,
"y": 375.31298828125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 6779.85546875,
"y": 380.6865234375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 6790.7373046875,
"y": 391.13427734375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 6798.34228515625,
"y": 398.11328125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 6816.609375,
"y": 405.6845703125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 6827.55029296875,
"y": 409.98974609375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 6836.47412109375,
"y": 424.748046875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 10,
"x": 6842.34814453125,
"y": 446.39990234375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 11,
"x": 6851.697265625,
"y": 462.83251953125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 12,
"x": 6854.1611328125,
"y": 476.1376953125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 13,
"x": 6858.7880859375,
"y": 507.1513671875,
"type": "path",
"move_mode": "fly",
"action": "",
"action_params": ""
},
{
"id": 14,
"x": 6850.39697265625,
"y": 542.9169921875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,49 +0,0 @@
{
"info": {
"name": "深邃摹结株前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753792527051,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 9345.50390625,
"y": -1340.40771484375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 9336.6083984375,
"y": -1310.02734375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 9328.75,
"y": -1281.68017578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,58 +0,0 @@
{
"info": {
"authors": [
{
"links": "https://github.com/1004452714",
"name": "DarkFlameMaster"
}
],
"bgi_version": "0.52.0",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1775700388310,
"map_match_method": "SIFT",
"map_name": "Teyvat",
"name": "深黯魇语之主前往",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "fly",
"type": "teleport",
"x": 10285.056640625,
"y": 6355.1962890625
},
{
"action": "",
"action_params": "",
"id": 2,
"move_mode": "fly",
"type": "path",
"x": 10293.6328125,
"y": 6361.96728515625
},
{
"action": "stop_flying",
"action_params": "",
"id": 3,
"move_mode": "fly",
"type": "path",
"x": 10335.369140625,
"y": 6393.92578125
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "run",
"type": "path",
"x": 10360.021484375,
"y": 6406.78564453125
}
]
}
@@ -1,67 +0,0 @@
{
"info": {
"name": "灵觉隐修的迷者前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753792615054,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 9595.2724609375,
"y": -1857.921875,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 9590.01171875,
"y": -1861.314453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 9574.6259765625,
"y": -1865.4580078125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 9559.29296875,
"y": -1883.2001953125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 9532.3603515625,
"y": -1903.8388671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,49 +0,0 @@
{
"info": {
"name": "熔岩辉龙像前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753792755970,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 9884.259765625,
"y": -2216.931640625,
"type": "teleport",
"move_mode": "walk",
"action": "force_tp",
"action_params": ""
},
{
"id": 2,
"x": 9894.6767578125,
"y": -2228.0947265625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 3,
"x": 9914.0439453125,
"y": -2248.6640625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,103 +0,0 @@
{
"info": {
"name": "爆炎树前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753711249019,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 837.4912109375,
"y": 235.0888671875,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 852.419921875,
"y": 228.279296875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 900.30859375,
"y": 228.51904296875,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 4,
"x": 914.7392578125,
"y": 238.0849609375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 933.87890625,
"y": 240.2333984375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 950.39453125,
"y": 228.48388671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 955.4921875,
"y": 212.90380859375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 955.54296875,
"y": 187.16552734375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 954.6064453125,
"y": 154.91064453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -1,138 +0,0 @@
{
"info": {
"name": "科培琉司的劫罚前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1753791900320,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 3602.185546875,
"y": 3529.386474609375,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 3617.0234375,
"y": 3515.871337890625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 3633.8837890625,
"y": 3500.517578125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 3646.794921875,
"y": 3487.844482421875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 3661.6240234375,
"y": 3472.979248046875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 3685.3115234375,
"y": 3472.762939453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 3699.0478515625,
"y": 3486.41015625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 3712.1982421875,
"y": 3499.31689453125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 3726.9365234375,
"y": 3513.27685546875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 10,
"x": 3742.3486328125,
"y": 3528.9443359375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 11,
"x": 3758.2509765625,
"y": 3545.006103515625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 12,
"x": 3773.4033203125,
"y": 3560.517822265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 13,
"x": 3787.8408203125,
"y": 3571.67578125,
"type": "target",
"move_mode": "walk",
"action": "combat_script",
"action_params": "keypress(F),wait(3),click,wait(2),keypress(S),wait(1),keypress(F),wait(6)"
}
]
}
@@ -1,44 +0,0 @@
{
"info": {
"name": "冰封组曲快速前往",
"type": "collect",
"authors": [],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.45.0",
"tags": [],
"last_modified_time": 1755781802879,
"enable_monster_loot_split": false,
"map_match_method": ""
},
"positions": [
{
"id": 1,
"x": 3805.1650390625,
"y": 3592.691650390625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 3787.48046875,
"y": 3572.779541015625,
"type": "target",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 13,
"x": 3787.8408203125,
"y": 3571.67578125,
"type": "target",
"move_mode": "walk",
"action": "combat_script",
"action_params": "keypress(F),wait(3),click,wait(2),keypress(S),wait(1),keypress(F),wait(6)"
}
]
}
Loaded 100 of 1014 files, more files were not shown because too many files have changed in this diff. Show more