Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74583166b6 | ||
|
|
3b7bf83b30 | ||
|
|
bee375484c | ||
|
|
bd8cb74cae |
No files matched your search
@@ -1,27 +0,0 @@
|
||||
main:
|
||||
# 自定义按钮可触发的事件
|
||||
web_trigger_one:
|
||||
- docker:
|
||||
image: python:3.11
|
||||
imports:
|
||||
- https://cnb.cool/bettergi/secret/-/blob/main/env.yml
|
||||
stages:
|
||||
- name: 下载构建物并上传
|
||||
script: |
|
||||
cd .github/workflows
|
||||
pip install -r requirements.txt
|
||||
python github_download_and_cnb_upload.py --cnb-token $CNB_TOKEN --github-token $GITHUB_TOKEN
|
||||
echo done!
|
||||
api_trigger_one:
|
||||
- docker:
|
||||
image: python:3.11
|
||||
imports:
|
||||
- https://cnb.cool/bettergi/secret/-/blob/main/env.yml
|
||||
stages:
|
||||
- name: API触发上传
|
||||
script: |
|
||||
echo run id: $RUN_ID
|
||||
cd .github/workflows
|
||||
pip install -r requirements.txt
|
||||
python github_download_and_cnb_upload.py --cnb-token $CNB_TOKEN --github-token $GITHUB_TOKEN --run-id $RUN_ID
|
||||
echo api done!
|
||||
@@ -1,5 +0,0 @@
|
||||
branch:
|
||||
- buttons:
|
||||
- name: 触发上传
|
||||
description: 上传测试版或者正式版
|
||||
event: web_trigger_one
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: Bug report / 错误报告
|
||||
about: Create a report to help us improve / 创建报告以帮助我们改进
|
||||
title: "[bug]请补充标题内容"
|
||||
title: "[bug] "
|
||||
labels: bug
|
||||
---
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
---
|
||||
name: I have feature requesting / 我有新功能请求
|
||||
about: Your request may come as a surprise. / 你的请求也许成为惊喜
|
||||
title: "[feature] "
|
||||
labels: feature 功能请求
|
||||
---
|
||||
|
||||
- Your feature requesting / 你的新功能请求
|
||||
|
||||
@@ -1,452 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
CNB Release Uploader
|
||||
|
||||
依赖:
|
||||
- requests
|
||||
- tqdm
|
||||
|
||||
安装依赖:
|
||||
pip install requests tqdm
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
import time
|
||||
import sys
|
||||
import argparse
|
||||
from typing import List, Dict, Optional
|
||||
from pathlib import Path
|
||||
from tqdm import tqdm
|
||||
|
||||
|
||||
class CNBReleaseUploader:
|
||||
def __init__(self, token: str, base_url: str = "https://api.cnb.cool"):
|
||||
"""
|
||||
初始化CNB Release上传器
|
||||
|
||||
Args:
|
||||
token: 认证token
|
||||
base_url: API基础URL
|
||||
"""
|
||||
self.token = token
|
||||
self.base_url = base_url
|
||||
self.headers = {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json',
|
||||
'User-Agent': 'CNB-Release-Uploader/1.0.0',
|
||||
'Host': 'api.cnb.cool',
|
||||
'Connection': 'keep-alive'
|
||||
}
|
||||
|
||||
def create_release(self, project_path: str, release_data: Dict) -> Optional[Dict]:
|
||||
"""
|
||||
创建一个新的release
|
||||
|
||||
Args:
|
||||
project_path: 项目路径 (例如: "bettergi/better-genshin-impact")
|
||||
release_data: release数据
|
||||
|
||||
Returns:
|
||||
创建的release信息或None
|
||||
"""
|
||||
url = f"{self.base_url}/{project_path}/-/releases"
|
||||
|
||||
# 打印请求信息
|
||||
print("\n📋 请求头 (Headers):")
|
||||
for key, value in self.headers.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
try:
|
||||
response = requests.post(url, headers=self.headers, json=release_data)
|
||||
response.raise_for_status()
|
||||
|
||||
release_info = response.json()
|
||||
print(f"✅ Release创建成功: {release_info.get('name', 'N/A')}")
|
||||
print(f" Release ID: {release_info.get('id', 'N/A')}")
|
||||
print(f" Tag Name: {release_info.get('tag_name', 'N/A')}")
|
||||
print(f" Created At: {release_info.get('created_at', 'N/A')}")
|
||||
print(f" Is Latest: {release_info.get('is_latest', False)}")
|
||||
return release_info
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 创建release失败: {e}")
|
||||
if hasattr(e, 'response') and e.response is not None:
|
||||
print(f" 状态码: {e.response.status_code}")
|
||||
print(f" 响应内容: {e.response.text}")
|
||||
return None
|
||||
|
||||
def get_asset_upload_url(self, project_path: str, release_id: str, asset_name: str,
|
||||
file_size: int, overwrite: bool = True) -> Optional[Dict]:
|
||||
"""
|
||||
获取asset上传URL
|
||||
|
||||
Args:
|
||||
project_path: 项目路径
|
||||
release_id: release ID
|
||||
asset_name: asset名称
|
||||
file_size: 文件大小
|
||||
overwrite: 是否覆盖现有文件
|
||||
|
||||
Returns:
|
||||
包含upload_url等信息的字典或None
|
||||
"""
|
||||
url = f"{self.base_url}/{project_path}/-/releases/{release_id}/asset-upload-url"
|
||||
|
||||
data = {
|
||||
"asset_name": asset_name,
|
||||
"overwrite": overwrite,
|
||||
"size": file_size
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
|
||||
upload_info = response.json()
|
||||
print(f"✅ 获取上传URL成功")
|
||||
return upload_info
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 获取上传URL失败 ({asset_name}): {e}")
|
||||
if hasattr(e, 'response') and e.response is not None:
|
||||
print(f" 状态码: {e.response.status_code}")
|
||||
print(f" 响应内容: {e.response.text}")
|
||||
return None
|
||||
|
||||
def upload_asset(self, upload_url: str, file_path: str, show_progress: bool = True) -> bool:
|
||||
"""
|
||||
上传asset文件
|
||||
|
||||
Args:
|
||||
upload_url: 上传URL
|
||||
file_path: 本地文件路径
|
||||
show_progress: 是否显示上传进度条
|
||||
|
||||
Returns:
|
||||
是否上传成功
|
||||
"""
|
||||
if not os.path.exists(file_path):
|
||||
print(f"❌ 文件不存在: {file_path}")
|
||||
return False
|
||||
|
||||
upload_headers = {
|
||||
'Accept': 'application/json',
|
||||
'Authorization': f'Bearer {self.token}',
|
||||
}
|
||||
|
||||
file_size = os.path.getsize(file_path)
|
||||
file_name = os.path.basename(file_path)
|
||||
|
||||
try:
|
||||
with open(file_path, 'rb') as file:
|
||||
if show_progress and file_size > 0:
|
||||
# 创建进度条
|
||||
progress_bar = tqdm(
|
||||
total=file_size,
|
||||
unit='B',
|
||||
unit_scale=True,
|
||||
unit_divisor=1024,
|
||||
desc=f"📤 上传 {file_name}",
|
||||
ncols=80,
|
||||
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]'
|
||||
)
|
||||
|
||||
# 创建一个包装器来更新进度条
|
||||
class ProgressFileWrapper:
|
||||
def __init__(self, file_obj, progress_bar):
|
||||
self.file_obj = file_obj
|
||||
self.progress_bar = progress_bar
|
||||
|
||||
def read(self, size=-1):
|
||||
data = self.file_obj.read(size)
|
||||
if data:
|
||||
self.progress_bar.update(len(data))
|
||||
return data
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.file_obj, name)
|
||||
|
||||
wrapped_file = ProgressFileWrapper(file, progress_bar)
|
||||
response = requests.put(upload_url, headers=upload_headers, data=wrapped_file)
|
||||
progress_bar.close()
|
||||
else:
|
||||
response = requests.put(upload_url, headers=upload_headers, data=file)
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
print(f"📤 上传到 {upload_url} 返回结果: {response.status_code}")
|
||||
|
||||
try:
|
||||
response_data = response.json()
|
||||
print(f" 响应内容 (JSON): {json.dumps(response_data, indent=2, ensure_ascii=False)}")
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
print(f" 响应内容 (文本): {response.text}")
|
||||
|
||||
return True
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 文件上传失败 ({os.path.basename(file_path)}): {e}")
|
||||
if hasattr(e, 'response') and e.response is not None:
|
||||
print(f" 响应状态码: {e.response.status_code}")
|
||||
print(f" 响应内容: {e.response.text}")
|
||||
return False
|
||||
|
||||
def verify_upload(self, verify_url: str) -> bool:
|
||||
"""
|
||||
验证上传是否成功
|
||||
|
||||
Args:
|
||||
verify_url: 验证URL
|
||||
|
||||
Returns:
|
||||
是否验证成功
|
||||
"""
|
||||
try:
|
||||
response = requests.post(verify_url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
|
||||
print(f"🔍 验证请求返回状态: {response.status_code}")
|
||||
|
||||
try:
|
||||
response_data = response.json()
|
||||
print(f" 响应内容 (JSON): {json.dumps(response_data, indent=2, ensure_ascii=False)}")
|
||||
except (json.JSONDecodeError, ValueError):
|
||||
print(f" 响应内容 (文本): {response.text}")
|
||||
|
||||
return True
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 验证上传失败: {e}")
|
||||
if hasattr(e, 'response') and e.response is not None:
|
||||
print(f" 验证状态码: {e.response.status_code}")
|
||||
print(f" 验证响应内容: {e.response.text}")
|
||||
return False
|
||||
|
||||
def upload_multiple_assets(self, project_path: str, release_id: str,
|
||||
asset_files: List[str], overwrite: bool = True, show_progress: bool = True) -> List[bool]:
|
||||
"""
|
||||
上传多个assets
|
||||
|
||||
Args:
|
||||
project_path: 项目路径
|
||||
release_id: release ID
|
||||
asset_files: asset文件路径列表
|
||||
overwrite: 是否覆盖现有文件
|
||||
show_progress: 是否显示进度条
|
||||
|
||||
Returns:
|
||||
每个文件的上传结果列表
|
||||
"""
|
||||
results = []
|
||||
|
||||
print(f"\n📦 开始上传 {len(asset_files)} 个文件到release {release_id}...")
|
||||
|
||||
# 计算总文件大小用于整体进度显示
|
||||
total_size = 0
|
||||
valid_files = []
|
||||
for file_path in asset_files:
|
||||
if os.path.exists(file_path):
|
||||
total_size += os.path.getsize(file_path)
|
||||
valid_files.append(file_path)
|
||||
|
||||
if show_progress and valid_files:
|
||||
print(f"📊 总计 {len(valid_files)} 个有效文件,总大小: {total_size / 1024 / 1024:.2f} MB")
|
||||
print("" + "=" * 60)
|
||||
|
||||
for i, file_path in enumerate(asset_files, 1):
|
||||
if not os.path.exists(file_path):
|
||||
print(f"❌ [{i}/{len(asset_files)}] 跳过不存在的文件: {file_path}")
|
||||
results.append(False)
|
||||
continue
|
||||
|
||||
file_size = os.path.getsize(file_path)
|
||||
asset_name = os.path.basename(file_path)
|
||||
|
||||
print(f"\n📁 [{i}/{len(asset_files)}] 处理文件: {asset_name}")
|
||||
print(f" 文件大小: {file_size:,} bytes ({file_size / 1024 / 1024:.2f} MB)")
|
||||
|
||||
# 1. 获取上传URL
|
||||
upload_info = self.get_asset_upload_url(
|
||||
project_path, release_id, asset_name, file_size, overwrite
|
||||
)
|
||||
|
||||
if not upload_info:
|
||||
results.append(False)
|
||||
continue
|
||||
|
||||
# 2. 上传文件
|
||||
upload_success = self.upload_asset(upload_info['upload_url'], file_path, show_progress)
|
||||
time.sleep(1)
|
||||
|
||||
# 3. 验证上传(如果有验证URL)
|
||||
final_success = upload_success
|
||||
if upload_success and 'verify_url' in upload_info:
|
||||
verify_success = self.verify_upload(upload_info['verify_url'])
|
||||
final_success = verify_success
|
||||
if verify_success:
|
||||
print(f"✅ 文件 {asset_name} 上传并验证成功")
|
||||
else:
|
||||
print(f"❌ 文件 {asset_name} 上传成功但验证失败")
|
||||
elif upload_success:
|
||||
print(f"✅ 文件 {asset_name} 上传成功(无需验证)")
|
||||
|
||||
results.append(final_success)
|
||||
|
||||
# 避免请求过快
|
||||
if i < len(asset_files):
|
||||
time.sleep(1)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def load_config_from_json(json_input: str) -> Dict:
|
||||
"""
|
||||
从JSON字符串或文件路径加载配置
|
||||
|
||||
Args:
|
||||
json_input: JSON字符串或JSON文件路径
|
||||
|
||||
Returns:
|
||||
配置字典
|
||||
"""
|
||||
try:
|
||||
# 首先尝试作为JSON字符串解析
|
||||
config = json.loads(json_input)
|
||||
print("✅ 从JSON字符串加载配置成功")
|
||||
return config
|
||||
except json.JSONDecodeError:
|
||||
# 如果失败,尝试作为文件路径
|
||||
try:
|
||||
if os.path.exists(json_input):
|
||||
with open(json_input, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
print(f"✅ 从文件 {json_input} 加载配置成功")
|
||||
return config
|
||||
else:
|
||||
raise FileNotFoundError(f"配置文件不存在: {json_input}")
|
||||
except Exception as e:
|
||||
raise ValueError(f"无法解析JSON配置: {e}")
|
||||
|
||||
|
||||
def validate_config(config: Dict) -> None:
|
||||
"""
|
||||
验证配置的必需字段
|
||||
|
||||
Args:
|
||||
config: 配置字典
|
||||
|
||||
Raises:
|
||||
ValueError: 如果配置无效
|
||||
"""
|
||||
required_fields = ['token', 'project_path', 'release_data']
|
||||
for field in required_fields:
|
||||
if field not in config:
|
||||
raise ValueError(f"缺少必需字段: {field}")
|
||||
|
||||
# 验证release_data必需字段
|
||||
release_required = ['tag_name', 'name']
|
||||
for field in release_required:
|
||||
if field not in config['release_data']:
|
||||
raise ValueError(f"release_data缺少必需字段: {field}")
|
||||
|
||||
# 验证asset_files
|
||||
if 'asset_files' in config and not isinstance(config['asset_files'], list):
|
||||
raise ValueError("asset_files必须是数组")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='CNB Release Uploader - JSON配置版本')
|
||||
parser.add_argument('config', help='JSON配置字符串或JSON配置文件路径')
|
||||
parser.add_argument('--dry-run', action='store_true', help='只验证配置,不执行上传')
|
||||
parser.add_argument('--no-progress', action='store_true', help='禁用上传进度条显示')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
# 加载配置
|
||||
print("🔧 加载配置...")
|
||||
config = load_config_from_json(args.config)
|
||||
|
||||
# 验证配置
|
||||
print("🔍 验证配置...")
|
||||
validate_config(config)
|
||||
|
||||
# 打印配置信息
|
||||
print("\n📋 配置信息:")
|
||||
print(f" Token: {'*' * 20}")
|
||||
print(f" 项目路径: {config['project_path']}")
|
||||
print(f" Release名称: {config['release_data']['name']}")
|
||||
print(f" Tag名称: {config['release_data']['tag_name']}")
|
||||
print(f" Asset文件数量: {len(config.get('asset_files', []))}")
|
||||
|
||||
if args.dry_run:
|
||||
print("\n🧪 Dry-run模式,配置验证通过,退出程序")
|
||||
return 0
|
||||
|
||||
# 创建上传器实例
|
||||
uploader = CNBReleaseUploader(
|
||||
token=config['token'],
|
||||
base_url=config.get('base_url', 'https://api.cnb.cool')
|
||||
)
|
||||
|
||||
# 1. 创建release
|
||||
print("\n🚀 开始创建release...")
|
||||
release_info = uploader.create_release(config['project_path'], config['release_data'])
|
||||
|
||||
if not release_info:
|
||||
print("❌ 创建release失败,退出程序")
|
||||
return 1
|
||||
|
||||
release_id = release_info.get('id')
|
||||
if not release_id:
|
||||
print("❌ 无法获取release ID,退出程序")
|
||||
return 1
|
||||
|
||||
# 2. 上传assets(如果有)
|
||||
asset_files = config.get('asset_files', [])
|
||||
if asset_files:
|
||||
overwrite = config.get('overwrite', True)
|
||||
show_progress = not args.no_progress # 默认显示进度条,除非指定 --no-progress
|
||||
results = uploader.upload_multiple_assets(
|
||||
config['project_path'], release_id, asset_files, overwrite, show_progress
|
||||
)
|
||||
|
||||
# 3. 显示结果
|
||||
print("\n" + "=" * 50)
|
||||
print("📊 上传结果汇总:")
|
||||
print("=" * 50)
|
||||
|
||||
success_count = sum(results)
|
||||
total_count = len(results)
|
||||
|
||||
for i, (file_path, success) in enumerate(zip(asset_files, results)):
|
||||
status = "✅ 成功" if success else "❌ 失败"
|
||||
print(f" [{i + 1}] {status} - {os.path.basename(file_path)}")
|
||||
|
||||
print(f"\n🎉 完成! 成功上传 {success_count}/{total_count} 个文件")
|
||||
|
||||
if success_count == total_count:
|
||||
print("🎊 所有文件都上传成功!")
|
||||
return 0
|
||||
elif success_count > 0:
|
||||
print("⚠️ 部分文件上传成功,请检查失败的文件")
|
||||
return 2
|
||||
else:
|
||||
print("💥 所有文件上传失败,请检查配置和网络")
|
||||
return 1
|
||||
else:
|
||||
print("\n📦 没有指定asset文件,只创建了release")
|
||||
return 0
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 程序执行失败: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = main()
|
||||
sys.exit(exit_code)
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Better Genshin Impact Build Trigger Script
|
||||
用于触发CNB构建的Python脚本
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
import sys
|
||||
import argparse
|
||||
|
||||
def trigger_build(token, branch="main", event="api_trigger_one", runid=None):
|
||||
"""
|
||||
触发构建请求
|
||||
|
||||
Args:
|
||||
token (str): 授权token
|
||||
branch (str): 分支名称,默认为main
|
||||
event (str): 事件类型,默认为api_trigger_one
|
||||
runid (str): 运行ID,可选参数
|
||||
|
||||
Returns:
|
||||
dict: API响应结果
|
||||
"""
|
||||
url = "https://api.cnb.cool/bettergi/better-genshin-impact/-/build/start"
|
||||
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
"Authorization": f"Bearer {token}",
|
||||
"Content-Type": "application/json",
|
||||
"Host": "api.cnb.cool",
|
||||
"Connection": "keep-alive"
|
||||
}
|
||||
|
||||
data = {
|
||||
"branch": branch,
|
||||
"event": event
|
||||
}
|
||||
|
||||
# 如果提供了runid,则添加到env中
|
||||
if runid:
|
||||
data["env"] = {
|
||||
"RUN_ID": runid
|
||||
}
|
||||
|
||||
try:
|
||||
print(f"正在发起构建请求...")
|
||||
print(f"URL: {url}")
|
||||
|
||||
print(f"请求体: {json.dumps(data, indent=2, ensure_ascii=False)}")
|
||||
|
||||
response = requests.post(url, headers=headers, json=data)
|
||||
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
print("构建触发成功!")
|
||||
print(f"响应内容: {json.dumps(result, indent=2, ensure_ascii=False)}")
|
||||
return result
|
||||
else:
|
||||
print(f"请求失败: {response.status_code}")
|
||||
print(f"错误信息: {response.text}")
|
||||
return None
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"请求异常: {e}")
|
||||
return None
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"JSON解析错误: {e}")
|
||||
print(f"响应内容: {response.text}")
|
||||
return None
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="触发Better Genshin Impact构建")
|
||||
parser.add_argument("token", help="授权token")
|
||||
parser.add_argument("--branch", default="main", help="分支名称 (默认: main)")
|
||||
parser.add_argument("--event", default="api_trigger_one", help="事件类型 (默认: api_trigger_one)")
|
||||
parser.add_argument("--runid", help="运行ID (可选)")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.token:
|
||||
print("错误: 必须提供token参数")
|
||||
sys.exit(1)
|
||||
|
||||
result = trigger_build(args.token, args.branch, args.event, args.runid)
|
||||
|
||||
if result is None:
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,507 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
GitHub Actions 构建物下载和上传脚本
|
||||
|
||||
该脚本用于:
|
||||
1. 从 GitHub Actions 下载最新的构建物 (BetterGI_7z 和 BetterGI_Install)
|
||||
2. 解压构建物到本地
|
||||
3. 调用 cnb_release.py 上传文件到 CNB
|
||||
|
||||
使用方法:
|
||||
python github_download_and_cnb_upload.py --cnb-token YOUR_CNB_TOKEN [--github-token YOUR_GITHUB_TOKEN] [--run-id RUN_ID]
|
||||
|
||||
参数说明:
|
||||
--cnb-token: CNB API Token (必需)
|
||||
--github-token: GitHub Personal Access Token (可选,用于提高API限制)
|
||||
--run-id: 指定 GitHub Actions 运行 ID (可选,默认获取最新运行)
|
||||
|
||||
依赖:
|
||||
- requests: HTTP 请求库
|
||||
- tqdm: 进度条显示库
|
||||
|
||||
安装依赖:pip install -r requirements.txt
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import requests
|
||||
import zipfile
|
||||
import tempfile
|
||||
import shutil
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import List, Dict, Optional
|
||||
from tqdm import tqdm
|
||||
|
||||
# 导入 CNBReleaseUploader
|
||||
from cnb_release import CNBReleaseUploader
|
||||
|
||||
|
||||
class GitHubActionsDownloader:
|
||||
def __init__(self, token: Optional[str] = None):
|
||||
"""
|
||||
初始化 GitHub Actions 下载器
|
||||
|
||||
Args:
|
||||
token: GitHub Personal Access Token (可选,用于提高API限制)
|
||||
"""
|
||||
self.token = token
|
||||
self.headers = {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
'User-Agent': 'BetterGI-Downloader/1.0.0'
|
||||
}
|
||||
if token:
|
||||
self.headers['Authorization'] = f'token {token}'
|
||||
|
||||
def get_latest_workflow_run(self, owner: str, repo: str, workflow_file: str) -> Optional[Dict]:
|
||||
"""
|
||||
获取最新的工作流运行
|
||||
|
||||
Args:
|
||||
owner: 仓库所有者
|
||||
repo: 仓库名称
|
||||
workflow_file: 工作流文件名
|
||||
|
||||
Returns:
|
||||
最新的工作流运行信息或None
|
||||
"""
|
||||
url = f'https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_file}/runs'
|
||||
params = {
|
||||
'status': 'completed',
|
||||
'conclusion': 'success',
|
||||
'per_page': 1
|
||||
}
|
||||
|
||||
try:
|
||||
response = requests.get(url, headers=self.headers, params=params)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
runs = data.get('workflow_runs', [])
|
||||
|
||||
if not runs:
|
||||
print("❌ 没有找到成功完成的工作流运行")
|
||||
return None
|
||||
|
||||
latest_run = runs[0]
|
||||
print(f"✅ 找到最新的工作流运行:")
|
||||
print(f" Run ID: {latest_run['id']}")
|
||||
print(f" 创建时间: {latest_run['created_at']}")
|
||||
print(f" 状态: {latest_run['status']} / {latest_run['conclusion']}")
|
||||
print(f" 分支: {latest_run['head_branch']}")
|
||||
|
||||
return latest_run
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 获取工作流运行失败: {e}")
|
||||
return None
|
||||
|
||||
def get_artifacts(self, owner: str, repo: str, run_id: int) -> List[Dict]:
|
||||
"""
|
||||
获取指定运行的构建物列表
|
||||
|
||||
Args:
|
||||
owner: 仓库所有者
|
||||
repo: 仓库名称
|
||||
run_id: 运行ID
|
||||
|
||||
Returns:
|
||||
构建物列表
|
||||
"""
|
||||
url = f'https://api.github.com/repos/{owner}/{repo}/actions/runs/{run_id}/artifacts'
|
||||
|
||||
try:
|
||||
response = requests.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
|
||||
data = response.json()
|
||||
artifacts = data.get('artifacts', [])
|
||||
|
||||
print(f"📦 找到 {len(artifacts)} 个构建物:")
|
||||
for artifact in artifacts:
|
||||
print(f" - {artifact['name']} ({artifact['size_in_bytes']:,} bytes)")
|
||||
|
||||
return artifacts
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 获取构建物列表失败: {e}")
|
||||
return []
|
||||
|
||||
def download_artifact(self, owner: str, repo: str, artifact_id: int,
|
||||
artifact_name: str, download_dir: str) -> Optional[str]:
|
||||
"""
|
||||
下载指定的构建物
|
||||
|
||||
Args:
|
||||
owner: 仓库所有者
|
||||
repo: 仓库名称
|
||||
artifact_id: 构建物ID
|
||||
artifact_name: 构建物名称
|
||||
download_dir: 下载目录
|
||||
|
||||
Returns:
|
||||
下载的文件路径或None
|
||||
"""
|
||||
url = f'https://api.github.com/repos/{owner}/{repo}/actions/artifacts/{artifact_id}/zip'
|
||||
|
||||
try:
|
||||
print(f"📥 开始下载构建物: {artifact_name}")
|
||||
response = requests.get(url, headers=self.headers, stream=True)
|
||||
response.raise_for_status()
|
||||
|
||||
# 获取文件总大小
|
||||
total_size = int(response.headers.get('content-length', 0))
|
||||
|
||||
# 保存到临时文件
|
||||
zip_path = os.path.join(download_dir, f"{artifact_name}.zip")
|
||||
|
||||
# 使用 tqdm 创建进度条
|
||||
chunk_size = 8192
|
||||
with open(zip_path, 'wb') as f:
|
||||
with tqdm(
|
||||
total=total_size,
|
||||
unit='B',
|
||||
unit_scale=True,
|
||||
unit_divisor=1024,
|
||||
desc=f"下载 {artifact_name}",
|
||||
ncols=80,
|
||||
bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]'
|
||||
) as pbar:
|
||||
for chunk in response.iter_content(chunk_size=chunk_size):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
|
||||
print(f"✅ 下载完成: {zip_path}")
|
||||
return zip_path
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"❌ 下载构建物失败 ({artifact_name}): {e}")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def extract_artifact(self, zip_path: str, extract_dir: str) -> List[str]:
|
||||
"""
|
||||
解压构建物
|
||||
|
||||
Args:
|
||||
zip_path: ZIP文件路径
|
||||
extract_dir: 解压目录
|
||||
|
||||
Returns:
|
||||
解压出的文件列表
|
||||
"""
|
||||
extracted_files = []
|
||||
|
||||
try:
|
||||
print(f"📂 解压构建物: {os.path.basename(zip_path)}")
|
||||
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||
zip_ref.extractall(extract_dir)
|
||||
extracted_files = [os.path.join(extract_dir, name) for name in zip_ref.namelist()]
|
||||
|
||||
print(f"✅ 解压完成,共 {len(extracted_files)} 个文件")
|
||||
for file_path in extracted_files:
|
||||
if os.path.isfile(file_path):
|
||||
size = os.path.getsize(file_path)
|
||||
print(f" - {os.path.basename(file_path)} ({size:,} bytes)")
|
||||
|
||||
return extracted_files
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 解压失败: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def extract_version_from_filename(filename: str) -> Optional[str]:
|
||||
"""
|
||||
从文件名中提取版本号
|
||||
|
||||
Args:
|
||||
filename: 文件名
|
||||
|
||||
Returns:
|
||||
版本号或None
|
||||
"""
|
||||
# 去除扩展名
|
||||
import os
|
||||
filename_without_ext = os.path.splitext(filename)[0]
|
||||
|
||||
# 匹配版本号模式,如 v1.2.3, 1.2.3-alpha.1 等
|
||||
patterns = [
|
||||
r'v?([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)',
|
||||
r'_v?([0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?)',
|
||||
]
|
||||
|
||||
for pattern in patterns:
|
||||
match = re.search(pattern, filename_without_ext)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def create_cnb_config(files: List[str], version: str, token: str) -> Dict:
|
||||
"""
|
||||
创建CNB上传配置
|
||||
|
||||
Args:
|
||||
files: 要上传的文件列表
|
||||
version: 版本号
|
||||
token: CNB token
|
||||
|
||||
Returns:
|
||||
CNB配置字典
|
||||
"""
|
||||
# 判断是否为预发布版本
|
||||
is_prerelease = '-' in version
|
||||
make_latest = "false" if is_prerelease else "true"
|
||||
|
||||
config = {
|
||||
"token": token,
|
||||
"project_path": "bettergi/better-genshin-impact",
|
||||
"base_url": "https://api.cnb.cool",
|
||||
"overwrite": True,
|
||||
"release_data": {
|
||||
"tag_name": f"v{version}",
|
||||
"name": f"BetterGI v{version}",
|
||||
"body": f"BetterGI v{version} 自动发布",
|
||||
"draft": False,
|
||||
"prerelease": is_prerelease,
|
||||
"target_commitish": "main",
|
||||
"make_latest": make_latest
|
||||
},
|
||||
"asset_files": files
|
||||
}
|
||||
|
||||
return config
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
# 解析命令行参数
|
||||
parser = argparse.ArgumentParser(description='BetterGI 构建物下载和上传工具')
|
||||
parser.add_argument('--run-id', type=str, help='指定 GitHub Actions 运行 ID,如果提供则不会获取最新运行')
|
||||
parser.add_argument('--github-token', type=str, help='GitHub Personal Access Token')
|
||||
parser.add_argument('--cnb-token', type=str, required=True, help='CNB API Token (必需)')
|
||||
args = parser.parse_args()
|
||||
|
||||
print("🚀 BetterGI 构建物下载和上传工具")
|
||||
print("=" * 50)
|
||||
|
||||
# 获取 token,优先使用命令行参数,其次使用环境变量
|
||||
github_token = args.github_token or os.getenv('GITHUB_TOKEN')
|
||||
cnb_token = args.cnb_token or os.getenv('CNB_TOKEN')
|
||||
|
||||
if not cnb_token:
|
||||
print("❌ 错误: 请设置 CNB_TOKEN 环境变量")
|
||||
return 1
|
||||
|
||||
if not github_token:
|
||||
print("⚠️ 警告: 未设置 GITHUB_TOKEN,可能会遇到API限制")
|
||||
|
||||
# 确定运行 ID
|
||||
if args.run_id:
|
||||
print(f"\n🎯 使用指定的运行 ID: {args.run_id}")
|
||||
run_id = args.run_id
|
||||
else:
|
||||
# 创建下载器来获取最新运行 ID
|
||||
downloader = GitHubActionsDownloader(github_token)
|
||||
print("\n🔍 查找最新的工作流运行...")
|
||||
latest_run = downloader.get_latest_workflow_run('babalae', 'better-genshin-impact', 'publish.yml')
|
||||
if not latest_run:
|
||||
return 1
|
||||
run_id = str(latest_run['id'])
|
||||
|
||||
# 使用当前目录下的固定目录,以action运行ID命名
|
||||
work_dir = os.path.join(os.getcwd(), 'github_actions_cache', run_id)
|
||||
download_dir = os.path.join(work_dir, 'downloads')
|
||||
extract_dir = os.path.join(work_dir, 'extracted')
|
||||
|
||||
print(f"\n📁 使用工作目录: {work_dir}")
|
||||
|
||||
# 检查是否已存在解压后的文件
|
||||
all_files = []
|
||||
version = None
|
||||
|
||||
# 检查解压目录是否已存在且包含文件
|
||||
if os.path.exists(extract_dir):
|
||||
print("🔍 检查已存在的构建物...")
|
||||
existing_files = []
|
||||
# 预期的构建物名称
|
||||
expected_artifacts = ['BetterGI_7z', 'BetterGI_Install']
|
||||
|
||||
for artifact_name in expected_artifacts:
|
||||
artifact_extract_dir = os.path.join(extract_dir, artifact_name)
|
||||
if os.path.exists(artifact_extract_dir):
|
||||
for root, dirs, files in os.walk(artifact_extract_dir):
|
||||
for file in files:
|
||||
file_path = os.path.join(root, file)
|
||||
existing_files.append(file_path)
|
||||
|
||||
# 尝试从文件名提取版本号
|
||||
if not version:
|
||||
filename = os.path.basename(file_path)
|
||||
extracted_version = extract_version_from_filename(filename)
|
||||
if extracted_version:
|
||||
version = extracted_version
|
||||
|
||||
if existing_files and version:
|
||||
print(f"✅ 发现已存在的构建物 ({len(existing_files)} 个文件),跳过下载")
|
||||
print(f"📋 检测到版本号: {version}")
|
||||
all_files = existing_files
|
||||
else:
|
||||
print("⚠️ 已存在目录但未找到有效文件,将重新下载")
|
||||
|
||||
# 如果没有找到已存在的文件,则进行下载和解压
|
||||
if not all_files:
|
||||
print("📥 需要下载构建物,正在获取构建物信息...")
|
||||
|
||||
# 如果还没有创建下载器,现在创建
|
||||
if 'downloader' not in locals():
|
||||
downloader = GitHubActionsDownloader(github_token)
|
||||
|
||||
# 获取构建物列表
|
||||
print("\n📦 获取构建物列表...")
|
||||
artifacts = downloader.get_artifacts('babalae', 'better-genshin-impact', int(run_id))
|
||||
if not artifacts:
|
||||
return 1
|
||||
|
||||
# 筛选需要的构建物
|
||||
target_artifacts = []
|
||||
for artifact in artifacts:
|
||||
if artifact['name'] in ['BetterGI_7z', 'BetterGI_Install']:
|
||||
target_artifacts.append(artifact)
|
||||
|
||||
if len(target_artifacts) != 2:
|
||||
print(f"❌ 错误: 期望找到2个构建物,实际找到 {len(target_artifacts)} 个")
|
||||
return 1
|
||||
|
||||
print("📥 开始下载和解压构建物...")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
os.makedirs(extract_dir, exist_ok=True)
|
||||
|
||||
for artifact in target_artifacts:
|
||||
# 下载
|
||||
zip_path = downloader.download_artifact(
|
||||
'babalae', 'better-genshin-impact',
|
||||
artifact['id'], artifact['name'], download_dir
|
||||
)
|
||||
|
||||
if not zip_path:
|
||||
continue
|
||||
|
||||
# 解压
|
||||
artifact_extract_dir = os.path.join(extract_dir, artifact['name'])
|
||||
os.makedirs(artifact_extract_dir, exist_ok=True)
|
||||
|
||||
extracted_files = downloader.extract_artifact(zip_path, artifact_extract_dir)
|
||||
|
||||
# 收集文件并提取版本号
|
||||
for file_path in extracted_files:
|
||||
if os.path.isfile(file_path):
|
||||
all_files.append(file_path)
|
||||
|
||||
# 尝试从文件名提取版本号
|
||||
if not version:
|
||||
filename = os.path.basename(file_path)
|
||||
extracted_version = extract_version_from_filename(filename)
|
||||
if extracted_version:
|
||||
version = extracted_version
|
||||
print(f"📋 检测到版本号: {version}")
|
||||
|
||||
if not all_files:
|
||||
print("❌ 错误: 没有找到可上传的文件")
|
||||
return 1
|
||||
|
||||
if not version:
|
||||
print("❌ 错误: 无法从文件名中提取版本号")
|
||||
return 1
|
||||
|
||||
print(f"\n📋 准备上传 {len(all_files)} 个文件:")
|
||||
for file_path in all_files:
|
||||
size = os.path.getsize(file_path)
|
||||
print(f" - {os.path.basename(file_path)} ({size:,} bytes)")
|
||||
|
||||
# 创建CNB配置
|
||||
print("\n⚙️ 创建CNB配置...")
|
||||
cnb_config = create_cnb_config(all_files, version, cnb_token)
|
||||
|
||||
# 保存配置文件
|
||||
config_path = os.path.join(work_dir, 'cnb_config.json')
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(cnb_config, f, indent=2, ensure_ascii=False)
|
||||
|
||||
print(f"✅ 配置文件已保存: {config_path}")
|
||||
|
||||
# 直接调用 CNBReleaseUploader
|
||||
print("\n🚀 开始上传到CNB...")
|
||||
|
||||
try:
|
||||
# 创建 CNBReleaseUploader 实例
|
||||
uploader = CNBReleaseUploader(
|
||||
token=cnb_config['token'],
|
||||
base_url=cnb_config.get('base_url', 'https://api.cnb.cool')
|
||||
)
|
||||
|
||||
# 创建 release
|
||||
print(f"📝 创建 release: {cnb_config['release_data']['name']}")
|
||||
release_result = uploader.create_release(
|
||||
project_path=cnb_config['project_path'],
|
||||
release_data=cnb_config['release_data']
|
||||
)
|
||||
|
||||
if not release_result:
|
||||
print("❌ 创建 release 失败")
|
||||
return 1
|
||||
|
||||
print(f"✅ Release 创建成功: {release_result['name']}")
|
||||
|
||||
# 上传文件
|
||||
print(f"📤 开始上传 {len(cnb_config['asset_files'])} 个文件...")
|
||||
upload_results = uploader.upload_multiple_assets(
|
||||
project_path=cnb_config['project_path'],
|
||||
release_id=release_result['id'],
|
||||
asset_files=cnb_config['asset_files'],
|
||||
overwrite=cnb_config.get('overwrite', True)
|
||||
)
|
||||
|
||||
# 检查上传结果
|
||||
success_count = sum(1 for result in upload_results if result)
|
||||
total_count = len(upload_results)
|
||||
|
||||
print(f"\n📊 上传结果汇总:")
|
||||
print(f" ✅ 成功: {success_count}/{total_count}")
|
||||
|
||||
if success_count < total_count:
|
||||
print(f" ❌ 失败: {total_count - success_count}/{total_count}")
|
||||
for i, result in enumerate(upload_results):
|
||||
if not result:
|
||||
file_name = os.path.basename(cnb_config['asset_files'][i])
|
||||
print(f" - {file_name}: 上传失败")
|
||||
|
||||
if success_count == total_count:
|
||||
print("\n🎉 所有文件上传完成!")
|
||||
return 0
|
||||
else:
|
||||
print("\n❌ 部分文件上传失败")
|
||||
return 1
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ CNB上传失败: {e}")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
exit_code = main()
|
||||
sys.exit(exit_code)
|
||||
except KeyboardInterrupt:
|
||||
print("\n⚠️ 用户中断操作")
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"\n💥 程序异常: {e}")
|
||||
sys.exit(1)
|
||||
@@ -1,19 +0,0 @@
|
||||
name: mirrorchyan_release_note
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [edited, released]
|
||||
|
||||
jobs:
|
||||
mirrorchyan_release_note:
|
||||
runs-on: macos-latest
|
||||
|
||||
steps:
|
||||
- id: uploading
|
||||
uses: MirrorChyan/release-note-action@v1
|
||||
with:
|
||||
mirrorchyan_rid: BGI
|
||||
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,88 +0,0 @@
|
||||
name: mirrorchyan_uploading
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [released]
|
||||
|
||||
jobs:
|
||||
mirrorchyan:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: 📥 Download release
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
latest: true
|
||||
fileName: "*"
|
||||
|
||||
- name: 📥 Download kachina-builder release
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "YuehaiTeam/kachina-installer"
|
||||
latest: true
|
||||
fileName: "kachina-builder.exe"
|
||||
|
||||
- name: Embed Dotnet and VCRedist
|
||||
shell: bash
|
||||
run: |
|
||||
# dotnet
|
||||
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
|
||||
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Cannot get the latest version from $VERSION_URL"
|
||||
exit 1
|
||||
fi
|
||||
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
|
||||
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
|
||||
# vcredist
|
||||
echo "Downloading VCRedist"
|
||||
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
|
||||
# embed
|
||||
echo "Embedding runtimes"
|
||||
./kachina-builder.exe append -o ./BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
./kachina-builder.exe extract -i ./BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
|
||||
|
||||
- name: Extract 7z and create zip
|
||||
shell: bash
|
||||
run: |
|
||||
7z a -tzip BetterGI.Install.zip ./BetterGI.Install.*.exe -mx=1 -r -y
|
||||
choco install wget --no-progress
|
||||
7z x BetterGI_v*.7z -oun7z
|
||||
mv ./metadata.json ./un7z/BetterGI/.metadata.json
|
||||
cd un7z
|
||||
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
|
||||
|
||||
- name: Determine version number
|
||||
id: get-version
|
||||
shell: bash
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "release" ]; then
|
||||
echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
|
||||
else
|
||||
LATEST_TAG=$(curl -s -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
|
||||
https://api.github.com/repos/${{ github.repository }}/releases/latest \
|
||||
| jq -r '.tag_name')
|
||||
echo "version=$LATEST_TAG" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload Zip
|
||||
uses: MirrorChyan/uploading-action@v1
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "BetterGI.zip"
|
||||
version_name: ${{ steps.get-version.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
os: win
|
||||
arch: x64
|
||||
- name: Upload Exe
|
||||
uses: MirrorChyan/uploading-action@v1
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "BetterGI.Install.zip"
|
||||
version_name: ${{ steps.get-version.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
|
||||
@@ -1,596 +0,0 @@
|
||||
name: BetterGI Publish
|
||||
run-name: "BetterGI ${{ inputs.version }}"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'BetterGI Version (eg: 0.35.1, 0.36.5-alpha.1)'
|
||||
required: true
|
||||
type: string
|
||||
kachina-channel:
|
||||
type: choice
|
||||
description: 'Kachina Installer Channel'
|
||||
required: true
|
||||
default: 'release'
|
||||
options:
|
||||
- release
|
||||
- dev
|
||||
create-release:
|
||||
type: boolean
|
||||
description: '创建 GitHub Release 草稿'
|
||||
required: true
|
||||
default: false
|
||||
upload-to-steambird:
|
||||
type: boolean
|
||||
description: '上传到 Steambird'
|
||||
required: true
|
||||
default: false
|
||||
|
||||
jobs:
|
||||
# Add validation job to check version format
|
||||
validate:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.set-version.outputs.version }}
|
||||
steps:
|
||||
- name: Set version from input or tag
|
||||
id: set-version
|
||||
run: |
|
||||
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
# Validate manual input version format
|
||||
if ! [[ "${{ github.event.inputs.version }}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$ ]]; then
|
||||
echo "❌ 错误:版本格式必须符合语义化版本规范 (例如: 1.2.3, 1.2.3-alpha, 1.2.3+build.123)"
|
||||
exit 1
|
||||
fi
|
||||
echo "version=${{ github.event.inputs.version }}" >> $GITHUB_OUTPUT
|
||||
echo "✨ 手动触发构建,版本号:${{ github.event.inputs.version }}"
|
||||
else
|
||||
# Extract version from tag name (remove 'v' prefix)
|
||||
VERSION=${GITHUB_REF#refs/tags/v}
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "🏷️ 从 tag 触发构建,版本号:${VERSION}"
|
||||
fi
|
||||
|
||||
build_web_map_editor:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: huiyadanli/bettergi-map
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'npm'
|
||||
- run: npm install
|
||||
- run: npm run build:single
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: web_map_editor
|
||||
path: dist/
|
||||
|
||||
build_web_scripts_list:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: A-Little-AnQi/bettergi-script-web
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: 'npm'
|
||||
- run: npm install
|
||||
- run: npm run build:single
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: web_scripts_list
|
||||
path: dist/
|
||||
|
||||
build_dist:
|
||||
runs-on: windows-latest
|
||||
needs: [validate, build_web_map_editor, build_web_scripts_list]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: 8.x
|
||||
- name: 更新 csproj 文件版本号
|
||||
run: |
|
||||
$version = '${{ needs.validate.outputs.version }}'
|
||||
(Get-Content BetterGenshinImpact/BetterGenshinImpact.csproj) -replace '<Version>.*</Version>', "<Version>$version</Version>" | Set-Content BetterGenshinImpact/BetterGenshinImpact.csproj
|
||||
- name: 自动提交更改
|
||||
if: github.repository_owner == 'babalae'
|
||||
uses: stefanzweifel/git-auto-commit-action@v5
|
||||
with:
|
||||
commit_message: "Update version to ${{ needs.validate.outputs.version }}"
|
||||
branch: main
|
||||
file_pattern: BetterGenshinImpact/BetterGenshinImpact.csproj
|
||||
- name: Cache NuGet packages
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.nuget/packages
|
||||
key: ${{ runner.os }}-nuget-${{ hashFiles('**/BetterGenshinImpact.csproj') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nuget-
|
||||
- name: 🛠️ Build application
|
||||
run: dotnet publish BetterGenshinImpact/BetterGenshinImpact.csproj -c Release -p:PublishProfile=FolderProfile -p:Version=${{ needs.validate.outputs.version }}
|
||||
continue-on-error: true
|
||||
- name: 🧹 Clear & Move Files
|
||||
run: |
|
||||
$sourceDir = ".\BetterGenshinImpact\bin\x64\Release\net8.0-windows10.0.22621.0\publish\win-x64"
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.lib" | Remove-Item -Force
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*ffmpeg*.dll" | Remove-Item -Force
|
||||
Get-ChildItem -Path $sourceDir -Recurse -Filter "*.pdb" | Remove-Item -Force
|
||||
New-Item -Path "dist/BetterGI" -ItemType Directory
|
||||
xcopy "$sourceDir\*" ".\dist\BetterGI\" /E /H /I /Y
|
||||
# 下载前面构建好的web内容
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: web_map_editor
|
||||
path: dist/BetterGI/Assets/Map/Editor
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: web_scripts_list
|
||||
path: dist/BetterGI/Assets/Web/ScriptRepo
|
||||
# 下载构建 repo 的内容补充数据
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: babalae/bettergi-publish
|
||||
path: publish
|
||||
# - name: 🗜️ Extract Map
|
||||
# run: |
|
||||
# cd publish
|
||||
# # Extract zst files
|
||||
# Get-ChildItem -Filter *.zst | ForEach-Object {
|
||||
# if ($_.PSIsContainer -eq $false) {
|
||||
# $file = $_.Name
|
||||
# $output_file = "..\dist\BetterGI\Assets\Map\$($file -replace '.zst$', '')"
|
||||
# & zstd -d $file -o $output_file
|
||||
# Write-Host "$file -> $output_file"
|
||||
# }
|
||||
# }
|
||||
# # Extract zip files
|
||||
# Get-ChildItem -Filter *.zip | ForEach-Object {
|
||||
# if ($_.PSIsContainer -eq $false) {
|
||||
# $file = $_.FullName
|
||||
# $destination = "..\dist\BetterGI\Assets\Map"
|
||||
# Expand-Archive -Path $file -DestinationPath $destination -Force
|
||||
# Write-Host "$file -> $destination"
|
||||
# }
|
||||
# }
|
||||
# 生成更新器
|
||||
- name: 📥 Download kachina-builder release
|
||||
if: ${{ github.event.inputs.kachina-channel == 'release' }}
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "YuehaiTeam/kachina-installer"
|
||||
latest: true
|
||||
fileName: "kachina-builder.exe"
|
||||
|
||||
- name: 📥 Download kachina-builder dev
|
||||
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
|
||||
uses: dawidd6/action-download-artifact@v8
|
||||
with:
|
||||
github_token: ${{secrets.GITHUB_TOKEN}}
|
||||
repo: "YuehaiTeam/kachina-installer"
|
||||
workflow: "build.yml"
|
||||
name: artifact
|
||||
branch: main
|
||||
event: push
|
||||
workflow_conclusion: success
|
||||
- name: 📦 Gen Updater by kachina-builder
|
||||
run: |
|
||||
cd dist
|
||||
..\kachina-builder.exe pack -c ..\Build\kachina.config.json -o BetterGI/BetterGI.update.exe
|
||||
# 打包上传
|
||||
- name: 📦 Generate archive
|
||||
run: |
|
||||
cd dist
|
||||
7z a "BetterGI_v${{ needs.validate.outputs.version }}.7z" BetterGI -t7z -mx=5 -mf=BCJ2 -r -y
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BetterGI_7z
|
||||
path: dist/BetterGI_*.7z
|
||||
|
||||
build_installer:
|
||||
runs-on: windows-latest
|
||||
needs: [validate, build_dist]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: BetterGI_7z
|
||||
path: dist
|
||||
- name: Unpack BetterGI_*.7z
|
||||
run: |
|
||||
cd dist
|
||||
7z x "BetterGI_v${{ needs.validate.outputs.version }}.7z"
|
||||
- name: 📥 Download kachina-builder release
|
||||
if: ${{ github.event.inputs.kachina-channel == 'release' }}
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "YuehaiTeam/kachina-installer"
|
||||
latest: true
|
||||
fileName: "kachina-builder.exe"
|
||||
- name: 📥 Download kachina-builder dev
|
||||
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
|
||||
uses: dawidd6/action-download-artifact@v8
|
||||
with:
|
||||
github_token: ${{secrets.GITHUB_TOKEN}}
|
||||
repo: "YuehaiTeam/kachina-installer"
|
||||
workflow: "build.yml"
|
||||
name: artifact
|
||||
branch: main
|
||||
event: push
|
||||
workflow_conclusion: success
|
||||
- name: 📥 Download last release
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "babalae/better-genshin-impact"
|
||||
latest: true
|
||||
fileName: "BetterGI_v*.7z"
|
||||
out-file-path: 'last'
|
||||
- name: 📥 Get 2nd and 3rd release
|
||||
id: release_tags
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
$releasesUrl = "https://api.github.com/repos/babalae/better-genshin-impact/releases"
|
||||
$headers = @{
|
||||
"Authorization" = "Bearer $env:GITHUB_TOKEN"
|
||||
"Accept" = "application/vnd.github.v3+json"
|
||||
}
|
||||
$releases = Invoke-RestMethod -Uri $releasesUrl -Headers $headers -Method Get
|
||||
$validReleases = $releases |
|
||||
Where-Object { -not $_.draft -and -not $_.prerelease } |
|
||||
Sort-Object { [DateTime]$_.published_at } -Descending
|
||||
if ($validReleases.Count -lt 3) {
|
||||
Write-Error "至少需要 3 个正式 Release(当前找到 $($validReleases.Count) 个)"
|
||||
exit 1
|
||||
}
|
||||
"second_release_tag=$($validReleases[1].tag_name)" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
|
||||
"third_release_tag=$($validReleases[2].tag_name)" | Out-File -FilePath $env:GITHUB_OUTPUT -Append
|
||||
|
||||
- name: 📥 Download 2nd last release
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "babalae/better-genshin-impact"
|
||||
tag: ${{ steps.release_tags.outputs.second_release_tag }}
|
||||
fileName: "BetterGI_v*.7z"
|
||||
out-file-path: '2nd'
|
||||
- name: 📥 Download 3rd last release
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "babalae/better-genshin-impact"
|
||||
tag: ${{ steps.release_tags.outputs.third_release_tag }}
|
||||
fileName: "BetterGI_v*.7z"
|
||||
out-file-path: '3rd'
|
||||
- name: Unpack releases
|
||||
run: |
|
||||
cd last
|
||||
7z x "BetterGI*.7z" -otemp
|
||||
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
|
||||
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
|
||||
} else {
|
||||
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
|
||||
}
|
||||
cd ..
|
||||
cd 2nd
|
||||
7z x "BetterGI*.7z" -otemp
|
||||
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
|
||||
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
|
||||
} else {
|
||||
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
|
||||
}
|
||||
cd ..
|
||||
cd 3rd
|
||||
7z x "BetterGI*.7z" -otemp
|
||||
if (Test-Path -Path ".\temp\BetterGI" -PathType Container) {
|
||||
Move-Item -Path ".\temp\BetterGI" -Destination ".\BetterGI"
|
||||
} else {
|
||||
Rename-Item -Path ".\temp" -NewName ".\BetterGI"
|
||||
}
|
||||
cd ..
|
||||
ls .\last
|
||||
ls .\2nd
|
||||
ls .\3rd
|
||||
- name: 📦 Pack kachina-builder
|
||||
run: |
|
||||
cd dist
|
||||
..\kachina-builder.exe gen -j 6 -i BetterGI -m metadata.json -o hashed -r babalae/bettergi -t ${{ needs.validate.outputs.version }} --diff-vers ..\last\BetterGI --diff-vers ..\2nd\BetterGI --diff-vers ..\3rd\BetterGI --diff-ignore *[.txt,.onnx] -u .\BetterGI\BetterGI.update.exe
|
||||
..\kachina-builder.exe pack -c ../Build/kachina.config.json -m metadata.json -d hashed -o BetterGI.Install.${{ needs.validate.outputs.version }}.exe
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BetterGI_Install
|
||||
path: dist/BetterGI.Install.*.exe
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BetterGI_OnlineInst
|
||||
path: dist/BetterGI/BetterGI.update.exe
|
||||
|
||||
build_setup:
|
||||
runs-on: windows-latest
|
||||
needs: [validate, build_dist]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: BetterGI_7z
|
||||
path: dist
|
||||
- name: Unpack BetterGI_*.7z & Repack
|
||||
run: |
|
||||
cd dist
|
||||
7z x "BetterGI_v${{ needs.validate.outputs.version }}.7z"
|
||||
cd BetterGI
|
||||
7z a -t7z "..\..\publish.7z" *
|
||||
- name: 📥 Download MicaSetup
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "lemutec/MicaSetup"
|
||||
latest: true
|
||||
fileName: "MicaSetup_v*.7z"
|
||||
- name: 📦 Pack MicaSetup
|
||||
run: |
|
||||
$archiveFiles = Get-ChildItem -Path . -Filter "MicaSetup_v*.7z"
|
||||
foreach ($archive in $archiveFiles) {
|
||||
& 7z x $archive.FullName
|
||||
}
|
||||
Copy-Item -Path "Build\micasetup.json" -Destination "."
|
||||
Copy-Item -Path "Build\micasetup" -Destination "." -Recurse -Force
|
||||
.\makemica.exe micasetup.json
|
||||
ren BetterGI_Setup.exe BetterGI_Setup_v${{ needs.validate.outputs.version }}.exe
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BetterGI_Setup
|
||||
path: BetterGI_Setup*.exe
|
||||
|
||||
# 创建 GitHub Release
|
||||
create_release:
|
||||
if: github.event.inputs.create-release == 'true'
|
||||
needs: [validate, build_dist, build_installer]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: ${{ needs.validate.outputs.version }}
|
||||
name: BetterGI v${{ needs.validate.outputs.version }}
|
||||
draft: true
|
||||
prerelease: ${{ contains(needs.validate.outputs.version, '-') }}
|
||||
fail_on_unmatched_files: true
|
||||
files: |
|
||||
artifacts/BetterGI_7z/*.7z
|
||||
artifacts/BetterGI_Install/*.exe
|
||||
|
||||
mirrorchyan_uploading:
|
||||
if: github.repository_owner == 'babalae' && contains(needs.validate.outputs.version, '-')
|
||||
needs: [validate, build_dist, build_installer]
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: downloads
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: 📥 Download kachina-builder release
|
||||
if: ${{ github.event.inputs.kachina-channel == 'release' }}
|
||||
uses: robinraju/[email protected]
|
||||
with:
|
||||
repository: "YuehaiTeam/kachina-installer"
|
||||
latest: true
|
||||
fileName: "kachina-builder.exe"
|
||||
- name: 📥 Download kachina-builder dev
|
||||
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
|
||||
uses: dawidd6/action-download-artifact@v8
|
||||
with:
|
||||
github_token: ${{secrets.GITHUB_TOKEN}}
|
||||
repo: "YuehaiTeam/kachina-installer"
|
||||
workflow: "build.yml"
|
||||
name: artifact
|
||||
branch: main
|
||||
event: push
|
||||
workflow_conclusion: success
|
||||
|
||||
- name: Embed Dotnet and VCRedist
|
||||
shell: bash
|
||||
run: |
|
||||
# dotnet
|
||||
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
|
||||
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Cannot get the latest version from $VERSION_URL"
|
||||
exit 1
|
||||
fi
|
||||
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
|
||||
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
|
||||
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
|
||||
# vcredist
|
||||
echo "Downloading VCRedist"
|
||||
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
|
||||
# embed
|
||||
echo "Embedding runtimes"
|
||||
./kachina-builder.exe append -o ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
|
||||
./kachina-builder.exe extract -i ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
|
||||
- name: Extract 7z and create zip
|
||||
shell: bash
|
||||
run: |
|
||||
choco install wget --no-progress
|
||||
7z a -tzip BetterGI.Install.${{ needs.validate.outputs.version }}.zip ./downloads/BetterGI_Install/BetterGI.Install.${{ needs.validate.outputs.version }}.exe -mx=1 -r -y
|
||||
cd downloads/BetterGI_7z
|
||||
7z x BetterGI_v*.7z -oun7z
|
||||
mv ../../metadata.json ./un7z/BetterGI/.metadata.json
|
||||
cd un7z
|
||||
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
|
||||
|
||||
- name: Upload Zip
|
||||
uses: MirrorChyan/uploading-action@v1
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "downloads/BetterGI_7z/BetterGI.zip"
|
||||
version_name: ${{ needs.validate.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
os: win
|
||||
arch: x64
|
||||
|
||||
- name: Upload Install.exe
|
||||
uses: MirrorChyan/uploading-action@v1
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "BetterGI.Install.${{ needs.validate.outputs.version }}.zip"
|
||||
version_name: ${{ needs.validate.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
|
||||
cnb_uploading:
|
||||
if: github.repository_owner == 'babalae' && false
|
||||
needs: [validate, build_dist, build_installer]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.x'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r .github/workflows/requirements.txt
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Prepare files for upload
|
||||
run: |
|
||||
mkdir -p upload_files
|
||||
# 只复制 7z 文件和 Install.exe 文件
|
||||
find artifacts -name "*.7z" -exec cp {} upload_files/ \;
|
||||
find artifacts -name "BetterGI.Install.*.exe" -exec cp {} upload_files/ \;
|
||||
echo "📦 准备上传的文件:"
|
||||
ls -la upload_files/
|
||||
|
||||
- name: Copy CNB uploader script
|
||||
run: |
|
||||
# 复制 CNB 上传脚本到当前目录
|
||||
cp .github/workflows/cnb_release.py ./cnb_release.py
|
||||
|
||||
- name: Upload to CNB
|
||||
env:
|
||||
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
run: |
|
||||
# 生成文件列表数组
|
||||
FILE_LIST=""
|
||||
for file in upload_files/*; do
|
||||
if [ -f "$file" ]; then
|
||||
if [ -n "$FILE_LIST" ]; then
|
||||
FILE_LIST="$FILE_LIST,"
|
||||
fi
|
||||
FILE_LIST="$FILE_LIST\"$file\""
|
||||
fi
|
||||
done
|
||||
|
||||
# 判断是否为预发布版本
|
||||
if [[ "$VERSION" == *"-"* ]]; then
|
||||
IS_PRERELEASE="true"
|
||||
MAKE_LATEST="false"
|
||||
else
|
||||
IS_PRERELEASE="false"
|
||||
MAKE_LATEST="true"
|
||||
fi
|
||||
|
||||
# 创建 JSON 配置
|
||||
cat > cnb_config.json << EOF
|
||||
{
|
||||
"token": "$CNB_TOKEN",
|
||||
"project_path": "bettergi/better-genshin-impact",
|
||||
"base_url": "https://api.cnb.cool",
|
||||
"overwrite": true,
|
||||
"release_data": {
|
||||
"tag_name": "v$VERSION",
|
||||
"name": "BetterGI v$VERSION",
|
||||
"body": "BetterGI v$VERSION 自动发布",
|
||||
"draft": false,
|
||||
"prerelease": $IS_PRERELEASE,
|
||||
"target_commitish": "main",
|
||||
"make_latest": "$MAKE_LATEST"
|
||||
},
|
||||
"asset_files": [
|
||||
$FILE_LIST
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
# 检查配置文件内容
|
||||
echo "📋 CNB 配置内容:"
|
||||
cat cnb_config.json
|
||||
|
||||
# 验证 JSON 格式
|
||||
python -c "import json; print('✅ JSON 格式验证通过'); json.load(open('cnb_config.json'))"
|
||||
|
||||
# 执行上传
|
||||
python cnb_release.py cnb_config.json
|
||||
|
||||
cnb_trigger:
|
||||
if: github.repository_owner == 'babalae'
|
||||
needs: [validate, build_dist, build_installer]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.x'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install -r .github/workflows/requirements.txt
|
||||
|
||||
- name: Trigger CNB Build
|
||||
env:
|
||||
CNB_TOKEN: ${{ secrets.CNB_TOKEN }}
|
||||
run: |
|
||||
python .github/workflows/cnb_trigger.py "$CNB_TOKEN" --runid ${{ github.run_id }}
|
||||
|
||||
upload_to_steambird:
|
||||
if: ${{ inputs.upload-to-steambird && github.repository_owner == 'babalae' }}
|
||||
needs: [validate, build_dist, build_installer]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
path: artifacts
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Prepare files for upload
|
||||
run: |
|
||||
mkdir -p upload_files
|
||||
# 只复制 7z 文件和 Install.exe 文件
|
||||
find artifacts -name "*.7z" -exec cp {} upload_files/ \;
|
||||
find artifacts -name "BetterGI.Install.*.exe" -exec cp {} upload_files/ \;
|
||||
echo "📦 准备上传的文件:"
|
||||
ls -la upload_files/
|
||||
|
||||
- name: Upload to Steambird
|
||||
env:
|
||||
TUS_USER: "bgi"
|
||||
TUS_PASS: ${{ secrets.TUS_PASS }}
|
||||
run: |
|
||||
wget https://uploads.steambird.pub/upload.sh
|
||||
chmod +x upload.sh
|
||||
./upload.sh https://uploads.steambird.pub/dav/bgi/ upload_files/BetterGI.Install.*.exe
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
# CNB Release Uploader 依赖
|
||||
requests>=2.25.0
|
||||
tqdm>=4.60.0
|
||||
@@ -24,14 +24,8 @@ bld/
|
||||
Tmp/
|
||||
/packages/
|
||||
node_modules/
|
||||
github_actions_cache/
|
||||
|
||||
*.zip
|
||||
|
||||
# Rider
|
||||
.idea
|
||||
.trae
|
||||
.claude
|
||||
CLAUDE.md
|
||||
|
||||
__pycache__/
|
||||
@@ -1,3 +0,0 @@
|
||||
[submodule "Test/BetterGenshinImpact.UnitTest/Assets"]
|
||||
path = Test/BetterGenshinImpact.UnitTest/Assets
|
||||
url = https://github.com/huiyadanli/BetterGI.UnitTest.Assets.git
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+2
-3
@@ -2,11 +2,10 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net7.0-windows10.0.22621.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseWPF>true</UseWPF>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -14,7 +13,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\BetterGenshinImpact\BetterGenshinImpact.csproj" />
|
||||
<ProjectReference Include="..\BetterGenshinImpact\BetterGenshinImpact.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
+15
-32
@@ -7,33 +7,24 @@ namespace BetterGenshinImpact.Test.Dataset;
|
||||
public class AvatarClassifyGen
|
||||
{
|
||||
// 基础图像文件夹
|
||||
private const string BaseDir = @"E:\HuiTask\更好的原神\侧面头像\side_src";
|
||||
|
||||
// 产出文件夹
|
||||
private const string OutputDir = @"E:\HuiTask\更好的原神\侧面头像\dateset";
|
||||
private const string BaseDir = @"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\分类器\";
|
||||
|
||||
// 背景图像文件夹
|
||||
private static readonly string BackgroundDir = @"E:\HuiTask\更好的原神\侧面头像\background";
|
||||
private static readonly string BackgroundDir = Path.Combine(BaseDir, "background");
|
||||
|
||||
private static readonly Random Rd = new Random();
|
||||
|
||||
// public static readonly List<string> ImgNames = ["UI_AvatarIcon_Side_Aino.png","UI_AvatarIcon_Side_Flins.png", "UI_AvatarIcon_Side_Nefer.png", "UI_AvatarIcon_Side_Nefer.png", "UI_AvatarIcon_Side_Lauma.png"];
|
||||
|
||||
public static void GenAll()
|
||||
{
|
||||
// 读取基础图像
|
||||
List<string> sideImageFiles = Directory.GetFiles(BaseDir, "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// 只用一个图像
|
||||
// List<string> sideImageFiles = [];
|
||||
//
|
||||
// foreach (string imgName in ImgNames)
|
||||
// {
|
||||
// sideImageFiles.Add(Path.Combine(BaseDir, imgName));
|
||||
// }
|
||||
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Arlecchino.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
|
||||
// 生成训练集
|
||||
GenTo(sideImageFiles, Path.Combine(OutputDir, @"dateset\train"), 200);
|
||||
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
|
||||
// 生成测试集
|
||||
GenTo(sideImageFiles, Path.Combine(OutputDir, @"dateset\test"), 40);
|
||||
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\test"), 40);
|
||||
// GenTo(new List<string> { sideImageFiles[1] }, Path.Combine(BaseDir, @"dateset\test"), 1);
|
||||
}
|
||||
|
||||
@@ -71,14 +62,11 @@ public class AvatarClassifyGen
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
// 随机挑选一张背景图像
|
||||
string backgroundImageFile = Path.Combine(BackgroundDir,
|
||||
Directory.GetFiles(BackgroundDir, "*.png")[
|
||||
Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
|
||||
string backgroundImageFile = Path.Combine(BackgroundDir, Directory.GetFiles(BackgroundDir, "*.png")[Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
|
||||
|
||||
// 从背景图像中随机取一块 128x128 的区域
|
||||
Mat backgroundImage = Cv2.ImRead(backgroundImageFile, ImreadModes.Color);
|
||||
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128),
|
||||
new Random().Next(backgroundImage.Height - 128), 128, 128);
|
||||
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128), new Random().Next(backgroundImage.Height - 128), 128, 128);
|
||||
Mat backgroundImageRegion = backgroundImage[backgroundRect];
|
||||
|
||||
// 随机平移、缩放保留区域
|
||||
@@ -95,11 +83,9 @@ public class AvatarClassifyGen
|
||||
// Cv2.ImShow("resizedSideImage", resizedSideImage);
|
||||
var resizedMaskImage = new Mat();
|
||||
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
|
||||
Cv2.Resize(~alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0,
|
||||
InterpolationFlags.Cubic);
|
||||
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
var resizedAlphaChannel = new Mat();
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0,
|
||||
InterpolationFlags.Cubic);
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
|
||||
// Cv2.ImShow("resizedMaskImage", resizedMaskImage);
|
||||
// generatedImage[transformedRect] = resizedSideImage;
|
||||
@@ -116,8 +102,7 @@ public class AvatarClassifyGen
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}大于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX,
|
||||
(resizedSideImage.Height - 128) + offsetY, 128, 128);
|
||||
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX, (resizedSideImage.Height - 128) + offsetY, 128, 128);
|
||||
// result = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone, backgroundImageRegionClone, result, resizedMaskImage[roi]);
|
||||
result = Mul(backgroundImageRegionClone, resizedAlphaChannel[roi]);
|
||||
@@ -131,8 +116,7 @@ public class AvatarClassifyGen
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}小于等于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX,
|
||||
(128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
|
||||
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX, (128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
|
||||
var res = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone[roi], backgroundImageRegionClone[roi], res, resizedMaskImage);
|
||||
res = Mul(backgroundImageRegionClone[roi], resizedAlphaChannel);
|
||||
@@ -152,12 +136,11 @@ public class AvatarClassifyGen
|
||||
var channels = background.Split();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Cv2.Multiply(channels[i], ~ alphaChannel, channels[i], 1 / 255.0);
|
||||
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
|
||||
}
|
||||
|
||||
Mat result = new Mat();
|
||||
Cv2.Merge(channels[..3], result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-35
@@ -4,7 +4,7 @@
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
Title="Test"
|
||||
Width="240"
|
||||
Width="120"
|
||||
Height="450"
|
||||
mc:Ignorable="d">
|
||||
<Canvas>
|
||||
@@ -31,7 +31,7 @@
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="DoMatchTest"
|
||||
Content="生成特征点" />
|
||||
Content="特征匹配测试" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="130"
|
||||
Width="100"
|
||||
@@ -43,48 +43,18 @@
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="MapDrawTeleportPoint"
|
||||
Content="画传送点" />
|
||||
Content="超大地图标点" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="190"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="GenAvatarData"
|
||||
Content="侧面头像数据集" />
|
||||
<Button Canvas.Left="120"
|
||||
Canvas.Top="190"
|
||||
Width="100"
|
||||
Height="23"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Click="GenAvatarDataT"
|
||||
Content="透明头像数据集" />
|
||||
Content="生成侧面头像数据集" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="220"
|
||||
Canvas.Top="190"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="AutoCookTestCase"
|
||||
Content="自动烹饪图像测试" />
|
||||
<Button Canvas.Left="10"
|
||||
Canvas.Top="250"
|
||||
Width="100"
|
||||
Height="23"
|
||||
Click="MapPathView"
|
||||
Content="路线地图查看" />
|
||||
<Button Canvas.Left="120"
|
||||
Canvas.Top="10"
|
||||
Width="100"
|
||||
Height="23"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Click="ZoomOut"
|
||||
Content="缩小地图到256" />
|
||||
<Button Canvas.Left="120"
|
||||
Canvas.Top="40"
|
||||
Width="100"
|
||||
Height="23"
|
||||
HorizontalAlignment="Left"
|
||||
VerticalAlignment="Center"
|
||||
Click="CameraTest"
|
||||
Content="新视角识别测试" />
|
||||
</Canvas>
|
||||
</Window>
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Windows;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
using BetterGenshinImpact.Test.Dataset;
|
||||
using BetterGenshinImpact.Test.Simple;
|
||||
using BetterGenshinImpact.Test.Simple.AllMap;
|
||||
using BetterGenshinImpact.Test.View;
|
||||
|
||||
namespace BetterGenshinImpact.Test;
|
||||
|
||||
/// <summary>
|
||||
/// MainWindow.xaml 的交互逻辑
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
Global.StartUpPath = @"D:\HuiPrograming\Projects\CSharp\MiHoYo\BetterGenshinImpact\BetterGenshinImpact\bin\x64\Debug\net7.0-windows10.0.22621.0";
|
||||
}
|
||||
|
||||
private void ShowCameraRecWindow(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
new CameraRecWindow().Show();
|
||||
}
|
||||
|
||||
private void ShowHsvTestWindow(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
new HsvTestWindow().Run();
|
||||
}
|
||||
|
||||
private void DoMapPuzzle(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
MapPuzzle.Put();
|
||||
}
|
||||
|
||||
private void DoOcrTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
OcrTest.TestYap();
|
||||
}
|
||||
|
||||
private void DoMatchTemplateTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
MatchTemplateTest.Test();
|
||||
}
|
||||
|
||||
private void DoMatchTest(object sender, System.Windows.RoutedEventArgs e)
|
||||
{
|
||||
// KeyPointMatchTest.Test();
|
||||
// EntireMapTest.Test();
|
||||
EntireMapTest.Storage();
|
||||
}
|
||||
|
||||
private void MapDrawTeleportPoint(object sender, RoutedEventArgs e)
|
||||
{
|
||||
MapTeleportPointDraw.Draw();
|
||||
}
|
||||
|
||||
private void GenAvatarData(object sender, RoutedEventArgs e)
|
||||
{
|
||||
AvatarClassifyGen.GenAll();
|
||||
}
|
||||
|
||||
private void AutoCookTestCase(object sender, RoutedEventArgs e)
|
||||
{
|
||||
AutoCookTest.Test();
|
||||
}
|
||||
}
|
||||
+11
-19
@@ -1,13 +1,10 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Detail;
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Forms;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
@@ -22,21 +19,22 @@ public class EntireMapTest
|
||||
|
||||
speedTimer.Record("初始化特征");
|
||||
|
||||
var p = surfMatcher.Match(queryMat);
|
||||
var pArray = surfMatcher.Match(queryMat);
|
||||
speedTimer.Record("匹配1");
|
||||
if (!p.IsEmpty())
|
||||
if (pArray != null)
|
||||
{
|
||||
Debug.WriteLine($"Matched rect 1: {p}");
|
||||
Cv2.Circle(mainMap1024BlockMat, p.ToPoint(), 10, Scalar.Red);
|
||||
var rect = Cv2.BoundingRect(pArray);
|
||||
Debug.WriteLine($"Matched rect 1: {rect}");
|
||||
Cv2.Rectangle(mainMap1024BlockMat, rect, Scalar.Red, 2);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b1.png", mainMap1024BlockMat);
|
||||
|
||||
var p2 = surfMatcher.Match(queryMat, p.X, p.Y);
|
||||
var pArray2 = surfMatcher.Match(queryMat, rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
|
||||
speedTimer.Record("匹配2");
|
||||
if (!p2.IsEmpty())
|
||||
if (pArray2 != null)
|
||||
{
|
||||
// var rect2 = Cv2.BoundingRect(pArray2);
|
||||
Debug.WriteLine($"Matched rect 2: {p2}");
|
||||
// Cv2.Rectangle(mainMap1024BlockMat, rect2, Scalar.Yellow, 1);
|
||||
var rect2 = Cv2.BoundingRect(pArray2);
|
||||
Debug.WriteLine($"Matched rect 2: {rect2}");
|
||||
Cv2.Rectangle(mainMap1024BlockMat, rect2, Scalar.Yellow, 1);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\b2.png", mainMap1024BlockMat);
|
||||
}
|
||||
else
|
||||
@@ -53,13 +51,7 @@ public class EntireMapTest
|
||||
|
||||
public static void Storage()
|
||||
{
|
||||
var featureMatcher = new FeatureMatcher(new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\map_52_2048.png", ImreadModes.Grayscale), new FeatureStorage("mainMap2048Block"));
|
||||
var featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap2048BlockMat.Value, new FeatureStorage("mainMap2048Block"));
|
||||
MessageBox.Show("特征点生成完成");
|
||||
}
|
||||
|
||||
public static void Storage256()
|
||||
{
|
||||
FeatureMatcher _featureMatcher = new( new Mat(Global.Absolute(@"Assets\Map\mainMap256Block.png"), ImreadModes.Grayscale), new FeatureStorage("mainMap256Block"));
|
||||
MessageBox.Show("256特征点生成完成");
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -281,10 +281,10 @@ public class KeyPointMatchTest
|
||||
writer.Write(image.Rows);
|
||||
writer.Write(image.Cols);
|
||||
int depth = image.Depth();
|
||||
MatType type = image.Type();
|
||||
int type = image.Type();
|
||||
int channels = image.Channels();
|
||||
writer.Write(depth);
|
||||
writer.Write(type.Value);
|
||||
writer.Write(type);
|
||||
writer.Write(channels);
|
||||
int sizeInBytes = (int)image.Step() * image.Rows;
|
||||
writer.Write(sizeInBytes);
|
||||
+9
-56
@@ -8,6 +8,7 @@ namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class MapPuzzle
|
||||
{
|
||||
public static readonly int block = 2048;
|
||||
|
||||
public static List<string> PicWhiteHashList = new List<string>
|
||||
{
|
||||
@@ -25,29 +26,9 @@ public class MapPuzzle
|
||||
|
||||
public static MD5 Md5Service = MD5.Create();
|
||||
|
||||
public static void PutAll()
|
||||
public static void Put()
|
||||
{
|
||||
var folder = @"E:\HuiTask\更好的原神\地图匹配\拼图结果\6.4";
|
||||
Directory.CreateDirectory(folder);
|
||||
|
||||
// 保存2048大图
|
||||
var img2048 = Put(2048);
|
||||
Cv2.ImWrite(@$"{folder}\map_2048.png", img2048);
|
||||
|
||||
// 保存1024
|
||||
var img1024 = Put(1024);
|
||||
Cv2.ImWrite(@$"{folder}\map_1024.png", img1024);
|
||||
|
||||
// 保存256
|
||||
var grayImage = new Mat();
|
||||
Cv2.CvtColor(img2048.Resize(new Size(img2048.Width / 8, img2048.Height / 8), 0, 0, InterpolationFlags.Cubic), grayImage, ColorConversionCodes.BGR2GRAY);
|
||||
Cv2.ImWrite(@$"{folder}\Teyvat_0_256.png", grayImage);
|
||||
|
||||
}
|
||||
|
||||
public static Mat Put(int block = 2048)
|
||||
{
|
||||
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\地图块素材\UI_Map_最新"; // 图片文件夹路径
|
||||
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map"; // 图片文件夹路径
|
||||
string pattern = @"UI_MapBack_([-+]?\d+)_([-+]?\d+)(.*)";
|
||||
var images = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly); // 获取所有图片文件路径
|
||||
|
||||
@@ -133,7 +114,6 @@ public class MapPuzzle
|
||||
// 计算大图的总宽度和高度
|
||||
var lenCol = maxCol - minCol;
|
||||
var lenRow = maxRow - minRow;
|
||||
Debug.WriteLine($"列数X: {lenCol+1}, 行数Y: {lenRow+1}");
|
||||
int totalWidth = (lenCol + 1) * block;
|
||||
int totalHeight = (lenRow + 1) * block;
|
||||
|
||||
@@ -177,43 +157,16 @@ public class MapPuzzle
|
||||
Debug.WriteLine("");
|
||||
}
|
||||
|
||||
// 地图图片块
|
||||
// SaveImagesAs1024X1024(arr, imageLocations, @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\地图块", minRow, minCol);
|
||||
|
||||
|
||||
// 保存大图
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\map_46_2048.png", largeImage);
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_sd4x.png", largeImage.Resize(new Size(largeImage.Width / 4, largeImage.Height / 4), 0, 0, InterpolationFlags.Cubic));
|
||||
// Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\combined_image_small.png", largeImage.Resize(new Size(1400, 1300), 0, 0, InterpolationFlags.Cubic));
|
||||
|
||||
// 释放资源
|
||||
return largeImage;
|
||||
}
|
||||
|
||||
public static void SaveImagesAs1024X1024(int[,] arr, Dictionary<(int row, int col), ImgInfo> imageLocations, string outputFolder, int minRow, int minCol)
|
||||
{
|
||||
if (!Directory.Exists(outputFolder))
|
||||
largeImage.Dispose();
|
||||
foreach (var img in imageLocations.Values)
|
||||
{
|
||||
Directory.CreateDirectory(outputFolder);
|
||||
}
|
||||
|
||||
for (int row = 0; row < arr.GetLength(0); row++)
|
||||
{
|
||||
for (int col = 0; col < arr.GetLength(1); col++)
|
||||
{
|
||||
if (arr[row, col] == 1)
|
||||
{
|
||||
var key = (row + minRow, col + minCol);
|
||||
if (imageLocations.TryGetValue(key, out var imgInfo))
|
||||
{
|
||||
var img = imgInfo.Img;
|
||||
if (img.Width != 1204 || img.Height != 1204)
|
||||
{
|
||||
img = imgInfo.Img.Resize(new Size(1024, 1024), 0, 0, InterpolationFlags.Nearest);
|
||||
}
|
||||
var outputPath = Path.Combine(outputFolder, $"{row}_{col}.png");
|
||||
Cv2.ImWrite(outputPath, img);
|
||||
img.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
img.Img.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
using BetterGenshinImpact.Service;
|
||||
using OpenCvSharp;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple.AllMap;
|
||||
|
||||
public class MapTeleportPointDraw
|
||||
{
|
||||
public static void Draw()
|
||||
{
|
||||
var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\Json_Integration\锚点&神像\");
|
||||
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\genshin_map_带标记.png");
|
||||
DrawTeleportPoint(map, pList.ToArray());
|
||||
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\genshin_map_带标记_传送点.png", map);
|
||||
}
|
||||
|
||||
public static void DrawTeleportPoint(Mat map, Point[] points)
|
||||
{
|
||||
foreach (var point in points)
|
||||
{
|
||||
Cv2.Circle(map, new Point(point.X, point.Y), 10, Scalar.Red, 2);
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Point> LoadTeleportPoint(string folderPath)
|
||||
{
|
||||
string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
|
||||
List<Point> points = new();
|
||||
foreach (var file in files)
|
||||
{
|
||||
var gamePoint = JsonSerializer.Deserialize<GamePoint>(File.ReadAllText(file), ConfigService.JsonOptions);
|
||||
if (gamePoint == null)
|
||||
{
|
||||
Debug.WriteLine($"{file} json is null");
|
||||
continue;
|
||||
}
|
||||
|
||||
points.Add(Transform(gamePoint.Position));
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 坐标系转换
|
||||
/// </summary>
|
||||
/// <param name="position">[a,b,c]</param>
|
||||
/// <returns></returns>
|
||||
public static Point Transform(decimal[] position)
|
||||
{
|
||||
// 四舍六入五取偶
|
||||
var a = (int)Math.Round(position[0]); // 上
|
||||
var c = (int)Math.Round(position[2]); // 左
|
||||
|
||||
// 转换1024区块坐标,大地图坐标系正轴是往左上方向的
|
||||
// 这里写最左上角的区块坐标(m,n)/(上,左),截止4.5版本,最左上角的区块坐标是(5,7)
|
||||
|
||||
int m = 5, n = 7;
|
||||
return new Point((n + 1) * 1024 - c, (m + 1) * 1024 - a);
|
||||
}
|
||||
|
||||
class GamePoint
|
||||
{
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public decimal[] Position { get; set; } = new decimal[3];
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
+1
-1
@@ -61,7 +61,7 @@ internal class HsvTestWindow
|
||||
Cv2.CreateTrackbar("High S", _windowDetectionName, ref _highS, MaxValue, on_high_S_thresh_trackbar);
|
||||
Cv2.CreateTrackbar("Low V", _windowDetectionName, ref _lowV, MaxValue, on_low_V_thresh_trackbar);
|
||||
Cv2.CreateTrackbar("High V", _windowDetectionName, ref _highV, MaxValue, on_high_V_thresh_trackbar);
|
||||
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\Q识别\拼图\2.png", ImreadModes.Color);
|
||||
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\bsz1.png", ImreadModes.Color);
|
||||
Mat frameHsv = new Mat();
|
||||
// Convert from BGR to HSV colorspace
|
||||
Cv2.CvtColor(frame, frameHsv, ColorConversionCodes.BGR2HSV);
|
||||
File renamed without changes.
+1
-1
@@ -282,7 +282,7 @@ public class CharacterOrientationTest
|
||||
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
Rect maxRect = default;
|
||||
var maxRect = Rect.Empty;
|
||||
var maxIndex = 0;
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Diagnostics;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Test.Simple;
|
||||
|
||||
public class OcrTest
|
||||
{
|
||||
public static void TestYap()
|
||||
{
|
||||
Mat mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
|
||||
var text = TextInferenceFactory.Pick.Inference(PreProcessForInference(mat));
|
||||
Debug.WriteLine(text);
|
||||
|
||||
Mat mat2 = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png", ImreadModes.Grayscale);
|
||||
var text2 = OcrFactory.Paddle.Ocr(mat2);
|
||||
Debug.WriteLine(text2);
|
||||
}
|
||||
|
||||
private static Mat PreProcessForInference(Mat mat)
|
||||
{
|
||||
// Yap 已经改用灰度图了 https://github.com/Alex-Beng/Yap/commit/c2ad1e7b1442aaf2d80782a032e00876cd1c6c84
|
||||
// 二值化
|
||||
// Cv2.Threshold(mat, mat, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
|
||||
//Cv2.AdaptiveThreshold(mat, mat, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 31, 3); // 效果不错 但是和模型不搭
|
||||
//mat = OpenCvCommonHelper.Threshold(mat, Scalar.FromRgb(235, 235, 235), Scalar.FromRgb(255, 255, 255)); // 识别物品不太行
|
||||
// 不知道为什么要强制拉伸到 221x32
|
||||
mat = ResizeHelper.ResizeTo(mat, 221, 32);
|
||||
// 填充到 384x32
|
||||
var padded = new Mat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
|
||||
padded[new Rect(0, 0, mat.Width, mat.Height)] = mat;
|
||||
//Cv2.ImWrite(Global.Absolute("padded.png"), padded);
|
||||
return padded;
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<Platforms>x64</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="NativeMethods.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Windows.CsWin32" Version="0.3.46-beta">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/microsoft/CsWin32/main/src/Microsoft.Windows.CsWin32/settings.schema.json",
|
||||
"allowMarshaling": true,
|
||||
"useSafeHandles": false,
|
||||
"emitSingleFile": true,
|
||||
"public": true,
|
||||
"comInterop": {
|
||||
"useIntPtrForComOutPointers": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// D3D11
|
||||
CreateDirect3D11DeviceFromDXGIDevice
|
||||
CreateDirect3D11SurfaceFromDXGISurface
|
||||
|
||||
// GDI32
|
||||
BitBlt
|
||||
CreateCompatibleBitmap
|
||||
CreateCompatibleDC
|
||||
DeleteDC
|
||||
GetDeviceCaps
|
||||
SelectObject
|
||||
|
||||
// User32
|
||||
GetClientRect
|
||||
GetDC
|
||||
GetForegroundWindow
|
||||
GetSystemMetrics
|
||||
GetWindowDC
|
||||
GetWindowRect
|
||||
GetWindowThreadProcessId
|
||||
mouse_event
|
||||
PostMessage
|
||||
ReleaseDC
|
||||
EnumWindows
|
||||
GetWindowText
|
||||
IsWindowVisible
|
||||
GetWindowTextLength
|
||||
|
||||
// COM & WinRT
|
||||
D3D11CreateDevice
|
||||
ID3D11Device3
|
||||
IDirect3DDxgiInterfaceAccess
|
||||
|
||||
// Constants
|
||||
D3D11_SDK_VERSION
|
||||
DXGI_ERROR_UNSUPPORTED
|
||||
WM_LBUTTONDOWN
|
||||
WM_LBUTTONUP
|
||||
+71
-21
@@ -5,18 +5,28 @@ VisualStudioVersion = 17.6.33815.320
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact", "BetterGenshinImpact\BetterGenshinImpact.csproj", "{75EC89E2-413D-4725-BCEA-AFAC57708F07}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Vision.WindowCapture", "Vision.WindowCapture\Vision.WindowCapture.csproj", "{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Win32", "BetterGenshinImpact.Win32\BetterGenshinImpact.Win32.csproj", "{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.GameCapture", "Fischless.GameCapture\Fischless.GameCapture.csproj", "{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Vision.WindowCapture.Test", "Vision.WindowCapture.Test\Vision.WindowCapture.Test.csproj", "{D35CB953-C666-4E57-9A9A-3AAE5BF78402}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.HotkeyCapture", "Fischless.HotkeyCapture\Fischless.HotkeyCapture.csproj", "{08152E44-2564-46C5-B5B2-54DD43C01A79}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test", "Test\BetterGenshinImpact.Test\BetterGenshinImpact.Test.csproj", "{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.KeyboardCapture", "Fischless.KeyboardCapture\Fischless.KeyboardCapture.csproj", "{10A48327-7E58-4B51-B1FC-55506C703C8F}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Deploy", "Deploy", "{458E1106-43A4-47E6-B11B-D243035D4C76}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicaSetup", "Build\MicaSetup\MicaSetup.csproj", "{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MicaSetup.Uninst", "Build\MicaSetup\MicaSetup.Uninst.csproj", "{673344BC-B860-44AE-AD88-D33465BDE25B}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test", "BetterGenshinImpact.Test\BetterGenshinImpact.Test.csproj", "{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.WindowsInput", "Fischless.WindowsInput\Fischless.WindowsInput.csproj", "{9D00BC7A-9280-4AC9-8951-4502EDB71B76}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.UnitTest", "Test\BetterGenshinImpact.UnitTest\BetterGenshinImpact.UnitTest.csproj", "{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -33,6 +43,22 @@ Global
|
||||
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|Any CPU.Build.0 = Release|x64
|
||||
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|x64.ActiveCfg = Release|x64
|
||||
{75EC89E2-413D-4725-BCEA-AFAC57708F07}.Release|x64.Build.0 = Release|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Debug|x64.Build.0 = Debug|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|Any CPU.Build.0 = Release|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|x64.ActiveCfg = Release|x64
|
||||
{C9080C1D-1B26-46CB-A494-A5E7FE3FCEBA}.Release|x64.Build.0 = Release|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Debug|x64.Build.0 = Debug|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|Any CPU.Build.0 = Release|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|x64.ActiveCfg = Release|x64
|
||||
{75F4541B-9624-4AFB-BAEA-3EAFD3300EE1}.Release|x64.Build.0 = Release|x64
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Debug|x64.ActiveCfg = Debug|x64
|
||||
@@ -41,6 +67,14 @@ Global
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|Any CPU.Build.0 = Release|x64
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|x64.ActiveCfg = Release|x64
|
||||
{6B0A3D96-D88D-48DD-8112-4CD5BA5D27CE}.Release|x64.Build.0 = Release|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Debug|x64.Build.0 = Debug|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|Any CPU.Build.0 = Release|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|x64.ActiveCfg = Release|x64
|
||||
{D35CB953-C666-4E57-9A9A-3AAE5BF78402}.Release|x64.Build.0 = Release|x64
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Debug|x64.ActiveCfg = Debug|x64
|
||||
@@ -49,14 +83,38 @@ Global
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|Any CPU.Build.0 = Release|x64
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.ActiveCfg = Release|x64
|
||||
{08152E44-2564-46C5-B5B2-54DD43C01A79}.Release|x64.Build.0 = Release|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Debug|x64.Build.0 = Debug|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|Any CPU.Build.0 = Release|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|x64.ActiveCfg = Release|x64
|
||||
{10A48327-7E58-4B51-B1FC-55506C703C8F}.Release|x64.Build.0 = Release|x64
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Debug|x64.Build.0 = Debug|x64
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|x64.ActiveCfg = Release|x64
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15}.Release|x64.Build.0 = Release|x64
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Debug|x64.Build.0 = Debug|x64
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|x64.ActiveCfg = Release|x64
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B}.Release|x64.Build.0 = Release|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.Build.0 = Debug|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.Build.0 = Release|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.ActiveCfg = Release|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.Build.0 = Release|x64
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE}.Release|x64.Build.0 = Release|Any CPU
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|Any CPU.ActiveCfg = Debug|x64
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|Any CPU.Build.0 = Debug|x64
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Debug|x64.ActiveCfg = Debug|x64
|
||||
@@ -65,21 +123,13 @@ Global
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|Any CPU.Build.0 = Release|x64
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.ActiveCfg = Release|x64
|
||||
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.Build.0 = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Debug|x64.Build.0 = Debug|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.ActiveCfg = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|Any CPU.Build.0 = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.ActiveCfg = Release|x64
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{27AF227E-BE44-450F-8E95-C1AD4FDE14BE} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{7DA575C0-8D1E-4BD2-AEDB-5471D8906B98} = {02CEA57F-C24B-40F9-AF31-F1D4F3BDB4BF}
|
||||
{AB85DA23-EB8F-4FBF-A7FA-35CE05B23C15} = {458E1106-43A4-47E6-B11B-D243035D4C76}
|
||||
{673344BC-B860-44AE-AD88-D33465BDE25B} = {458E1106-43A4-47E6-B11B-D243035D4C76}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {352D8B78-9DE3-4E58-985F-FADD22594DB4}
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=chyan/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=enkanomiya/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Kongying/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=mirrorchan/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=onslaugh/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=retcode/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=serenitea/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=steambird/@EntryIndexedValue">True</s:Boolean>
|
||||
<s:Boolean x:Key="/Default/UserDictionary/Words/=Teyvat/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
|
||||
@@ -1 +0,0 @@
|
||||
/Assets/Strings/*.html linguist-vendored
|
||||
@@ -1,35 +1,19 @@
|
||||
<Application x:Class="BetterGenshinImpact.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
|
||||
xmlns:bgivc="clr-namespace:BetterGenshinImpact.View.Converters"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
xmlns:vio="http://schemas.lepo.co/wpfui/2022/xaml/violeta">
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
|
||||
<Application.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ui:ThemesDictionary Theme="Dark" />
|
||||
<ui:ControlsDictionary />
|
||||
<vio:ControlsDictionary />
|
||||
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
|
||||
<ResourceDictionary Source="/View/Controls/Drawer/DrawerStyles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
|
||||
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
|
||||
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
|
||||
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
|
||||
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
|
||||
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
|
||||
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
|
||||
<bgivc:NotNullConverter x:Key="NotNullConverter" />
|
||||
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
|
||||
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
|
||||
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
|
||||
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
|
||||
</Style>
|
||||
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type ui:TextBox}">
|
||||
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</Application.Resources>
|
||||
</Application>
|
||||
+14
-109
@@ -1,17 +1,6 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Helpers.Extensions;
|
||||
using BetterGenshinImpact.Helpers.Win32;
|
||||
using BetterGenshinImpact.Hutao;
|
||||
using BetterGenshinImpact.Service;
|
||||
using BetterGenshinImpact.Service.Interface;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
@@ -20,23 +9,17 @@ using BetterGenshinImpact.View;
|
||||
using BetterGenshinImpact.View.Pages;
|
||||
using BetterGenshinImpact.ViewModel;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using BetterGenshinImpact.ViewModel.Pages.View;
|
||||
using LazyCache;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using Serilog.Events;
|
||||
using Serilog.Sinks.RichTextBox.Abstraction;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using Wpf.Ui;
|
||||
using Wpf.Ui.DependencyInjection;
|
||||
using Wpf.Ui.Violeta.Appearance;
|
||||
using Wpf.Ui.Violeta.Controls;
|
||||
|
||||
// Wine 平台适配
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
using BetterGenshinImpact.Service.Tavern;
|
||||
|
||||
namespace BetterGenshinImpact;
|
||||
|
||||
@@ -48,10 +31,8 @@ public partial class App : Application
|
||||
// https://docs.microsoft.com/dotnet/core/extensions/configuration
|
||||
// https://docs.microsoft.com/dotnet/core/extensions/logging
|
||||
private static readonly IHost _host = Host.CreateDefaultBuilder()
|
||||
.CheckIntegration()
|
||||
.UseElevated()
|
||||
.UseSingleInstance("BetterGI")
|
||||
.ConfigureLogging(builder => { builder.ClearProviders(); })
|
||||
.ConfigureServices(
|
||||
(context, services) =>
|
||||
{
|
||||
@@ -64,42 +45,30 @@ public partial class App : Application
|
||||
Directory.CreateDirectory(logFolder);
|
||||
var logFile = Path.Combine(logFolder, "better-genshin-impact.log");
|
||||
|
||||
var richTextBox = new RichTextBoxImpl();
|
||||
services.AddSingleton<IRichTextBox>(richTextBox);
|
||||
var maskWindow = new MaskWindow();
|
||||
services.AddSingleton(maskWindow);
|
||||
|
||||
var loggerConfiguration = new LoggerConfiguration()
|
||||
.WriteTo.File(logFile,
|
||||
outputTemplate:
|
||||
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
|
||||
rollingInterval: RollingInterval.Day,
|
||||
retainedFileCountLimit: 31,
|
||||
retainedFileTimeLimit: TimeSpan.FromDays(21))
|
||||
.WriteTo.Console(outputTemplate:
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.File(path: logFile, outputTemplate: "[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}", rollingInterval: RollingInterval.Day)
|
||||
.MinimumLevel.Debug()
|
||||
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
|
||||
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
|
||||
if (all.MaskWindowConfig.MaskEnabled)
|
||||
{
|
||||
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
|
||||
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
loggerConfiguration.WriteTo.RichTextBox(maskWindow.LogBox, LogEventLevel.Information, outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
|
||||
}
|
||||
|
||||
Log.Logger = loggerConfiguration.CreateLogger();
|
||||
services.AddLogging(c => c.AddSerilog());
|
||||
|
||||
services.AddLocalization();
|
||||
|
||||
services.AddNavigationViewPageProvider();
|
||||
// App Host
|
||||
services.AddHostedService<ApplicationHostService>();
|
||||
|
||||
// Page resolver service
|
||||
services.AddSingleton<INavigationService, NavigationService>();
|
||||
services.AddSingleton<IUpdateService, UpdateService>();
|
||||
services.AddSingleton<IPageService, PageService>();
|
||||
|
||||
// Service containing navigation, same as INavigationWindow... but without window
|
||||
services.AddSingleton<INavigationService, NavigationService>();
|
||||
services.AddSingleton<ISnackbarService, SnackbarService>();
|
||||
|
||||
// Main window with navigation
|
||||
services.AddView<INavigationWindow, MainWindow, MainWindowViewModel>();
|
||||
@@ -114,54 +83,19 @@ public partial class App : Application
|
||||
services.AddView<TaskSettingsPage, TaskSettingsPageViewModel>();
|
||||
services.AddView<HotKeyPage, HotKeyPageViewModel>();
|
||||
services.AddView<NotificationSettingsPage, NotificationSettingsPageViewModel>();
|
||||
services.AddView<KeyMouseRecordPage, KeyMouseRecordPageViewModel>();
|
||||
services.AddView<JsListPage, JsListViewModel>();
|
||||
services.AddView<MapPathingPage, MapPathingViewModel>();
|
||||
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
|
||||
services.AddSingleton<PathingConfigViewModel>();
|
||||
// services.AddView<PathingConfigView, PathingConfigViewModel>();
|
||||
services.AddView<KeyBindingsSettingsPage, KeyBindingsSettingsPageViewModel>();
|
||||
|
||||
// 一条龙 ViewModels
|
||||
// services.AddSingleton<CraftViewModel>();
|
||||
// services.AddSingleton<DailyCommissionViewModel>();
|
||||
// services.AddSingleton<DailyRewardViewModel>();
|
||||
// services.AddSingleton<DomainViewModel>();
|
||||
// services.AddSingleton<ForgingViewModel>();
|
||||
// services.AddSingleton<LeyLineBlossomViewModel>();
|
||||
// services.AddSingleton<MailViewModel>();
|
||||
// services.AddSingleton<SereniteaPotViewModel>();
|
||||
// services.AddSingleton<TcgViewModel>();
|
||||
|
||||
// My Services
|
||||
services.AddSingleton<TaskTriggerDispatcher>();
|
||||
services.AddSingleton<NotificationService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
|
||||
services.AddSingleton<NotifierManager>();
|
||||
services.AddSingleton<IScriptService, ScriptService>();
|
||||
services.AddSingleton<HutaoNamedPipe>();
|
||||
services.AddSingleton<BgiOnnxFactory>();
|
||||
services.AddSingleton<OcrFactory>();
|
||||
services.AddMemoryCache();
|
||||
services.AddSingleton<IAppCache, CachingService>();
|
||||
services.AddSingleton<MemoryFileCache>();
|
||||
services.AddSingleton<IMihoyoMapApiService, MihoyoMapApiService>();
|
||||
services.AddSingleton<IKongyingTavernApiService, KongyingTavernApiService>();
|
||||
services.AddSingleton<IMaskMapPointService, MaskMapPointService>();
|
||||
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
|
||||
|
||||
// Configuration
|
||||
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
|
||||
|
||||
I18N.Culture = new CultureInfo("zh-Hans"); // #1846
|
||||
}
|
||||
)
|
||||
.Build();
|
||||
|
||||
public static IServiceProvider ServiceProvider => _host.Services;
|
||||
|
||||
public static ILogger<T> GetLogger<T>()
|
||||
{
|
||||
return _host.Services.GetService<ILogger<T>>()!;
|
||||
@@ -192,24 +126,18 @@ public partial class App : Application
|
||||
/// </summary>
|
||||
protected override async void OnStartup(StartupEventArgs e)
|
||||
{
|
||||
// Wine 平台适配
|
||||
WinePlatformAddon.ApplyApplicationConfig();
|
||||
base.OnStartup(e);
|
||||
|
||||
try
|
||||
{
|
||||
// 分配控制台窗口以支持控制台输出
|
||||
ConsoleHelper.AllocateConsole("BetterGI Console");
|
||||
RegisterEvents();
|
||||
await _host.StartAsync();
|
||||
ServerTimeHelper.Initialize(_host.Services.GetRequiredService<IServerTimeProvider>());
|
||||
await UrlProtocolHelper.RegisterAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// DEBUG only, no overhead
|
||||
Debug.WriteLine(ex);
|
||||
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
|
||||
|
||||
if (Debugger.IsAttached)
|
||||
{
|
||||
@@ -225,15 +153,8 @@ public partial class App : Application
|
||||
{
|
||||
base.OnExit(e);
|
||||
|
||||
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
|
||||
|
||||
TempManager.CleanUp();
|
||||
|
||||
await _host.StopAsync();
|
||||
_host.Dispose();
|
||||
|
||||
// 释放控制台窗口
|
||||
ConsoleHelper.FreeConsoleWindow();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -288,7 +209,7 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
//UI线程未捕获异常处理事件(UI主线程)
|
||||
private static void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
|
||||
private static void AppDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -312,23 +233,7 @@ public partial class App : Application
|
||||
e = e.InnerException;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
ExceptionReport.Show(e);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Fallback.
|
||||
System.Windows.Forms.MessageBox.Show(
|
||||
$"""
|
||||
程序异常:{e.Source}
|
||||
--
|
||||
{e.StackTrace}
|
||||
--
|
||||
{e.Message}
|
||||
"""
|
||||
);
|
||||
}
|
||||
MessageBox.Show("程序异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
|
||||
|
||||
// log
|
||||
GetLogger<App>().LogDebug(e, "UnHandle Exception");
|
||||
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,72 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<SyntaxDefinition name="Json" extensions=".json" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008">
|
||||
<Color name="Bool" foreground="#569CD6" exampleText="true | false" />
|
||||
<Color name="Number" foreground="#B5CEA8" exampleText="3.14" />
|
||||
<Color name="String" foreground="#CE9178" exampleText="" />
|
||||
<Color name="Null" foreground="#569CD6" exampleText="" />
|
||||
<Color name="FieldName" foreground="#9CDCF0" />
|
||||
<Color name="Punctuation1" foreground="#DA66BE" />
|
||||
<Color name="Punctuation2" foreground="#FFD710" />
|
||||
<Color name="Punctuation3" foreground="#FFFFFF" />
|
||||
|
||||
<RuleSet name="String">
|
||||
<Span begin="\\" end="."/>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Object">
|
||||
<Span color="FieldName" ruleSet="String">
|
||||
<Begin>"</Begin>
|
||||
<End>"</End>
|
||||
</Span>
|
||||
<Span color="FieldName" ruleSet="String">
|
||||
<Begin>'</Begin>
|
||||
<End>'</End>
|
||||
</Span>
|
||||
<Span color="Punctuation3" ruleSet="Expression">
|
||||
<Begin>:</Begin>
|
||||
</Span>
|
||||
<Span color="Punctuation3">
|
||||
<Begin>,</Begin>
|
||||
</Span>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Array">
|
||||
<Import ruleSet="Expression"/>
|
||||
<Span color="Punctuation3">
|
||||
<Begin>,</Begin>
|
||||
</Span>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet name="Expression">
|
||||
<Keywords color="Bool" >
|
||||
<Word>true</Word>
|
||||
<Word>false</Word>
|
||||
</Keywords>
|
||||
<Keywords color="Null" >
|
||||
<Word>null</Word>
|
||||
</Keywords>
|
||||
<Span color="String" ruleSet="String">
|
||||
<Begin>"</Begin>
|
||||
<End>"</End>
|
||||
</Span>
|
||||
<Span color="String" ruleSet="String">
|
||||
<Begin>'</Begin>
|
||||
<End>'</End>
|
||||
</Span>
|
||||
<Span color="Punctuation1" ruleSet="Object" multiline="true">
|
||||
<Begin>\{</Begin>
|
||||
<End>\}</End>
|
||||
</Span>
|
||||
<Span color="Punctuation2" ruleSet="Array" multiline="true">
|
||||
<Begin>\[</Begin>
|
||||
<End>\]</End>
|
||||
</Span>
|
||||
<Rule color="Number">
|
||||
\b0[xX][0-9a-fA-F]+|(\b\d+(\.[0-9]+)?|\.[0-9]+)([eE][+-]?[0-9]+)?
|
||||
</Rule>
|
||||
</RuleSet>
|
||||
|
||||
<RuleSet>
|
||||
<Import ruleSet="Expression"/>
|
||||
</RuleSet>
|
||||
</SyntaxDefinition>
|
||||
File renamed without changes.
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Binary file not shown.
File renamed without changes.
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
File renamed without changes.
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 229 KiB |
@@ -1,106 +1,62 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.55.2-alpha.1</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
<TargetFramework>net7.0-windows10.0.22621.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWPF>true</UseWPF>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<UseWindowsForms>True</UseWindowsForms>
|
||||
<LangVersion>12.0</LangVersion>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<ApplicationIcon>Resources\Images\logo.ico</ApplicationIcon>
|
||||
<ApplicationIcon>Assets\logo.ico</ApplicationIcon>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Platforms>x64</Platforms>
|
||||
<DebugType>embedded</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- <ItemGroup>
|
||||
<None Remove="Assets\Images\*.jpg" />
|
||||
<None Remove="Assets\Images\*" />
|
||||
<None Remove="Assets\Images\*.png" />
|
||||
<None Remove="Assets\Images\*.ico" />
|
||||
<ItemGroup>
|
||||
<None Remove="Assets\*.jpg" />
|
||||
<None Remove="Assets\*.png" />
|
||||
<None Remove="Assets\*.ico" />
|
||||
<None Remove="Assets\Fonts\*.ttf" />
|
||||
<None Remove="Assets\Highlighting\*.xshd" />
|
||||
<None Remove="Assets\Strings\*.html" />
|
||||
<None Remove="Assets\Strings\*.md" />
|
||||
<None Remove="Assets\Audios\*.mp3" />
|
||||
<None Update="Assets\Config\*"/>
|
||||
</ItemGroup>-->
|
||||
|
||||
<ItemGroup>
|
||||
<Resource Include="Resources\Images\*.jpg" />
|
||||
<Resource Include="Resources\Images\Anniversary\*" />
|
||||
<Resource Include="Resources\Images\*.png" />
|
||||
<Resource Include="Resources\Images\*.ico" />
|
||||
<Resource Include="Resources\Fonts\*.ttf" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.1.120" />
|
||||
<PackageReference Include="BehaviourTree" Version="1.0.73" />
|
||||
<Resource Include="Assets\*.jpg" />
|
||||
<Resource Include="Assets\*.png" />
|
||||
<Resource Include="Assets\*.ico" />
|
||||
<Resource Include="Assets\Fonts\*.ttf" />
|
||||
<Resource Include="Assets\Highlighting\*.xshd" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
|
||||
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
|
||||
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.18" />
|
||||
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.10" />
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
|
||||
<PackageReference Include="clipper_standard" Version="0.0.1" />
|
||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
|
||||
<PackageReference Include="DeviceId" Version="6.9.0" />
|
||||
<PackageReference Include="DeviceId.Windows" Version="6.9.0" />
|
||||
<PackageReference Include="DeviceId.Windows.Wmi" Version="6.9.0" />
|
||||
<PackageReference Include="Emoji.Wpf" Version="0.3.4" />
|
||||
<PackageReference Include="LibGit2Sharp" Version="0.31.0" />
|
||||
<PackageReference Include="LazyCache" Version="2.4.0" />
|
||||
<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" />
|
||||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.21.0" />
|
||||
<!--排除掉cpu的runtime dll-->
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.21.0" IncludeAssets="none" />
|
||||
<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.14.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.17.1" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.17.1" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.122" />
|
||||
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
|
||||
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.77" />
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="PresentMonFps" Version="2.0.5" />
|
||||
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
|
||||
<PackageReference Include="Semver" Version="3.0.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.1" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
|
||||
<PackageReference Include="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.NtDll" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
|
||||
<PackageReference Include="XamlAnimatedGif" Version="2.3.1" />
|
||||
<PackageReference Include="WPF-UI" Version="4.2.0" />
|
||||
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.2.0" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="4.2.0" />
|
||||
<PackageReference Include="WPF-UI.Violeta" Version="4.2.0.1" />
|
||||
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
<PackageReference Include="YoloSharp" Version="6.0.3" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.RichTextBox.Wpf" Version="1.1.0" />
|
||||
<PackageReference Include="Vanara.PInvoke.NtDll" Version="3.4.17" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="3.4.17" />
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="3.4.17" />
|
||||
<PackageReference Include="WPF-UI" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="WPF-UI.Tray" Version="3.0.0-preview.7" />
|
||||
<PackageReference Include="YoloV8" Version="2.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
|
||||
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.4" />
|
||||
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.4" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -110,127 +66,467 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="Assets\Map\**">
|
||||
<Compile Update="GameTask\TaskContext.cs">
|
||||
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
|
||||
</Compile>
|
||||
<Compile Update="View\MaskWindow.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Update="View\Pages\HotkeyPage.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Update="View\Pages\TriggerSettingsPage.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Update="View\PickerWindow.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Update="View\Windows\MapViewer.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="Assets\Map\cityMap2048Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\combined_image_2048_lim[quick].png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\combined_image_lim[quick].png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMap100Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMap1024Block.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\mainMapZoomOut1024.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Map\map_sd1024.png">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Model\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Assets\Config\**">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\click_any_close_tip.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\condensed_resin_count.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\exit.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\fragile_resin_count.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\use_condensed_resin.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\wanderer_icon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\1920x1080\wanderer_icon_no_active.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\flashing maintenance mek bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\LogParse\Assets\**">
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\sour bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\sugardew bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\lift_rod.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\switch_bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\fake fly bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\false worm bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\fruit paste bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\bait\redrot bait.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\exit_fishing.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\space.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoFishing\Assets\1920x1080\wait_bite.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_anemo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_cryo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_dendro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_electro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_geo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_hydro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_omni.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\action_pyro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_anemo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_cryo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_dendro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_electro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_geo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_hydro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_omni.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\dice\roll_pyro.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\元素调和.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\元素骰子不足.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\冻结.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\出战角色.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\回合结束.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\回合结算阶段.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\对方行动中.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\满能量.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\确定.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\空能量.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色死亡.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色状态_冻结.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色状态_冻结2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色状态_水泡.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色血量上方.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\角色被打败.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\1920x1080\other\退出挑战.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoGeniusInvokation\Assets\tcg_character_card.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoPick\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoPick\Assets\1920x1080\F.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoPick\Assets\1920x1080\icon_settings.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\collect.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\comfirm_btn1.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\comfirm_btn2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\hangout_selected.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\hangout_unselected.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\primogem.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\re.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_daily_reward.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_explore.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoSkip\Assets\hangout.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoTrackPath\Assets\tp.json">
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\blue_track_point_28x.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\**">
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_black_cancel.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\Json\**">
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_online_no.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_online_yes.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\paimon_menu.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoMusicGame\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\icon_option.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\GameLoading\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickSereniteaPot\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoEat\Assets\1920x1080\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickBuy\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\page_close.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\UseRedeemCode\Assets\1920x1080\**">
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\stop_auto.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\**">
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\submit_goods.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\LogParse\Assets\log.css">
|
||||
<None Update="GameTask\AutoSkip\Assets\1920x1080\submit_icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\LogParse\Assets\log.js">
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\character_guide.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\GameLoading\Assets\1920x1080\enter_game.png">
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\enter_game.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\exit_welcome.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\menu_bag.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\AutoWood\Assets\1920x1080\TheBoonOfTheElderTree.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_black_confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_white_cancel.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\btn_white_confirm.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\collect.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\comfirm_btn1.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\comfirm_btn2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_daily_reward.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_explore.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\icon_option.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\paimon_menu.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\page_close.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\primogem.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\re.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\stop_auto.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\submit_icon_exclamation.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\ui_left_top_cook_icon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\ui_lt_cook_icon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\Common\Element\Assets\1920x1080\yellow_track_point_28x.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\GameLoading\Assets\1920x1080\welkin_moon_logo.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\Domain.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\Domain2.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\GoTeleport.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\Mansion.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapChoose.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapCloseButton.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapScaleButton.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\MapUndergroundSwitchButton.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\PortableWaypoint.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\ScaleWithMask.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\StatueOfTheSeven.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\SubSpaceWaypoint.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickTeleport\Assets\1920x1080\TeleportWaypoint.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="GameTask\QuickSereniteaPot\Assets\1920x1080\SereniteaPotIcon.png">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoFight\**">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\1.莫娜砂糖琴.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\2.刻晴雷神甘雨.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\3.雷神阿贝多丘丘王.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\4.重云雷神申鹤.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\5.迪希雅白术皇女.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\6.皇女科莱莫娜.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\7.莫娜白术皇女.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\8.雷神柯莱刻晴[推荐].txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\a.[惊喜牌组]东东.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\a.[惊喜牌组]巴哈拉克.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\a.[惊喜牌组]马鲁夫.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoGeniusInvokation\a.[惊喜牌组]黄衫.txt">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\default_pause_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\select_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\AutoSkip\pause_options.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\avatar_macro.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\pick_black_lists.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="User\pick_white_lists.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="GameTask\OneDragon\" />
|
||||
<Folder Include="GameTask\UseRedeemCode\Assets\1920x1080\" />
|
||||
<Folder Include="Resources\" />
|
||||
<Folder Include="Service\Notification\Builder\" />
|
||||
<Folder Include="User\AutoPathing\" />
|
||||
<Folder Include="GameTask\Common\Element\Assets\MapPoint\" />
|
||||
<Folder Include="View\Controls\WpfUi\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Page Update="View\Windows\WelcomeDialog.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<XamlRuntime>Wpf</XamlRuntime>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
<Page Update="View\Windows\MapPathingDevWindow.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<XamlRuntime>Wpf</XamlRuntime>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
<Page Update="View\Pages\View\HardwareAccelerationView.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<XamlRuntime>Wpf</XamlRuntime>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="View\Windows\WelcomeDialog.xaml.cs">
|
||||
<SubType>Code</SubType>
|
||||
<DependentUpon>WelcomeDialog.xaml</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<_DeploymentManifestIconFile Remove="Resources\Images\logo.ico" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
</Project>
|
||||
@@ -1,31 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.BgiVision;
|
||||
|
||||
public class BvImage
|
||||
{
|
||||
public RecognitionObject RecognitionObject { get; }
|
||||
|
||||
public BvImage(string templateAssert, Rect roi = default, double threshold = 0.8)
|
||||
{
|
||||
var args = templateAssert.Split(':');
|
||||
var featureName = args[0];
|
||||
var assertName = args[1];
|
||||
|
||||
RecognitionObject = new RecognitionObject
|
||||
{
|
||||
Name = templateAssert,
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage(featureName, assertName),
|
||||
RegionOfInterest = roi,
|
||||
Threshold = threshold
|
||||
}.InitTemplate();
|
||||
}
|
||||
|
||||
public RecognitionObject ToRecognitionObject()
|
||||
{
|
||||
return RecognitionObject;
|
||||
}
|
||||
}
|
||||
@@ -1,211 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
|
||||
namespace BetterGenshinImpact.Core.BgiVision;
|
||||
|
||||
/// <summary>
|
||||
/// 针对 Region 体系的包装
|
||||
/// </summary>
|
||||
public class BvLocator
|
||||
{
|
||||
private static readonly ILogger Logger = App.GetLogger<BvLocator>();
|
||||
private readonly CancellationToken _cancellationToken;
|
||||
|
||||
public RecognitionObject RecognitionObject { get; }
|
||||
|
||||
public Action<List<Region>>? RetryAction { get; set; }
|
||||
|
||||
public static int DefaultTimeout { get; set; } = 10000;
|
||||
|
||||
public static int DefaultRetryInterval { get; set; } = 250;
|
||||
|
||||
public BvLocator(RecognitionObject recognitionObject, CancellationToken cancellationToken)
|
||||
{
|
||||
RecognitionObject = recognitionObject.Clone();
|
||||
_cancellationToken = cancellationToken;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据传入的位置信息定位元素
|
||||
/// 不建议外部调用使用
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotSupportedException"></exception>
|
||||
public List<Region> FindAll()
|
||||
{
|
||||
using var screen = CaptureToRectArea();
|
||||
|
||||
if (RecognitionObject.RecognitionType == RecognitionTypes.TemplateMatch)
|
||||
{
|
||||
var region = screen.Find(RecognitionObject);
|
||||
if (region.IsExist())
|
||||
{
|
||||
return [region];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
else if (RecognitionObject.RecognitionType == RecognitionTypes.Ocr)
|
||||
{
|
||||
var results = screen.FindMulti(RecognitionObject);
|
||||
if (!string.IsNullOrEmpty(RecognitionObject.Text))
|
||||
{
|
||||
return results.FindAll(r => r.Text.Contains(RecognitionObject.Text));
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException($"不被 Locator 支持的识别类型: {RecognitionObject.RecognitionType}");
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsExist()
|
||||
{
|
||||
return FindAll().Count > 0;
|
||||
}
|
||||
|
||||
public async Task<Region> Click(int? timeout = null)
|
||||
{
|
||||
return (await WaitFor(timeout)).First().Click();
|
||||
}
|
||||
|
||||
public async Task<Region> ClickUntilDisappears(int? timeout = null)
|
||||
{
|
||||
var region = (await WaitFor(timeout)).First().Click();
|
||||
await new BvLocator(RecognitionObject, _cancellationToken)
|
||||
.WithRetryAction(resList => { resList.First().Click(); }).WaitForDisappear();
|
||||
return region;
|
||||
}
|
||||
|
||||
public async Task<Region> DoubleClick(int? timeout = null)
|
||||
{
|
||||
var list = await WaitFor(timeout);
|
||||
return list.First().DoubleClick();
|
||||
}
|
||||
|
||||
public async Task<List<Region>> WaitFor(int? timeout = null)
|
||||
{
|
||||
var actualTimeout = timeout ?? DefaultTimeout;
|
||||
var retryCount = actualTimeout / DefaultRetryInterval;
|
||||
|
||||
List<Region> results = [];
|
||||
var retryRes = await NewRetry.WaitForAction(() =>
|
||||
{
|
||||
results = FindAll();
|
||||
var b = results.Count > 0;
|
||||
RetryAction?.Invoke(results);
|
||||
return b;
|
||||
}, _cancellationToken, retryCount, DefaultRetryInterval);
|
||||
|
||||
if (retryRes)
|
||||
{
|
||||
return results;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw BuildTimeoutException(actualTimeout);
|
||||
}
|
||||
}
|
||||
|
||||
private TimeoutException BuildTimeoutException(int actualTimeout)
|
||||
{
|
||||
if (RecognitionObject.RecognitionType == RecognitionTypes.Ocr)
|
||||
{
|
||||
return new TimeoutException($"识别文字[{RecognitionObject.Text}]在 {actualTimeout}ms 后超时未出现!");
|
||||
}
|
||||
else if (RecognitionObject.RecognitionType == RecognitionTypes.TemplateMatch)
|
||||
{
|
||||
return new TimeoutException($"识别图像[{RecognitionObject.Name}]在 {actualTimeout}ms 后超时未出现!");
|
||||
}
|
||||
else
|
||||
{
|
||||
return new TimeoutException($"识别元素在 {actualTimeout}ms 后超时未出现!");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<Region>> TryWaitFor(int? timeout = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await WaitFor(timeout);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async Task WaitForDisappear(int? timeout = null)
|
||||
{
|
||||
var actualTimeout = timeout ?? DefaultTimeout;
|
||||
var retryCount = actualTimeout / DefaultRetryInterval;
|
||||
|
||||
var retryRes = await NewRetry.WaitForAction(() =>
|
||||
{
|
||||
var results = FindAll();
|
||||
var b = results.Count == 0;
|
||||
if (!b)
|
||||
{
|
||||
RetryAction?.Invoke(results);
|
||||
}
|
||||
|
||||
return b;
|
||||
}, _cancellationToken, retryCount, DefaultRetryInterval);
|
||||
|
||||
if (!retryRes)
|
||||
{
|
||||
throw new TimeoutException($"识别元素在 {actualTimeout}ms 后超时未消失!");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task TryWaitForDisappear(int? timeout = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await WaitForDisappear(timeout);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 方便优雅的设置感兴趣区域 (ROI)
|
||||
/// 该方法会覆盖 RecognitionObject.RegionOfInterest 的值。
|
||||
/// </summary>
|
||||
/// <param name="rect"></param>
|
||||
/// <returns></returns>
|
||||
public BvLocator WithRoi(Rect rect)
|
||||
{
|
||||
RecognitionObject.RegionOfInterest = rect;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BvLocator WithRoi(Func<Rect, Rect> deltaFunc)
|
||||
{
|
||||
var captureAreaRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
var rect = deltaFunc(captureAreaRect);
|
||||
RecognitionObject.RegionOfInterest = rect;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BvLocator WithRetryAction(Action<List<Region>>? action)
|
||||
{
|
||||
RetryAction = action;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Fischless.WindowsInput;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.BgiVision;
|
||||
|
||||
public class BvPage
|
||||
{
|
||||
private static readonly ILogger Logger = App.GetLogger<BvPage>();
|
||||
private readonly CancellationToken _cancellationToken;
|
||||
|
||||
public IKeyboardSimulator Keyboard => Simulation.SendInput.Keyboard;
|
||||
|
||||
public IMouseSimulator Mouse => Simulation.SendInput.Mouse;
|
||||
|
||||
/// <summary>
|
||||
/// Default timeout for operations in milliseconds
|
||||
/// </summary>
|
||||
public int DefaultTimeout { get; set; } = 10000;
|
||||
|
||||
/// <summary>
|
||||
/// Default retry interval in milliseconds
|
||||
/// </summary>
|
||||
public int DefaultRetryInterval { get; set; } = 1000;
|
||||
|
||||
public BvPage(CancellationToken cancellationToken = default)
|
||||
{
|
||||
_cancellationToken = cancellationToken;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 截图
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public ImageRegion Screenshot()
|
||||
{
|
||||
return TaskControl.CaptureToRectArea();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待
|
||||
/// </summary>
|
||||
/// <param name="milliseconds"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<BvPage> Wait(int milliseconds)
|
||||
{
|
||||
await TaskControl.Delay(milliseconds, _cancellationToken);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定位图片位置
|
||||
/// </summary>
|
||||
/// <param name="image"></param>
|
||||
/// <returns></returns>
|
||||
public BvLocator Locator(BvImage image)
|
||||
{
|
||||
return new BvLocator(image.ToRecognitionObject(), _cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 定位文本位置
|
||||
/// </summary>
|
||||
/// <param name="text"></param>
|
||||
/// <param name="rect"></param>
|
||||
/// <returns></returns>
|
||||
public BvLocator Locator(string text, Rect rect = default)
|
||||
{
|
||||
return Locator(new RecognitionObject
|
||||
{
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = rect,
|
||||
Text = text
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 定位 RecognitionObject 代表的位置
|
||||
/// </summary>
|
||||
/// <param name="ro"></param>
|
||||
/// <returns></returns>
|
||||
public BvLocator Locator(RecognitionObject ro)
|
||||
{
|
||||
return new BvLocator(ro, _cancellationToken);
|
||||
}
|
||||
|
||||
public BvLocator GetByText(string text = "", Rect rect = default)
|
||||
{
|
||||
return Locator(text, rect);
|
||||
}
|
||||
|
||||
public BvLocator GetByImage(BvImage image)
|
||||
{
|
||||
return Locator(image);
|
||||
}
|
||||
|
||||
|
||||
public List<Region> Ocr(Rect rect = default)
|
||||
{
|
||||
return Locator(string.Empty, rect).FindAll();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 1080P 分辨率下点击坐标
|
||||
/// </summary>
|
||||
/// <param name="x"></param>
|
||||
/// <param name="y"></param>
|
||||
public void Click(double x, double y)
|
||||
{
|
||||
GameCaptureRegion.GameRegion1080PPosClick(x, y);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
@@ -7,23 +6,14 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
|
||||
using BetterGenshinImpact.GameTask.AutoPick;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip;
|
||||
using BetterGenshinImpact.GameTask.AutoWood;
|
||||
using BetterGenshinImpact.GameTask.AutoMusicGame;
|
||||
using BetterGenshinImpact.GameTask.QuickTeleport;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using Fischless.GameCapture;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.AutoTrackPath;
|
||||
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
|
||||
using BetterGenshinImpact.GameTask.GetGridIcons;
|
||||
using BetterGenshinImpact.GameTask.AutoEat;
|
||||
using BetterGenshinImpact.GameTask.MapMask;
|
||||
using BetterGenshinImpact.GameTask.UseRedeemCode;
|
||||
using BetterGenshinImpact.GameTask.AutoCook;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
@@ -57,40 +47,19 @@ public partial class AllConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _triggerInterval = 50;
|
||||
|
||||
// /// <summary>
|
||||
// /// WGC使用位图缓存
|
||||
// /// 高帧率情况下,可能会导致卡顿
|
||||
// /// 云原神可能会出现黑屏
|
||||
// /// </summary>
|
||||
// [ObservableProperty]
|
||||
// private bool _wgcUseBitmapCache = true;
|
||||
|
||||
/// <summary>
|
||||
/// 自动修复Win11下BitBlt截图方式不可用的问题
|
||||
/// WGC使用位图缓存
|
||||
/// 高帧率情况下,可能会导致卡顿
|
||||
/// 云原神可能会出现黑屏
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoFixWin11BitBlt = true;
|
||||
private bool _wgcUseBitmapCache = true;
|
||||
|
||||
// /// <summary>
|
||||
// /// 推理使用的设备
|
||||
// /// </summary>
|
||||
// [ObservableProperty]
|
||||
// private string _inferenceDevice = "CPU";
|
||||
|
||||
[ObservableProperty]
|
||||
private List<ValueTuple<string, int, string, string>> _nextScheduledTask = [];
|
||||
|
||||
/// <summary>
|
||||
/// 连续执行任务时,从此任务开始执行
|
||||
/// </summary>
|
||||
[JsonIgnore]
|
||||
public string NextScriptGroupName { get; set; }= string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 一条龙选中使用的配置
|
||||
/// 推理使用的设备
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _selectedOneDragonFlowConfigName = string.Empty;
|
||||
private string _inferenceDevice = "CPU";
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
@@ -147,64 +116,16 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public AutoFightConfig AutoFightConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动乐曲配置 - 千音雅集
|
||||
/// </summary>
|
||||
public AutoMusicGameConfig AutoMusicGameConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动秘境配置
|
||||
/// </summary>
|
||||
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 自动秘境配置
|
||||
/// </summary>
|
||||
public AutoStygianOnslaughtConfig AutoStygianOnslaughtConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动分解圣遗物配置
|
||||
/// </summary>
|
||||
public AutoArtifactSalvageConfig AutoArtifactSalvageConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动吃药配置
|
||||
/// </summary>
|
||||
public AutoEatConfig AutoEatConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 地图遮罩
|
||||
/// </summary>
|
||||
public MapMaskConfig MapMaskConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 自动使用
|
||||
/// </summary>
|
||||
public AutoRedeemCodeConfig AutoRedeemCodeConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 截取物品图标配置
|
||||
/// </summary>
|
||||
public GetGridIconsConfig GetGridIconsConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 宏配置
|
||||
/// 脚本类配置
|
||||
/// </summary>
|
||||
public MacroConfig MacroConfig { get; set; } = new();
|
||||
|
||||
public RecordConfig RecordConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 脚本配置
|
||||
/// </summary>
|
||||
public ScriptConfig ScriptConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 地图追踪配置
|
||||
/// </summary>
|
||||
public PathingConditionConfig PathingConditionConfig { get; set; } = PathingConditionConfig.Default;
|
||||
|
||||
/// <summary>
|
||||
/// 快捷键配置
|
||||
/// </summary>
|
||||
@@ -215,32 +136,6 @@ public partial class AllConfig : ObservableObject
|
||||
/// </summary>
|
||||
public NotificationConfig NotificationConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 原神按键绑定配置
|
||||
/// </summary>
|
||||
public KeyBindingsConfig KeyBindingsConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 其他配置
|
||||
/// </summary>
|
||||
public OtherConfig OtherConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 传送相关配置
|
||||
/// </summary>
|
||||
public TpConfig TpConfig { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 开发者配置
|
||||
/// </summary>
|
||||
public DevConfig DevConfig { get; set; } = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 硬件加速设置
|
||||
/// </summary>
|
||||
public HardwareAccelerationConfig HardwareAccelerationConfig { get; set; } = new();
|
||||
|
||||
[JsonIgnore]
|
||||
public Action? OnAnyChangedAction { get; set; }
|
||||
|
||||
@@ -252,7 +147,7 @@ public partial class AllConfig : ObservableObject
|
||||
GenshinStartConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
|
||||
KeyBindingsConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
|
||||
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
@@ -263,17 +158,6 @@ public partial class AllConfig : ObservableObject
|
||||
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoStygianOnslaughtConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
TpConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
DevConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
|
||||
}
|
||||
|
||||
public void OnAnyPropertyChanged(object? sender, EventArgs args)
|
||||
@@ -286,4 +170,4 @@ public partial class AllConfig : ObservableObject
|
||||
{
|
||||
NotificationService.Instance().RefreshNotifiers();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,8 @@
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 主题类型配置
|
||||
/// </summary>
|
||||
public enum ThemeType
|
||||
{
|
||||
DarkNone,
|
||||
DarkMica,
|
||||
DarkAcrylic,
|
||||
LightNone,
|
||||
LightMica,
|
||||
LightAcrylic,
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩窗口配置
|
||||
/// </summary>
|
||||
@@ -36,48 +19,11 @@ public partial class CommonConfig : ObservableObject
|
||||
/// UID遮盖是否启用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _screenshotUidCoverEnabled = true;
|
||||
private bool _screenshotUidCoverEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 退出时最小化至托盘
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _exitToTray;
|
||||
|
||||
/// <summary>
|
||||
/// 当前主题类型(新版主题)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private ThemeType _currentThemeType = OsVersionHelper.IsWindows11_22523_OrGreater ? ThemeType.DarkMica : ThemeType.DarkNone;
|
||||
|
||||
/// <summary>
|
||||
/// 主题(旧版主题,兼容性保留)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private WindowBackdropType _currentBackdropType = WindowBackdropType.Mica;
|
||||
|
||||
/// <summary>
|
||||
/// 是否是第一次运行
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _isFirstRun = true;
|
||||
|
||||
/// <summary>
|
||||
/// 这个版本是否运行过
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _runForVersion = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 一个设备只运行一次的已运行设备ID列表
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private List<string> _onceHadRunDeviceIdList = new();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 当前看过的兑换码推送版本
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _redeemCodeFeedsUpdateVersion = "20251013";
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 脚本配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class DevConfig : ObservableObject
|
||||
{
|
||||
// 录制地图名称
|
||||
[ObservableProperty]
|
||||
private string _recordMapName = MapTypes.Teyvat.ToString();
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
@@ -9,11 +9,11 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
[Serializable]
|
||||
public partial class GenshinStartConfig : ObservableObject
|
||||
{
|
||||
// /// <summary>
|
||||
// /// 自动点击月卡
|
||||
// /// </summary>
|
||||
// [ObservableProperty]
|
||||
// private bool _autoClickBlessingOfTheWelkinMoonEnabled;
|
||||
/// <summary>
|
||||
/// 自动点击月卡
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoClickBlessingOfTheWelkinMoonEnabled;
|
||||
|
||||
/// <summary>
|
||||
/// 自动进入游戏(开门)
|
||||
@@ -38,13 +38,4 @@ public partial class GenshinStartConfig : ObservableObject
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _linkedStartEnabled = true;
|
||||
|
||||
/// <summary>
|
||||
/// 使用Starward同步记录时间
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _recordGameTimeEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _startGameWithCmd = false;
|
||||
}
|
||||
@@ -1,40 +1,19 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Semver;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
public class Global
|
||||
{
|
||||
public static string Version { get; } = Assembly.GetEntryAssembly()?.
|
||||
GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.
|
||||
InformationalVersion!;
|
||||
public static string Version { get; } = "0.30.3";
|
||||
|
||||
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
|
||||
|
||||
public static readonly JsonSerializerOptions ManifestJsonOptions = new()
|
||||
{
|
||||
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||
WriteIndented = true,
|
||||
AllowTrailingCommas = true,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
};
|
||||
|
||||
public static string Absolute(string relativePath)
|
||||
{
|
||||
return Path.Combine(StartUpPath, relativePath);
|
||||
}
|
||||
|
||||
public static string ScriptPath()
|
||||
{
|
||||
return Absolute("User\\JsScript");
|
||||
}
|
||||
|
||||
public static string? ReadAllTextIfExist(string relativePath)
|
||||
{
|
||||
var path = Absolute(relativePath);
|
||||
@@ -62,10 +41,10 @@ public class Global
|
||||
{
|
||||
try
|
||||
{
|
||||
var oldVersionX = SemVersion.Parse(oldVersion);
|
||||
var currentVersionX = SemVersion.Parse(currentVersion);
|
||||
Version oldVersionX = new(oldVersion);
|
||||
Version currentVersionX = new(currentVersion);
|
||||
|
||||
if (currentVersionX.CompareSortOrderTo(oldVersionX) > 0)
|
||||
if (currentVersionX > oldVersionX)
|
||||
// 需要更新
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class HardwareAccelerationConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 推理使用的设备。默认CPU
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
|
||||
|
||||
/// <summary>
|
||||
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _cpuOcr = false;
|
||||
|
||||
#region 一般GPU加速设置
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定gpu设备,默认为0(使用默认设备)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _gpuDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 附加path,用;分割。默认为空。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _additionalPath = "";
|
||||
|
||||
/// <summary>
|
||||
/// 是否输出优化后的模型文件到缓存。注意:在不支持的执行器上使用会导致异常。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _optimizedModel = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region cuda设置
|
||||
|
||||
/// <summary>
|
||||
/// 强制指定cuda设备,默认为0(使用默认设备)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _cudaDevice = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 自动附加cuda的path。一般情况下用这个就足够了。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _autoAppendCudaPath = false;
|
||||
|
||||
#endregion
|
||||
|
||||
#region TensorRT缓存设置
|
||||
|
||||
/// <summary>
|
||||
/// 启用TensorRT缓存。默认开启。不开的话使用TensorRT每次加载模型会卡爆。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableTensorRtCache = true;
|
||||
|
||||
/// <summary>
|
||||
/// 嵌入式引擎缓存。将引擎缓存嵌入到模型中。默认开启。关闭它可能会提高性能(如果不爆炸的话)。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _embedTensorRtCache = true;
|
||||
|
||||
#endregion
|
||||
|
||||
#region OpenVINO设置
|
||||
/// <summary>
|
||||
/// OpenVino 设备参数。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _openVinoDevice = "AUTO:GPU,CPU";
|
||||
|
||||
/// <summary>
|
||||
/// 启用 OpenVINO 缓存。默认关闭。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _enableOpenVinoCache = false;
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -148,13 +148,6 @@ public partial class HotKeyConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoMusicGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 活动音游开始/停止
|
||||
[ObservableProperty]
|
||||
private string _autoFishingGameHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _autoFishingGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 自动寻路
|
||||
[ObservableProperty]
|
||||
@@ -169,72 +162,4 @@ public partial class HotKeyConfig : ObservableObject
|
||||
|
||||
[ObservableProperty]
|
||||
private string _test1HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 测试2
|
||||
[ObservableProperty]
|
||||
private string _test2Hotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _test2HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 路径记录开始
|
||||
[ObservableProperty]
|
||||
private string _recBigMapPosHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _recBigMapPosHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 路径记录开始
|
||||
[ObservableProperty]
|
||||
private string _pathRecorderHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _pathRecorderHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 添加路径记录点
|
||||
[ObservableProperty]
|
||||
private string _addWaypointHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _addWaypointHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 路径执行
|
||||
[ObservableProperty]
|
||||
private string _executePathHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _executePathHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 日志与状态窗口展示
|
||||
[ObservableProperty]
|
||||
private string _logBoxDisplayHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _logBoxDisplayHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 键鼠录制/停止
|
||||
[ObservableProperty]
|
||||
private string _keyMouseMacroRecordHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _keyMouseMacroRecordHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
// 暂停
|
||||
[ObservableProperty]
|
||||
private string _suspendHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _suspendHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
// 停止任意独立任务
|
||||
[ObservableProperty]
|
||||
private string _cancelTaskHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _cancelTaskHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
|
||||
// 停止任意独立任务
|
||||
[ObservableProperty]
|
||||
private string _onedragonHotkey = "";
|
||||
|
||||
[ObservableProperty]
|
||||
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
|
||||
}
|
||||
@@ -1,970 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Windows.Forms;
|
||||
using System.Windows.Input;
|
||||
using Windows.Networking.PushNotifications;
|
||||
using static Vanara.PInvoke.User32;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 原神按键绑定配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class KeyBindingsConfig:ObservableObject
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用全局按键映射
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _globalKeyMappingEnabled = false;
|
||||
|
||||
#region Actions(操作)
|
||||
|
||||
/// <summary>
|
||||
/// 向前移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _moveForward = KeyId.W;
|
||||
|
||||
/// <summary>
|
||||
/// 向后移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _moveBackward = KeyId.S;
|
||||
|
||||
/// <summary>
|
||||
/// 向左移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _moveLeft = KeyId.A;
|
||||
|
||||
/// <summary>
|
||||
/// 向右移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _moveRight = KeyId.D;
|
||||
|
||||
/// <summary>
|
||||
/// 切换走/跑;特定操作模式下向下移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchToWalkOrRun = KeyId.LeftCtrl;
|
||||
|
||||
/// <summary>
|
||||
/// 普通攻击
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _normalAttack = KeyId.MouseLeftButton;
|
||||
|
||||
/// <summary>
|
||||
/// 元素战技
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _elementalSkill = KeyId.E;
|
||||
|
||||
/// <summary>
|
||||
/// 元素爆发
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _elementalBurst = KeyId.Q;
|
||||
|
||||
/// <summary>
|
||||
/// 冲刺(键盘)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _sprintKeyboard = KeyId.LeftShift;
|
||||
|
||||
/// <summary>
|
||||
/// 冲刺(鼠标)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _sprintMouse = KeyId.MouseRightButton;
|
||||
|
||||
/// <summary>
|
||||
/// 切换瞄准模式
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchAimingMode = KeyId.R;
|
||||
|
||||
/// <summary>
|
||||
/// 跳跃;特定操作模式下向上移动
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _jump = KeyId.Space;
|
||||
|
||||
/// <summary>
|
||||
/// 落下
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _drop = KeyId.X;
|
||||
|
||||
/// <summary>
|
||||
/// 拾取/交互(自动拾取由AutoPick模块管理)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _pickUpOrInteract = KeyId.F;
|
||||
|
||||
/// <summary>
|
||||
/// 快捷使用小道具
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _quickUseGadget = KeyId.Z;
|
||||
|
||||
/// <summary>
|
||||
/// 特定玩法内交互操作
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _interactionInSomeMode = KeyId.T;
|
||||
|
||||
/// <summary>
|
||||
/// 开启任务追踪
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _questNavigation = KeyId.V;
|
||||
|
||||
/// <summary>
|
||||
/// 中断挑战
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _abandonChallenge = KeyId.P;
|
||||
|
||||
/// <summary>
|
||||
/// 切换小队角色1
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchMember1 = KeyId.D1;
|
||||
|
||||
/// <summary>
|
||||
/// 切换小队角色2
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchMember2 = KeyId.D2;
|
||||
|
||||
/// <summary>
|
||||
/// 切换小队角色3
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchMember3 = KeyId.D3;
|
||||
|
||||
/// <summary>
|
||||
/// 切换小队角色4
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchMember4 = KeyId.D4;
|
||||
|
||||
/// <summary>
|
||||
/// 切换小队角色5
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _switchMember5 = KeyId.D5;
|
||||
|
||||
/// <summary>
|
||||
/// 呼出快捷轮盘
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _shortcutWheel = KeyId.Tab;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Menus(菜单)
|
||||
|
||||
/// <summary>
|
||||
/// 打开背包
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openInventory = KeyId.B;
|
||||
|
||||
/// <summary>
|
||||
/// 打开角色界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openCharacterScreen = KeyId.C;
|
||||
|
||||
/// <summary>
|
||||
/// 打开地图
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openMap = KeyId.M;
|
||||
|
||||
/// <summary>
|
||||
/// 打开派蒙界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openPaimonMenu = KeyId.Escape;
|
||||
|
||||
/// <summary>
|
||||
/// 打开冒险之证界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openAdventurerHandbook = KeyId.F1;
|
||||
|
||||
/// <summary>
|
||||
/// 打开多人游戏界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openCoOpScreen = KeyId.F2;
|
||||
|
||||
/// <summary>
|
||||
/// 打开祈愿界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openWishScreen = KeyId.F3;
|
||||
|
||||
/// <summary>
|
||||
/// 打开纪行界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openBattlePassScreen = KeyId.F4;
|
||||
|
||||
/// <summary>
|
||||
/// 打开活动面板
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openTheEventsMenu = KeyId.F5;
|
||||
|
||||
/// <summary>
|
||||
/// 打开玩法系统界面(尘歌壶内猫尾酒馆内)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openTheSettingsMenu = KeyId.F6;
|
||||
|
||||
/// <summary>
|
||||
/// 打开摆设界面(尘歌壶内)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openTheFurnishingScreen = KeyId.F7;
|
||||
|
||||
/// <summary>
|
||||
/// 打开星之归还(条件符合期间生效)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openStellarReunion = KeyId.F8;
|
||||
|
||||
/// <summary>
|
||||
/// 开关任务菜单
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openQuestMenu = KeyId.J;
|
||||
|
||||
/// <summary>
|
||||
/// 打开通知详情
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openNotificationDetails = KeyId.Y;
|
||||
|
||||
/// <summary>
|
||||
/// 打开聊天界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openChatScreen = KeyId.Enter;
|
||||
|
||||
/// <summary>
|
||||
/// 打开特殊环境说明
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openSpecialEnvironmentInformation = KeyId.U;
|
||||
|
||||
/// <summary>
|
||||
/// 查看教程详情
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _checkTutorialDetails = KeyId.G;
|
||||
|
||||
/// <summary>
|
||||
/// 长按打开元素视野
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _elementalSight = KeyId.MouseMiddleButton;
|
||||
|
||||
/// <summary>
|
||||
/// 呼出鼠标
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _showCursor = KeyId.LeftAlt;
|
||||
|
||||
/// <summary>
|
||||
/// 打开队伍配置界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openPartySetupScreen = KeyId.L;
|
||||
|
||||
/// <summary>
|
||||
/// 打开好友界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _openFriendsScreen = KeyId.O;
|
||||
|
||||
/// <summary>
|
||||
/// 隐藏主界面
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private KeyId _hideUI = KeyId.Slash;
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
|
||||
public static class KeyIdConverter
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 将KeyId转换为字符串(可在后续支持多语言),按键名称的显示尽量与原神UI一致
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static string ToName(this KeyId value)
|
||||
{
|
||||
return ToChineseName(value);
|
||||
}
|
||||
|
||||
private static string ToChineseName(KeyId value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
// 需要单独翻译的按键
|
||||
KeyId.None => "<未指定>",
|
||||
KeyId.Unknown => "<未知>",
|
||||
KeyId.MouseLeftButton => "鼠标左键",
|
||||
KeyId.MouseRightButton => "鼠标右键",
|
||||
KeyId.MouseMiddleButton => "鼠标中键",
|
||||
KeyId.MouseSideButton1 => "鼠标侧键1",
|
||||
KeyId.MouseSideButton2 => "鼠标侧键2",
|
||||
KeyId.Apps => "菜单键",
|
||||
// 无需单独翻译的部分
|
||||
_ => EnglishKeyNameToChinese(value),
|
||||
};
|
||||
}
|
||||
|
||||
private static string EnglishKeyNameToChinese(KeyId value)
|
||||
{
|
||||
var engName = ToEnglishName(value);
|
||||
if (engName.StartsWith("Left ") || engName.StartsWith("Right "))
|
||||
{
|
||||
return engName.Replace("Left ", "左").Replace("Right ", "右");
|
||||
}
|
||||
return engName;
|
||||
}
|
||||
|
||||
private static string ToEnglishName(KeyId value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
// 需要转换的部分
|
||||
KeyId.None => "<None>",
|
||||
KeyId.Unknown => "<Unknown>",
|
||||
KeyId.MouseLeftButton => "Mouse LButton",
|
||||
KeyId.MouseRightButton => "Mouse RButton",
|
||||
KeyId.MouseMiddleButton => "Mouse MButton",
|
||||
KeyId.MouseSideButton1 => "Mouse XButton1",
|
||||
KeyId.MouseSideButton2 => "Mouse XButton2",
|
||||
KeyId.Escape => "Esc",
|
||||
KeyId.PageUp => "Page Up",
|
||||
KeyId.PageDown => "Page Down",
|
||||
KeyId.CapsLock => "Caps Lock",
|
||||
KeyId.ScrollLock => "Scroll Lock",
|
||||
KeyId.LeftShift => "Left Shift",
|
||||
KeyId.RightShift => "Right Shift",
|
||||
KeyId.LeftCtrl => "Left Ctrl",
|
||||
KeyId.RightCtrl => "Right Ctrl",
|
||||
KeyId.LeftAlt => "Left Alt",
|
||||
KeyId.RightAlt => "Right Alt",
|
||||
KeyId.LeftWin => "Left Win",
|
||||
KeyId.RightWin => "Right Win",
|
||||
KeyId.Apps => "Menu",
|
||||
KeyId.Left => "←",
|
||||
KeyId.Up => "↑",
|
||||
KeyId.Right => "→",
|
||||
KeyId.Down => "↓",
|
||||
KeyId.D0 => "0",
|
||||
KeyId.D1 => "1",
|
||||
KeyId.D2 => "2",
|
||||
KeyId.D3 => "3",
|
||||
KeyId.D4 => "4",
|
||||
KeyId.D5 => "5",
|
||||
KeyId.D6 => "6",
|
||||
KeyId.D7 => "7",
|
||||
KeyId.D8 => "8",
|
||||
KeyId.D9 => "9",
|
||||
KeyId.Apostrophe => "'",
|
||||
KeyId.Comma => ",",
|
||||
KeyId.Minus => "-",
|
||||
KeyId.Equal => "=",
|
||||
KeyId.Period => ".",
|
||||
KeyId.Slash => "/",
|
||||
KeyId.Backslash => @"\",
|
||||
KeyId.Semicolon => ";",
|
||||
KeyId.LeftSquareBracket => "[",
|
||||
KeyId.RightSquareBracket => "]",
|
||||
KeyId.Tilde => "`",
|
||||
KeyId.NumLock => "Num Lock",
|
||||
KeyId.NumPad0 => "Num 0",
|
||||
KeyId.NumPad1 => "Num 1",
|
||||
KeyId.NumPad2 => "Num 2",
|
||||
KeyId.NumPad3 => "Num 3",
|
||||
KeyId.NumPad4 => "Num 4",
|
||||
KeyId.NumPad5 => "Num 5",
|
||||
KeyId.NumPad6 => "Num 6",
|
||||
KeyId.NumPad7 => "Num 7",
|
||||
KeyId.NumPad8 => "Num 8",
|
||||
KeyId.NumPad9 => "Num 9",
|
||||
KeyId.Decimal => "Num .",
|
||||
KeyId.Divide => "Num /",
|
||||
KeyId.Multiply => "Num *",
|
||||
KeyId.Subtract => "Num -",
|
||||
KeyId.Add => "Num +",
|
||||
KeyId.NumEnter => "Num Enter",
|
||||
// 默认使用枚举名
|
||||
_ => value.ToString(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将KeyId转换为VK
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static VK ToVK(this KeyId value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
// 这两个值在VK中没有,抛异常
|
||||
KeyId.None => throw new ArgumentOutOfRangeException(nameof(value), "未指定按键,无法转换为VK。"),
|
||||
KeyId.Unknown => throw new ArgumentOutOfRangeException(nameof(value), "未知按键,无法转换为VK。"),
|
||||
// 剩下的值相同,直接转
|
||||
_ => (VK)value,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将KeyId转换为System.Windows.Input.Key
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static Key ToInputKey(this KeyId value)
|
||||
{
|
||||
// 部分按键名称相同,使用名称转换
|
||||
try
|
||||
{
|
||||
return Enum.Parse<Key>(value.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 其他键使用查表法转换
|
||||
return value switch
|
||||
{
|
||||
KeyId.LeftWin => Key.LWin,
|
||||
KeyId.RightWin => Key.RWin,
|
||||
KeyId.Apostrophe => Key.Oem7,
|
||||
KeyId.Comma => Key.OemComma,
|
||||
KeyId.Minus => Key.OemMinus,
|
||||
KeyId.Equal => Key.OemPlus,
|
||||
KeyId.Period => Key.OemPeriod,
|
||||
KeyId.Slash => Key.Oem2,
|
||||
KeyId.Semicolon => Key.Oem1,
|
||||
KeyId.LeftSquareBracket => Key.Oem4,
|
||||
KeyId.Backslash => Key.Oem5,
|
||||
KeyId.RightSquareBracket => Key.Oem6,
|
||||
KeyId.Tilde => Key.Oem3,
|
||||
KeyId.Enter => Key.Enter,
|
||||
KeyId.ScrollLock => Key.Scroll,
|
||||
KeyId.PageUp => Key.Prior,
|
||||
KeyId.PageDown => Key.Next,
|
||||
KeyId.Backspace => Key.Back,
|
||||
KeyId.CapsLock => Key.Capital,
|
||||
// None、Unknown和鼠标按键抛异常
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(value)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将KeyId转换为MouseButton
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentOutOfRangeException"></exception>
|
||||
public static MouseButton ToMouseButton(this KeyId value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
KeyId.MouseLeftButton => MouseButton.Left,
|
||||
KeyId.MouseRightButton => MouseButton.Right,
|
||||
KeyId.MouseMiddleButton => MouseButton.Middle,
|
||||
KeyId.MouseSideButton1 => MouseButton.XButton1,
|
||||
KeyId.MouseSideButton2 => MouseButton.XButton2,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(value), "键盘按键请使用ToInputKey方法"),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// [实验] 将KeyId转换为WinForm中的Keys(用于兼容按键连发功能)
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static Keys ToWinFormKeys(this KeyId value)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Enum.Parse<Keys>(value.ToInputKey().ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将VK转换为KeyId
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static KeyId FromVK(VK value)
|
||||
{
|
||||
// 尝试通过VK的值获取KeyId的枚举名。若成功,表示对应的VK在KeyId支持的范围内,直接转换;否则返回Unknown
|
||||
return string.IsNullOrEmpty(Enum.GetName(typeof(KeyId), value)) ? KeyId.Unknown : (KeyId)value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将System.Windows.Input.Key转换为KeyId
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static KeyId FromInputKey(Key value)
|
||||
{
|
||||
// 部分按键名称相同,使用名称转换
|
||||
try
|
||||
{
|
||||
return Enum.Parse<KeyId>(value.ToString());
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 其他键使用查表法转换
|
||||
return value switch
|
||||
{
|
||||
Key.LWin => KeyId.LeftWin,
|
||||
Key.RWin => KeyId.RightWin,
|
||||
Key.Oem7 => KeyId.Apostrophe,
|
||||
Key.OemComma => KeyId.Comma,
|
||||
Key.OemMinus => KeyId.Minus,
|
||||
Key.OemPlus => KeyId.Equal,
|
||||
Key.OemPeriod => KeyId.Period,
|
||||
Key.Oem2 => KeyId.Slash,
|
||||
Key.Oem1 => KeyId.Semicolon,
|
||||
Key.Oem4 => KeyId.LeftSquareBracket,
|
||||
Key.Oem5 => KeyId.Backslash,
|
||||
Key.Oem6 => KeyId.RightSquareBracket,
|
||||
Key.Oem3 => KeyId.Tilde,
|
||||
Key.Enter => KeyId.Enter,
|
||||
Key.Scroll => KeyId.ScrollLock,
|
||||
Key.Prior => KeyId.PageUp,
|
||||
Key.Next => KeyId.PageDown,
|
||||
Key.Back => KeyId.Backspace,
|
||||
Key.Capital => KeyId.CapsLock,
|
||||
// 支持列表外的值返回Unknown
|
||||
_ => KeyId.Unknown,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将MouseButton转换为KeyId
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static KeyId FromMouseButton(MouseButton value)
|
||||
{
|
||||
return value switch
|
||||
{
|
||||
MouseButton.Left => KeyId.MouseLeftButton,
|
||||
MouseButton.Right => KeyId.MouseRightButton,
|
||||
MouseButton.Middle => KeyId.MouseMiddleButton,
|
||||
MouseButton.XButton1 => KeyId.MouseSideButton1,
|
||||
MouseButton.XButton2 => KeyId.MouseSideButton2,
|
||||
_ => KeyId.Unknown,
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于与VK/Windows.Input.Key解耦,值与VK对应,但是仅包含美式键盘(104键,不包括媒体控制等)和鼠标中的按键
|
||||
/// </summary>
|
||||
public enum KeyId
|
||||
{
|
||||
/// <summary>无</summary>
|
||||
None = 0x00,
|
||||
|
||||
/// <summary>未知按键</summary>
|
||||
Unknown = 0xFF,
|
||||
|
||||
#region 鼠标按键
|
||||
|
||||
/// <summary>鼠标左键</summary>
|
||||
MouseLeftButton = 0x01,
|
||||
|
||||
/// <summary>鼠标右键</summary>
|
||||
MouseRightButton = 0x02,
|
||||
|
||||
/// <summary>鼠标中键(滚轮)</summary>
|
||||
MouseMiddleButton = 0x04,
|
||||
|
||||
/// <summary>鼠标侧键1(后退)</summary>
|
||||
MouseSideButton1 = 0x05,
|
||||
|
||||
/// <summary>鼠标侧键2(前进)</summary>
|
||||
MouseSideButton2 = 0x06,
|
||||
|
||||
#endregion
|
||||
|
||||
#region F键区
|
||||
|
||||
/// <summary>F1</summary>
|
||||
F1 = 0x70,
|
||||
|
||||
/// <summary>F2</summary>
|
||||
F2 = 0x71,
|
||||
|
||||
/// <summary>F3</summary>
|
||||
F3 = 0x72,
|
||||
|
||||
/// <summary>F4</summary>
|
||||
F4 = 0x73,
|
||||
|
||||
/// <summary>F5</summary>
|
||||
F5 = 0x74,
|
||||
|
||||
/// <summary>F6</summary>
|
||||
F6 = 0x75,
|
||||
|
||||
/// <summary>F7</summary>
|
||||
F7 = 0x76,
|
||||
|
||||
/// <summary>F8</summary>
|
||||
F8 = 0x77,
|
||||
|
||||
/// <summary>F9</summary>
|
||||
F9 = 0x78,
|
||||
|
||||
/// <summary>F10</summary>
|
||||
F10 = 0x79,
|
||||
|
||||
/// <summary>F11</summary>
|
||||
F11 = 0x7A,
|
||||
|
||||
/// <summary>F12</summary>
|
||||
F12 = 0x7B,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 控制&功能键
|
||||
|
||||
/// <summary>Esc</summary>
|
||||
Escape = 0x1B,
|
||||
|
||||
/// <summary>PrintScreen</summary>
|
||||
PrintScreen = 0x2C,
|
||||
|
||||
/// <summary>ScrollLock</summary>
|
||||
ScrollLock = 0x91,
|
||||
|
||||
/// <summary>Pause</summary>
|
||||
Pause = 0x13,
|
||||
|
||||
/// <summary>Insert</summary>
|
||||
Insert = 0x2D,
|
||||
|
||||
/// <summary>Delete</summary>
|
||||
Delete = 0x2E,
|
||||
|
||||
/// <summary>Home</summary>
|
||||
Home = 0x24,
|
||||
|
||||
/// <summary>End</summary>
|
||||
End = 0x23,
|
||||
|
||||
/// <summary>Page Up</summary>
|
||||
PageUp = 0x21,
|
||||
|
||||
/// <summary>Page Down</summary>
|
||||
PageDown = 0x22,
|
||||
|
||||
/// <summary>Backspace退格</summary>
|
||||
Backspace = 0x08,
|
||||
|
||||
/// <summary>Tab</summary>
|
||||
Tab = 0x09,
|
||||
|
||||
/// <summary>Caps Lock大写锁定</summary>
|
||||
CapsLock = 0x14,
|
||||
|
||||
/// <summary>Enter回车</summary>
|
||||
Enter = 0x0D,
|
||||
|
||||
///// <summary>Shift</summary>
|
||||
//Shift = 0x10,
|
||||
|
||||
/// <summary>左Shift</summary>
|
||||
LeftShift = 0xA0,
|
||||
|
||||
/// <summary>右Shift</summary>
|
||||
RightShift = 0xA1,
|
||||
|
||||
///// <summary>Ctrl</summary>
|
||||
//Ctrl = 0x11,
|
||||
|
||||
/// <summary>左Ctrl</summary>
|
||||
LeftCtrl = 0xA2,
|
||||
|
||||
/// <summary>右Ctrl</summary>
|
||||
RightCtrl = 0xA3,
|
||||
|
||||
///// <summary>Alt</summary>
|
||||
//Alt = 0x12,
|
||||
|
||||
/// <summary>左Alt</summary>
|
||||
LeftAlt = 0xA4,
|
||||
|
||||
/// <summary>右Alt</summary>
|
||||
RightAlt = 0xA5,
|
||||
|
||||
/// <summary>左Win键 (Microsoft Natural Keyboard)</summary>
|
||||
LeftWin = 0x5B,
|
||||
|
||||
/// <summary>右Win键 (Microsoft Natural Keyboard)</summary>
|
||||
RightWin = 0x5C,
|
||||
|
||||
/// <summary>菜单键 (Microsoft Natural Keyboard)</summary>
|
||||
Apps = 0x5D,
|
||||
|
||||
/// <summary>Space空格键</summary>
|
||||
Space = 0x20,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 方向键
|
||||
|
||||
/// <summary>方向键 ←</summary>
|
||||
Left = 0x25,
|
||||
|
||||
/// <summary>方向键 ↑</summary>
|
||||
Up = 0x26,
|
||||
|
||||
/// <summary>方向键 →</summary>
|
||||
Right = 0x27,
|
||||
|
||||
/// <summary>方向键 ↓</summary>
|
||||
Down = 0x28,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 字母区 - 字母
|
||||
|
||||
/// <summary>A</summary>
|
||||
A = 0x41,
|
||||
|
||||
/// <summary>B</summary>
|
||||
B = 0x42,
|
||||
|
||||
/// <summary>C</summary>
|
||||
C = 0x43,
|
||||
|
||||
/// <summary>D</summary>
|
||||
D = 0x44,
|
||||
|
||||
/// <summary>E</summary>
|
||||
E = 0x45,
|
||||
|
||||
/// <summary>F</summary>
|
||||
F = 0x46,
|
||||
|
||||
/// <summary>G</summary>
|
||||
G = 0x47,
|
||||
|
||||
/// <summary>H</summary>
|
||||
H = 0x48,
|
||||
|
||||
/// <summary>I</summary>
|
||||
I = 0x49,
|
||||
|
||||
/// <summary>J</summary>
|
||||
J = 0x4A,
|
||||
|
||||
/// <summary>K</summary>
|
||||
K = 0x4B,
|
||||
|
||||
/// <summary>L</summary>
|
||||
L = 0x4C,
|
||||
|
||||
/// <summary>M</summary>
|
||||
M = 0x4D,
|
||||
|
||||
/// <summary>N</summary>
|
||||
N = 0x4E,
|
||||
|
||||
/// <summary>O</summary>
|
||||
O = 0x4F,
|
||||
|
||||
/// <summary>P</summary>
|
||||
P = 0x50,
|
||||
|
||||
/// <summary>Q</summary>
|
||||
Q = 0x51,
|
||||
|
||||
/// <summary>R</summary>
|
||||
R = 0x52,
|
||||
|
||||
/// <summary>S</summary>
|
||||
S = 0x53,
|
||||
|
||||
/// <summary>T</summary>
|
||||
T = 0x54,
|
||||
|
||||
/// <summary>U</summary>
|
||||
U = 0x55,
|
||||
|
||||
/// <summary>V</summary>
|
||||
V = 0x56,
|
||||
|
||||
/// <summary>W</summary>
|
||||
W = 0x57,
|
||||
|
||||
/// <summary>X</summary>
|
||||
X = 0x58,
|
||||
|
||||
/// <summary>Y</summary>
|
||||
Y = 0x59,
|
||||
|
||||
/// <summary>Z</summary>
|
||||
Z = 0x5A,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 字母区 - 数字
|
||||
|
||||
/// <summary>0</summary>
|
||||
D0 = 0x30,
|
||||
|
||||
/// <summary>1</summary>
|
||||
D1 = 0x31,
|
||||
|
||||
/// <summary>2</summary>
|
||||
D2 = 0x32,
|
||||
|
||||
/// <summary>3</summary>
|
||||
D3 = 0x33,
|
||||
|
||||
/// <summary>4</summary>
|
||||
D4 = 0x34,
|
||||
|
||||
/// <summary>5</summary>
|
||||
D5 = 0x35,
|
||||
|
||||
/// <summary>6</summary>
|
||||
D6 = 0x36,
|
||||
|
||||
/// <summary>7</summary>
|
||||
D7 = 0x37,
|
||||
|
||||
/// <summary>8</summary>
|
||||
D8 = 0x38,
|
||||
|
||||
/// <summary>9</summary>
|
||||
D9 = 0x39,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 字母区 - 符号
|
||||
|
||||
/// <summary>引号 '</summary>
|
||||
Apostrophe = 0xDE,
|
||||
|
||||
/// <summary>逗号 ,</summary>
|
||||
Comma = 0xBC,
|
||||
|
||||
/// <summary>连接符 -</summary>
|
||||
Minus = 0xBD,
|
||||
|
||||
/// <summary>等于号 =</summary>
|
||||
Equal = 0xBB,
|
||||
|
||||
/// <summary>句号 .</summary>
|
||||
Period = 0xBE,
|
||||
|
||||
/// <summary>斜杠 /</summary>
|
||||
Slash = 0xBF,
|
||||
|
||||
/// <summary>反斜杠 \</summary>
|
||||
Backslash = 0xE2,
|
||||
|
||||
/// <summary>分号 ;</summary>
|
||||
Semicolon = 0xBA,
|
||||
|
||||
/// <summary>左方括号 [</summary>
|
||||
LeftSquareBracket = 0xDB,
|
||||
|
||||
/// <summary>右方括号 ]</summary>
|
||||
RightSquareBracket = 0xDD,
|
||||
|
||||
/// <summary>波浪号 `</summary>
|
||||
Tilde = 0xC0,
|
||||
|
||||
#endregion
|
||||
|
||||
#region 小键盘区
|
||||
|
||||
/// <summary>Num Lock</summary>
|
||||
NumLock = 0x90,
|
||||
|
||||
/// <summary>Num 0</summary>
|
||||
NumPad0 = 0x60,
|
||||
|
||||
/// <summary>Num 1</summary>
|
||||
NumPad1 = 0x61,
|
||||
|
||||
/// <summary>Num 2</summary>
|
||||
NumPad2 = 0x62,
|
||||
|
||||
/// <summary>Num 3</summary>
|
||||
NumPad3 = 0x63,
|
||||
|
||||
/// <summary>Num 4</summary>
|
||||
NumPad4 = 0x64,
|
||||
|
||||
/// <summary>Num 5</summary>
|
||||
NumPad5 = 0x65,
|
||||
|
||||
/// <summary>Num 6</summary>
|
||||
NumPad6 = 0x66,
|
||||
|
||||
/// <summary>Num 7</summary>
|
||||
NumPad7 = 0x67,
|
||||
|
||||
/// <summary>Num 8</summary>
|
||||
NumPad8 = 0x68,
|
||||
|
||||
/// <summary>Num 9</summary>
|
||||
NumPad9 = 0x69,
|
||||
|
||||
/// <summary>Num .</summary>
|
||||
Decimal = 0x6E,
|
||||
|
||||
/// <summary>Num /</summary>
|
||||
Divide = 0x6F,
|
||||
|
||||
/// <summary>Num *</summary>
|
||||
Multiply = 0x6A,
|
||||
|
||||
/// <summary>Num -</summary>
|
||||
Subtract = 0x6D,
|
||||
|
||||
/// <summary>Num +</summary>
|
||||
Add = 0x6B,
|
||||
|
||||
/// <summary>Num Enter</summary>
|
||||
NumEnter = 0x0E,
|
||||
|
||||
#endregion
|
||||
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public partial class MacroConfig : ObservableObject
|
||||
/// 转圈圈时间间隔
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _runaroundInterval = 10;
|
||||
private int _runaroundInterval;
|
||||
|
||||
/// <summary>
|
||||
/// 转圈圈鼠标右移长度
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using Point = System.Windows.Point;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
@@ -10,6 +11,12 @@ namespace BetterGenshinImpact.Core.Config;
|
||||
[Serializable]
|
||||
public partial class MaskWindowConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 控件是否锁定(拖拽移动等)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _controlLocked = true;
|
||||
|
||||
/// <summary>
|
||||
/// 方位提示是否启用
|
||||
/// </summary>
|
||||
@@ -22,6 +29,12 @@ public partial class MaskWindowConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private bool _displayRecognitionResultsOnMask = true;
|
||||
|
||||
/// <summary>
|
||||
/// 日志窗口位置与大小
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private Rect _logBoxLocation;
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用遮罩窗口
|
||||
/// </summary>
|
||||
@@ -54,52 +67,15 @@ public partial class MaskWindowConfig : ObservableObject
|
||||
/// <summary>
|
||||
/// 1080p下UID遮盖的位置与大小
|
||||
/// </summary>
|
||||
[NonSerialized]
|
||||
public static readonly Rect UidCoverRightBottomRect = new(1920 - 1685, 1080 - 1053, 178, 22);
|
||||
public Rect UidCoverRect { get; set; } = new(1690, 1052, 173, 22);
|
||||
|
||||
/// <summary>
|
||||
/// 显示FPS
|
||||
/// 1080p下UID遮盖的位置与大小
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _showFps = false;
|
||||
public Rect UidCoverRightBottomRect { get; set; } = new(1920 - 1690, 1080 - 1052, 173, 22);
|
||||
|
||||
/// <summary>
|
||||
/// 作为原神子窗体
|
||||
/// 有些bug没解决
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _useSubform = false;
|
||||
|
||||
/// <summary>
|
||||
/// 遮罩文本透明度 (0.0-1.0)
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _textOpacity = 1.0;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _overlayLayoutEditEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxTopRatio = 832.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxWidthRatio = 477.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _logTextBoxHeightRatio = 188.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListLeftRatio = 20.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListTopRatio = 807.0 / 1080;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListWidthRatio = 477.0 / 1920;
|
||||
|
||||
[ObservableProperty]
|
||||
private double _statusListHeightRatio = 24.0 / 1080;
|
||||
public Point EastPoint { get; set; } = new(274, 109);
|
||||
public Point SouthPoint { get; set; } = new(150, 233);
|
||||
public Point WestPoint { get; set; } = new(32, 109);
|
||||
public Point NorthPoint { get; set; } = new(150, -9);
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class OneDragonFlowConfig : ObservableObject
|
||||
{
|
||||
// 配置名
|
||||
[ObservableProperty]
|
||||
private string _name = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 所有任务的开关状态
|
||||
/// </summary>
|
||||
public Dictionary<string, bool> TaskEnabledList { get; set; } = new();
|
||||
|
||||
// 合成树脂的国家
|
||||
[ObservableProperty]
|
||||
private string _craftingBenchCountry = "枫丹";
|
||||
|
||||
// 冒险者协会的国家
|
||||
[ObservableProperty]
|
||||
private string _adventurersGuildCountry = "枫丹";
|
||||
|
||||
// 自动战斗配置的队伍名称
|
||||
[ObservableProperty]
|
||||
private string _partyName = string.Empty;
|
||||
|
||||
// 自动战斗配置的策略名称
|
||||
[ObservableProperty]
|
||||
private string _domainName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _weeklyDomainEnabled = false;
|
||||
|
||||
// 领取每日奖励的好感队伍名称
|
||||
[ObservableProperty]
|
||||
private string _dailyRewardPartyName = string.Empty;
|
||||
|
||||
// 合成浓缩后保留原粹树脂的数量
|
||||
[ObservableProperty]
|
||||
private int _minResinToKeep = 0;
|
||||
|
||||
// 领取每日奖励的好感数量
|
||||
[ObservableProperty]
|
||||
private string _sundayEverySelectedValue = "0";
|
||||
|
||||
// 领取每日奖励的好感数量
|
||||
[ObservableProperty]
|
||||
private string _sundaySelectedValue = "0";
|
||||
|
||||
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
|
||||
[ObservableProperty]
|
||||
private string _sereniteaPotTpType = "地图传送";
|
||||
|
||||
// 尘歌壶洞天购买商品
|
||||
[ObservableProperty]
|
||||
private List<string> _secretTreasureObjects = new();
|
||||
|
||||
#region 每周秘境配置
|
||||
|
||||
//周一
|
||||
[ObservableProperty]
|
||||
private string _mondayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _mondayDomainName = string.Empty;
|
||||
|
||||
|
||||
//周二
|
||||
[ObservableProperty]
|
||||
private string _tuesdayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _tuesdayDomainName = string.Empty;
|
||||
|
||||
//周三
|
||||
[ObservableProperty]
|
||||
private string _wednesdayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _wednesdayDomainName = string.Empty;
|
||||
|
||||
//周四
|
||||
[ObservableProperty]
|
||||
private string _thursdayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _thursdayDomainName = string.Empty;
|
||||
|
||||
//周五
|
||||
[ObservableProperty]
|
||||
private string _fridayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _fridayDomainName = string.Empty;
|
||||
|
||||
//周六
|
||||
[ObservableProperty]
|
||||
private string _saturdayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _saturdayDomainName = string.Empty;
|
||||
|
||||
//周日
|
||||
[ObservableProperty]
|
||||
private string _sundayPartyName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _sundayDomainName = string.Empty;
|
||||
|
||||
// 完成后操作
|
||||
[ObservableProperty]
|
||||
private string _completionAction = string.Empty;
|
||||
|
||||
// 通过当天(4点起始)是哪一天来返回配置
|
||||
public (string partyName, string domainName, string sundaySelectedValue) GetDomainConfig()
|
||||
{
|
||||
if (WeeklyDomainEnabled)
|
||||
{
|
||||
var serverTime = ServerTimeHelper.GetServerTimeNow();
|
||||
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
|
||||
return dayOfWeek switch
|
||||
{
|
||||
DayOfWeek.Monday => (MondayPartyName, MondayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Tuesday => (TuesdayPartyName, TuesdayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Wednesday => (WednesdayPartyName, WednesdayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Thursday => (ThursdayPartyName, ThursdayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Friday => (FridayPartyName, FridayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Saturday => (SaturdayPartyName, SaturdayDomainName,SundaySelectedValue),
|
||||
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName,SundaySelectedValue),
|
||||
_ => (PartyName, DomainName,SundaySelectedValue)
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
return (PartyName, DomainName,SundayEverySelectedValue);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
|
||||
[Serializable]
|
||||
public partial class OtherConfig : ObservableObject
|
||||
{
|
||||
//调度器任务和部分独立任务,失去焦点,自动激活游戏窗口
|
||||
[ObservableProperty]
|
||||
private bool _restoreFocusOnLostEnabled = false;
|
||||
//自动领取派遣任务城市
|
||||
[ObservableProperty]
|
||||
private string _autoFetchDispatchAdventurersGuildCountry = "无";
|
||||
//服务器时区偏移量
|
||||
[ObservableProperty]
|
||||
private TimeSpan _serverTimeZoneOffset = TimeSpan.FromHours(8);
|
||||
[ObservableProperty]
|
||||
private AutoRestart _autoRestartConfig = new();
|
||||
//锄地规划
|
||||
[ObservableProperty]
|
||||
private FarmingPlan _farmingPlanConfig = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private Miyoushe _miyousheConfig = new();
|
||||
//OCR配置
|
||||
[ObservableProperty]
|
||||
private Ocr _ocrConfig = new();
|
||||
|
||||
|
||||
public partial class AutoRestart : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
|
||||
//调度器任务连续异常退出几次任务自动重启
|
||||
[ObservableProperty]
|
||||
private int _failureCount = 5;
|
||||
|
||||
//是否同时重启游戏,需开启首页启动配置:同时启动原神、自动进入游戏,此配置才会生效
|
||||
[ObservableProperty]
|
||||
private bool _restartGameTogether = false;
|
||||
|
||||
//锄地脚本,如果打架次数不一致,则判定任务失败。
|
||||
[ObservableProperty]
|
||||
private bool _isFightFailureExceptional = false;
|
||||
|
||||
//任何追踪任务,未走完全路径结束,视为失败。
|
||||
[ObservableProperty]
|
||||
private bool _isPathingFailureExceptional = false;
|
||||
|
||||
}
|
||||
|
||||
public partial class Miyoushe : ObservableObject
|
||||
{
|
||||
|
||||
//cookie
|
||||
[ObservableProperty]
|
||||
private string _cookie = "";
|
||||
|
||||
//与调度器日志处相互同步cookie
|
||||
[ObservableProperty]
|
||||
private bool _logSyncCookie = true;
|
||||
|
||||
}
|
||||
public partial class MiyousheDataSupport : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
|
||||
//日精英上限
|
||||
[ObservableProperty]
|
||||
private int _dailyEliteCap = 400;
|
||||
|
||||
//日小怪上限
|
||||
[ObservableProperty]
|
||||
private int _dailyMobCap = 2000;
|
||||
}
|
||||
public partial class FarmingPlan : ObservableObject
|
||||
{
|
||||
|
||||
|
||||
[ObservableProperty]
|
||||
private MiyousheDataSupport _miyousheDataConfig = new();
|
||||
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
|
||||
//日精英上限
|
||||
[ObservableProperty]
|
||||
private int _dailyEliteCap = 400;
|
||||
|
||||
//日小怪上限
|
||||
[ObservableProperty]
|
||||
private int _dailyMobCap = 2000;
|
||||
|
||||
}
|
||||
|
||||
public partial class Ocr : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// PaddleOCR模型配置
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private PaddleOcrModelConfig _paddleOcrModelConfig = PaddleOcrModelConfig.V4Auto;
|
||||
}
|
||||
|
||||
//public partial class OtherConfig : ObservableObject
|
||||
|
||||
/// <summary>
|
||||
/// 游戏语言名称
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _gameCultureInfoName = "zh-Hans";
|
||||
|
||||
/// <summary>
|
||||
/// BGI界面语言名称
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _uiCultureInfoName = "zh-Hans";
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.Model;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class PathingConditionConfig : ObservableObject
|
||||
{
|
||||
[ObservableProperty]
|
||||
private string _mapMatchingMethod = "TemplateMatch";
|
||||
|
||||
// 地图追踪条件配置
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<Condition> _partyConditions = [];
|
||||
|
||||
[ObservableProperty]
|
||||
private ObservableCollection<Condition> _avatarConditions = [];
|
||||
|
||||
// 只在传送传送点时复活
|
||||
[ObservableProperty]
|
||||
private bool _onlyInTeleportRecover = false;
|
||||
|
||||
// 使用小道具的间隔时间(ms)
|
||||
[ObservableProperty]
|
||||
private int _useGadgetIntervalMs = 0;
|
||||
|
||||
// 启用自动吃药功能
|
||||
[ObservableProperty]
|
||||
private bool _autoEatEnabled = false;
|
||||
|
||||
public static PathingConditionConfig Default => new()
|
||||
{
|
||||
AvatarConditions =
|
||||
[
|
||||
new Condition
|
||||
{
|
||||
Subject = "队伍中角色",
|
||||
Object = ["绮良良", "莱依拉", "茜特菈莉", "芭芭拉", "七七"],
|
||||
Result = "循环短E"
|
||||
},
|
||||
|
||||
new Condition
|
||||
{
|
||||
Subject = "队伍中角色",
|
||||
Object = ["钟离"],
|
||||
Result = "循环长E"
|
||||
},
|
||||
|
||||
new Condition
|
||||
{
|
||||
Subject = "队伍中角色",
|
||||
Object = ["迪希雅"],
|
||||
Result = "作为主要行走角色"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 找出当前应该切换的队伍名称
|
||||
/// </summary>
|
||||
/// <param name="materialName">采集物名称</param>
|
||||
/// <param name="specialActions">特殊动作</param>
|
||||
/// <returns></returns>
|
||||
public string? FilterPartyName(string? materialName, List<string?> specialActions)
|
||||
{
|
||||
if (specialActions is { Count: > 0 })
|
||||
{
|
||||
// 特殊动作匹配队伍名
|
||||
foreach (var action in specialActions)
|
||||
{
|
||||
if (string.IsNullOrEmpty(action))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!ConditionDefinitions.ActionCnDic.TryGetValue(action, out var actionCn))
|
||||
{
|
||||
continue; // 不校验
|
||||
}
|
||||
|
||||
var condition = PartyConditions.FirstOrDefault(c => c.Subject == "动作" && c.Object.Contains(actionCn));
|
||||
if (condition is { Result: not null })
|
||||
{
|
||||
return condition.Result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 采集物匹配队伍名
|
||||
Condition? materialCondition = null;
|
||||
if (!string.IsNullOrEmpty(materialName))
|
||||
{
|
||||
materialCondition = PartyConditions.FirstOrDefault(c => c.Subject == "采集物" && c.Object.Contains(materialName));
|
||||
}
|
||||
if (materialCondition is { Result: not null })
|
||||
{
|
||||
return materialCondition.Result;
|
||||
}
|
||||
else
|
||||
{
|
||||
materialCondition = PartyConditions.FirstOrDefault(c => c.Subject == "采集物" && c.Object.Contains("全部"));
|
||||
if (materialCondition is { Result: not null })
|
||||
{
|
||||
return materialCondition.Result;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通过条件配置生成队伍配置
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public PathingPartyConfig BuildPartyConfigByCondition(CombatScenes combatScenes)
|
||||
{
|
||||
PathingPartyConfig partyConfig = PathingPartyConfig.BuildDefault();
|
||||
// 使用最优先匹配上的条件
|
||||
foreach (var avatarCondition in AvatarConditions)
|
||||
{
|
||||
if (avatarCondition.Result == "循环短E" || avatarCondition.Result == "循环长E")
|
||||
{
|
||||
foreach (var avatar in combatScenes.GetAvatars())
|
||||
{
|
||||
if (avatarCondition is { Object: not null } && avatarCondition.Object.Contains(avatar.Name))
|
||||
{
|
||||
partyConfig.GuardianAvatarIndex = avatar.Index.ToString();
|
||||
if (avatarCondition.Result == "循环长E")
|
||||
{
|
||||
partyConfig.GuardianElementalSkillLongPress = true;
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.CombatAvatar.SkillHoldCd.ToString(CultureInfo.CurrentCulture);
|
||||
}
|
||||
else
|
||||
{
|
||||
partyConfig.GuardianElementalSkillLongPress = false;
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.CombatAvatar.SkillCd.ToString(CultureInfo.CurrentCulture);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(partyConfig.GuardianAvatarIndex))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var avatarCondition in AvatarConditions)
|
||||
{
|
||||
if (avatarCondition.Result == "作为主要行走角色")
|
||||
{
|
||||
foreach (var avatar in combatScenes.GetAvatars())
|
||||
{
|
||||
if (avatarCondition is not null && avatarCondition.Object.Contains(avatar.Name))
|
||||
{
|
||||
partyConfig.MainAvatarIndex = avatar.Index.ToString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(partyConfig.MainAvatarIndex))
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 默认元素力采集角色
|
||||
// var elementalCollectAvatars = ElementalCollectAvatarConfigs.Lists;
|
||||
// foreach (var avatar in combatScenes.Avatars)
|
||||
// {
|
||||
// var elementalCollectAvatar = elementalCollectAvatars.FirstOrDefault(x => x.Name == avatar.Name);
|
||||
// if (elementalCollectAvatar != null)
|
||||
// {
|
||||
// if (elementalCollectAvatar.ElementalType == ElementalType.Hydro)
|
||||
// {
|
||||
// partyConfig.HydroCollectAvatarIndex = avatar.Index.ToString();
|
||||
// }
|
||||
// else if (elementalCollectAvatar.ElementalType == ElementalType.Electro)
|
||||
// {
|
||||
// partyConfig.ElectroCollectAvatarIndex = avatar.Index.ToString();
|
||||
// }
|
||||
// else if (elementalCollectAvatar.ElementalType == ElementalType.Anemo)
|
||||
// {
|
||||
// partyConfig.AnemoCollectAvatarIndex = avatar.Index.ToString();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
return partyConfig;
|
||||
}
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.GameTask.AutoEat;
|
||||
using BetterGenshinImpact.GameTask.AutoFight;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class PathingPartyConfig : ObservableObject
|
||||
{
|
||||
// 配置是否启用,不启用会使用地图追踪内的条件配置
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
|
||||
// 是否启用自动拾取
|
||||
[ObservableProperty]
|
||||
private bool _autoPickEnabled = true;
|
||||
// 切换到队伍的名称
|
||||
[ObservableProperty]
|
||||
private string _partyName = string.Empty;
|
||||
|
||||
// 切换队伍前是否前往须弥七天神像
|
||||
[ObservableProperty]
|
||||
private bool _isVisitStatueBeforeSwitchParty = false;
|
||||
|
||||
// 主要行走追踪的角色编号
|
||||
[ObservableProperty]
|
||||
private string _mainAvatarIndex = string.Empty;
|
||||
|
||||
// [盾角]使用元素战技的角色编号
|
||||
[ObservableProperty]
|
||||
private string _guardianAvatarIndex = string.Empty;
|
||||
|
||||
// [盾角]使用元素战技的时间间隔(s)
|
||||
[ObservableProperty]
|
||||
private string _guardianElementalSkillSecondInterval = string.Empty;
|
||||
|
||||
// [盾角]使用元素战技的方式 长按/短按
|
||||
[ObservableProperty]
|
||||
private bool _guardianElementalSkillLongPress = false;
|
||||
|
||||
// // normal_attack 配置几号位
|
||||
// [ObservableProperty]
|
||||
// private string _normalAttackAvatarIndex = string.Empty;
|
||||
//
|
||||
// // elemental_skill 配置几号位
|
||||
// [ObservableProperty]
|
||||
// private string _elementalSkillAvatarIndex = string.Empty;
|
||||
|
||||
// // hydro_collect 配置几号位
|
||||
// [ObservableProperty]
|
||||
// private string _hydroCollectAvatarIndex = string.Empty;
|
||||
//
|
||||
// // electro_collect 配置几号位
|
||||
// [ObservableProperty]
|
||||
// private string _electroCollectAvatarIndex = string.Empty;
|
||||
//
|
||||
// // anemo_collect 配置几号位
|
||||
// [ObservableProperty]
|
||||
// private string _anemoCollectAvatarIndex = string.Empty;
|
||||
|
||||
[JsonIgnore]
|
||||
public List<string> AvatarIndexList { get; } = ["", "1", "2", "3", "4"];
|
||||
|
||||
// 只在传送传送点时复活
|
||||
[ObservableProperty]
|
||||
private bool _onlyInTeleportRecover = false;
|
||||
|
||||
//允许在jsScript脚本中使用此地图追踪配置
|
||||
[ObservableProperty]
|
||||
private bool _jsScriptUseEnabled = true;
|
||||
|
||||
//允许在此调度器中(一般在JS脚本中)调用自动战斗任务时,采用此追踪配置里的战斗策略
|
||||
[ObservableProperty]
|
||||
private bool _soloTaskUseFightEnabled = true;
|
||||
|
||||
//不在某时执行
|
||||
[ObservableProperty]
|
||||
private string _skipDuring = "";
|
||||
|
||||
// 使用小道具的间隔时间
|
||||
[ObservableProperty]
|
||||
private int _useGadgetIntervalMs = 0;
|
||||
|
||||
// 启用进入剧情自动脱离
|
||||
[ObservableProperty]
|
||||
private bool _autoSkipEnabled = true;
|
||||
|
||||
// 自动冲刺启用
|
||||
[ObservableProperty]
|
||||
private bool _autoRunEnabled = true;
|
||||
|
||||
// 启用自动吃药功能
|
||||
[ObservableProperty]
|
||||
private bool _autoEatEnabled = false;
|
||||
|
||||
/// <summary>
|
||||
/// 自动吃食物配置
|
||||
/// 供JS脚本使用
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private AutoEatConfig _autoEatConfig = new();
|
||||
|
||||
//在连续执行时是否隐藏
|
||||
[ObservableProperty]
|
||||
private bool _hideOnRepeat = false;
|
||||
|
||||
//执行周期配置
|
||||
[ObservableProperty]
|
||||
private PathingPartyTaskCycleConfig _taskCycleConfig = new();
|
||||
|
||||
//任务完成跳过执行配置
|
||||
[ObservableProperty]
|
||||
private TaskCompletionSkipRuleConfig _taskCompletionSkipRuleConfig = new();
|
||||
//优先执行其他配置组
|
||||
[ObservableProperty]
|
||||
private PreExecutionPriorityConfig _preExecutionPriorityConfig = new();
|
||||
|
||||
//启用自动战斗配置
|
||||
[ObservableProperty]
|
||||
private bool _autoFightEnabled = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private AutoFightConfig _autoFightConfig = new();
|
||||
public static PathingPartyConfig BuildDefault()
|
||||
{
|
||||
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
|
||||
var pathingConditionConfig = TaskContext.Instance().Config.PathingConditionConfig;
|
||||
return new PathingPartyConfig
|
||||
{
|
||||
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
|
||||
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs,
|
||||
AutoEatEnabled = pathingConditionConfig.AutoEatEnabled
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class PathingPartyTaskCycleConfig : ObservableObject
|
||||
{
|
||||
//启用执行周期配置
|
||||
[ObservableProperty]
|
||||
private bool _enable = false;
|
||||
|
||||
//周期分界时间点(小时),如果负数则不启用
|
||||
[ObservableProperty]
|
||||
private int _boundaryTime = 0;
|
||||
// 分界时间是否基于服务器时间(否则基于本地时间)
|
||||
[ObservableProperty]
|
||||
private bool _isBoundaryTimeBasedOnServerTime = false;
|
||||
|
||||
|
||||
//不同材料有不同的周期,按需配置,如矿石类是3、突破材料是2,或按照自已想几天执行一次配置即可
|
||||
[ObservableProperty]
|
||||
private int _cycle = 1;
|
||||
|
||||
|
||||
|
||||
//执行周期序号,按时间戳对应的天数,对周期求余值加1,得出的值和配置执一致就会执行,否则跳过任务。
|
||||
[ObservableProperty]
|
||||
private int _index = 1;
|
||||
|
||||
|
||||
public int GetExecutionOrder(DateTimeOffset now)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_cycle <= 0 || _boundaryTime <0 || _boundaryTime > 24 )
|
||||
return -1;
|
||||
|
||||
// 修正时间:如果当前时间小于当天的分界时间,则视为前一天
|
||||
DateTime boundaryTimeToday = new DateTime(now.Year, now.Month, now.Day, _boundaryTime, 0, 0);
|
||||
if (now < boundaryTimeToday)
|
||||
{
|
||||
now = now.AddDays(-1); // 归属到前一天
|
||||
}
|
||||
|
||||
// 获取从某个固定点(如 Unix 纪元)起的“修正天数”
|
||||
// 可以使用 DateTime.UnixEpoch(从 1970-01-01 00:00:00 开始)
|
||||
DateTime baseDate = DateTime.UnixEpoch; // 即 1970-01-01
|
||||
TimeSpan daysSinceBase = now.Date - baseDate.Date;
|
||||
int totalDays = (int)daysSinceBase.TotalDays;
|
||||
|
||||
// 执行序号 = (修正天数 % 周期) + 1
|
||||
int executionOrder = (totalDays % _cycle) + 1;
|
||||
return executionOrder;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
}
|
||||
public int GetExecutionOrder()
|
||||
{
|
||||
return GetExecutionOrder(IsBoundaryTimeBasedOnServerTime
|
||||
? ServerTimeHelper.GetServerTimeNow()
|
||||
: DateTimeOffset.Now);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
|
||||
[Serializable]
|
||||
public partial class PreExecutionPriorityConfig: ObservableObject
|
||||
{
|
||||
|
||||
// 配置是否启用
|
||||
[ObservableProperty]
|
||||
private bool _enabled = false;
|
||||
/// <summary>
|
||||
/// 需要优先检查执行的配置组名称,多个用逗号分隔。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private string _groupNames = "";
|
||||
|
||||
/// <summary>
|
||||
/// 最大重试次数,如果优先的任务执行失败了,重试几次。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int _maxRetryCount = 1;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
[Serializable]
|
||||
public partial class RecordConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 视角每移动1度,需要MouseMoveBy的距离
|
||||
/// 用作脚本记录度数后转化的鼠标移动距离
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _angle2MouseMoveByX = 1.0;
|
||||
|
||||
/// <summary>
|
||||
/// 视角每移动1度,需要DirectInput移动的单位
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private double _angle2DirectInputX = 1.0;
|
||||
|
||||
/// <summary>
|
||||
/// 图像识别记录相机视角朝向
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private bool _isRecordCameraOrientation = false;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
/// <summary>
|
||||
/// 脚本配置
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public partial class ScriptConfig : ObservableObject
|
||||
{
|
||||
// 自动更新脚本仓库周期(天)
|
||||
[ObservableProperty]
|
||||
private int _autoUpdateScriptRepoPeriod = 1;
|
||||
|
||||
// 上次更新脚本仓库时间
|
||||
[ObservableProperty]
|
||||
private DateTime _lastUpdateScriptRepoTime = DateTime.MinValue;
|
||||
|
||||
// 脚本仓库按钮红点是否展示
|
||||
[ObservableProperty]
|
||||
private bool _scriptRepoHintDotVisible = false;
|
||||
|
||||
// 已订阅的脚本路径列表
|
||||
[ObservableProperty]
|
||||
private List<string> _subscribedScriptPaths = [];
|
||||
|
||||
// 选择的更新渠道名称
|
||||
[ObservableProperty] private string _selectedChannelName = "";
|
||||
|
||||
// 自定义渠道的URL
|
||||
[ObservableProperty] private string _customRepoUrl = "";
|
||||
|
||||
// 仓库页面宽度
|
||||
[ObservableProperty] private double _webviewWidth = 0;
|
||||
|
||||
// 仓库页面高度
|
||||
[ObservableProperty] private double _webviewHeight = 0;
|
||||
|
||||
// 仓库页面横向位置
|
||||
[ObservableProperty] private double _webviewLeft = 0;
|
||||
|
||||
// 仓库页面纵向位置
|
||||
[ObservableProperty] private double _webviewTop = 0;
|
||||
|
||||
// 仓库页面是否最大化
|
||||
[ObservableProperty] private WindowState _webviewState = WindowState.Normal;
|
||||
|
||||
// 仓库新手教程是否已阅读
|
||||
[ObservableProperty] private bool _guideStatus = false;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Config;
|
||||
|
||||
public partial class TaskCompletionSkipRuleConfig:ObservableObject
|
||||
{
|
||||
//启用跳过完成任务
|
||||
[ObservableProperty]
|
||||
private bool _enable = false;
|
||||
|
||||
//跳过策略
|
||||
//GroupPhysicalPathSkipPolicy: 配置组且物理路径相同跳过
|
||||
//PhysicalPathSkipPolicy: 物理路径相同跳过
|
||||
//SameNameSkipPolicy: 同类型同名跳过
|
||||
[ObservableProperty]
|
||||
private string _skipPolicy = "GroupPhysicalPathSkipPolicy";
|
||||
|
||||
|
||||
//周期分界时间点,如果负数则不启用,主要适用于固定时间的刷新物品适用
|
||||
[ObservableProperty]
|
||||
private int _boundaryTime = 4;
|
||||
// 分界时间是否基于服务器时间(否则基于本地时间)
|
||||
[ObservableProperty]
|
||||
private bool _isBoundaryTimeBasedOnServerTime = false;
|
||||
|
||||
//上一次执行间隔时间,出于精度考虑,这里使用秒为单位
|
||||
[ObservableProperty]
|
||||
private int _lastRunGapSeconds = -1;
|
||||
//间隔时间计算参照,开始时间(StartTime)和结束时间(EndTime)
|
||||
[ObservableProperty]
|
||||
private string _referencePoint = "EndTime";
|
||||
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using SharpDX.DirectInput;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Monitor;
|
||||
|
||||
public class DirectInputMonitor : IDisposable
|
||||
{
|
||||
private bool _isRunning = true;
|
||||
|
||||
private readonly Mouse _mouse;
|
||||
|
||||
public static int Interval = 5;
|
||||
|
||||
public DirectInputMonitor()
|
||||
{
|
||||
var directInput = new DirectInput();
|
||||
_mouse = new Mouse(directInput);
|
||||
_mouse.SetCooperativeLevel(IntPtr.Zero, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
|
||||
}
|
||||
|
||||
public MouseState GetMouseState()
|
||||
{
|
||||
_mouse.Acquire();
|
||||
return _mouse.GetCurrentState();
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
while (_isRunning)
|
||||
{
|
||||
_mouse.Acquire();
|
||||
MouseState state = _mouse.GetCurrentState();
|
||||
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state, Kernel32.GetTickCount());
|
||||
Thread.Sleep(Interval); // 10ms, equivalent to CLOCKS_PER_SEC/100
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_isRunning = false;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_mouse.Dispose();
|
||||
}
|
||||
}
|
||||
+18
-81
@@ -1,32 +1,22 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recorder;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Model;
|
||||
using Gma.System.MouseKeyHook;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
using Vanara.PInvoke;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
// Wine 平台适配
|
||||
using BetterGenshinImpact.Platform.Wine;
|
||||
namespace BetterGenshinImpact.Core.Monitor;
|
||||
namespace BetterGenshinImpact.Core;
|
||||
|
||||
public partial class MouseKeyMonitor
|
||||
public class MouseKeyMonitor
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 长按F变F连发
|
||||
/// </summary>
|
||||
private readonly Timer _fTimer = new();
|
||||
|
||||
private Keys _pickUpKey = Keys.F;
|
||||
|
||||
private User32.VK _pickUpKeyCode = User32.VK.VK_F;
|
||||
|
||||
//private readonly Random _random = new();
|
||||
|
||||
/// <summary>
|
||||
@@ -34,10 +24,6 @@ public partial class MouseKeyMonitor
|
||||
/// </summary>
|
||||
private readonly Timer _spaceTimer = new();
|
||||
|
||||
private Keys _releaseControlKey = Keys.Space;
|
||||
|
||||
private User32.VK _releaseControlKeyCode = User32.VK.VK_SPACE;
|
||||
|
||||
private DateTime _firstFKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
/// <summary>
|
||||
@@ -45,67 +31,39 @@ public partial class MouseKeyMonitor
|
||||
/// </summary>
|
||||
private DateTime _firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
|
||||
private static IKeyboardMouseEvents? _globalHook;
|
||||
private static readonly object GlobalHookLock = new object();
|
||||
public static IKeyboardMouseEvents GlobalHook
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_globalHook == null)
|
||||
{
|
||||
lock (GlobalHookLock)
|
||||
{
|
||||
if (_globalHook == null)
|
||||
{
|
||||
_globalHook = Hook.GlobalEvents();
|
||||
}
|
||||
}
|
||||
}
|
||||
return _globalHook;
|
||||
}
|
||||
}
|
||||
private nint _hWnd;
|
||||
private IKeyboardMouseEvents? _globalHook;
|
||||
private IntPtr _hWnd;
|
||||
|
||||
public void Subscribe(nint gameHandle)
|
||||
public void Subscribe(IntPtr gameHandle)
|
||||
{
|
||||
_hWnd = gameHandle;
|
||||
// Note: for the application hook, use the Hook.AppEvents() instead
|
||||
_globalHook = Hook.GlobalEvents();
|
||||
|
||||
if (!WinePlatformAddon.IsRunningOnWine) {
|
||||
GlobalHook.KeyDown += GlobalHookKeyDown;
|
||||
GlobalHook.KeyUp += GlobalHookKeyUp;
|
||||
GlobalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
GlobalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
GlobalHook.MouseMoveExt += GlobalHookMouseMoveExt;
|
||||
GlobalHook.MouseWheelExt += GlobalHookMouseWheelExt;
|
||||
}
|
||||
TrySubscribeWinePolling();
|
||||
_globalHook.KeyDown += GlobalHookKeyDown;
|
||||
_globalHook.KeyUp += GlobalHookKeyUp;
|
||||
_globalHook.MouseDownExt += GlobalHookMouseDownExt;
|
||||
_globalHook.MouseUpExt += GlobalHookMouseUpExt;
|
||||
//_globalHook.KeyPress += GlobalHookKeyPress;
|
||||
|
||||
_pickUpKey = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToWinFormKeys();
|
||||
_pickUpKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.PickUpOrInteract.ToVK();
|
||||
_releaseControlKey = TaskContext.Instance().Config.KeyBindingsConfig.Jump.ToWinFormKeys();
|
||||
_releaseControlKeyCode = TaskContext.Instance().Config.KeyBindingsConfig.Jump.ToVK();
|
||||
|
||||
_firstSpaceKeyDownTime = DateTime.MaxValue;
|
||||
var si = TaskContext.Instance().Config.MacroConfig.SpaceFireInterval;
|
||||
_spaceTimer.Interval = si;
|
||||
_spaceTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_releaseControlKeyCode); };
|
||||
_spaceTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_SPACE); };
|
||||
|
||||
var fi = TaskContext.Instance().Config.MacroConfig.FFireInterval;
|
||||
_fTimer.Interval = fi;
|
||||
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(_pickUpKeyCode); };
|
||||
_fTimer.Elapsed += (sender, args) => { Simulation.PostMessage(_hWnd).KeyPress(User32.VK.VK_F); };
|
||||
}
|
||||
|
||||
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
|
||||
{
|
||||
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
|
||||
|
||||
// 热键按下事件
|
||||
HotKeyDown(sender, e);
|
||||
|
||||
if (e.KeyCode == _releaseControlKey)
|
||||
if (e.KeyCode == Keys.Space)
|
||||
{
|
||||
if (_firstSpaceKeyDownTime == DateTime.MaxValue)
|
||||
{
|
||||
@@ -119,7 +77,7 @@ public partial class MouseKeyMonitor
|
||||
_spaceTimer.Start();
|
||||
}
|
||||
}
|
||||
else if (e.KeyCode == _pickUpKey)
|
||||
else if (e.KeyCode == Keys.F)
|
||||
{
|
||||
if (_firstFKeyDownTime == DateTime.MaxValue)
|
||||
{
|
||||
@@ -138,12 +96,11 @@ public partial class MouseKeyMonitor
|
||||
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
|
||||
{
|
||||
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, Kernel32.GetTickCount());
|
||||
|
||||
// 热键松开事件
|
||||
HotKeyUp(sender, e);
|
||||
|
||||
if (e.KeyCode == _releaseControlKey)
|
||||
if (e.KeyCode == Keys.Space)
|
||||
{
|
||||
if (_firstSpaceKeyDownTime != DateTime.MaxValue)
|
||||
{
|
||||
@@ -153,7 +110,7 @@ public partial class MouseKeyMonitor
|
||||
_spaceTimer.Stop();
|
||||
}
|
||||
}
|
||||
else if (e.KeyCode == _pickUpKey)
|
||||
else if (e.KeyCode == Keys.F)
|
||||
{
|
||||
if (_firstFKeyDownTime != DateTime.MaxValue)
|
||||
{
|
||||
@@ -183,7 +140,6 @@ public partial class MouseKeyMonitor
|
||||
private void GlobalHookMouseDownExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseDown: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e);
|
||||
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
@@ -193,41 +149,22 @@ public partial class MouseKeyMonitor
|
||||
private void GlobalHookMouseUpExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseUp: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e);
|
||||
|
||||
if (e.Button != MouseButtons.Left)
|
||||
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
|
||||
hook.MouseUp(sender, e);
|
||||
}
|
||||
|
||||
private void GlobalHookMouseMoveExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e);
|
||||
}
|
||||
|
||||
private void GlobalHookMouseWheelExt(object? sender, MouseEventExtArgs e)
|
||||
{
|
||||
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
|
||||
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e);
|
||||
}
|
||||
|
||||
public void Unsubscribe()
|
||||
{
|
||||
if (_globalHook != null && !WinePlatformAddon.IsRunningOnWine)
|
||||
if (_globalHook != null)
|
||||
{
|
||||
_globalHook.KeyDown -= GlobalHookKeyDown;
|
||||
_globalHook.KeyUp -= GlobalHookKeyUp;
|
||||
_globalHook.MouseDownExt -= GlobalHookMouseDownExt;
|
||||
_globalHook.MouseUpExt -= GlobalHookMouseUpExt;
|
||||
_globalHook.MouseMoveExt -= GlobalHookMouseMoveExt;
|
||||
_globalHook.MouseWheelExt -= GlobalHookMouseWheelExt;
|
||||
//_globalHook.KeyPress -= GlobalHookKeyPress;
|
||||
_globalHook.Dispose();
|
||||
_globalHook = null;
|
||||
}
|
||||
if (WinePlatformAddon.IsRunningOnWine){
|
||||
DisposeWineAddon();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Dnn;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
|
||||
public static class OcrUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// 预处理速度比unsafe快5倍以上,且吃的资源还少
|
||||
/// </summary>
|
||||
/// <param name="inputImage">输入图像,若不是灰度图会转换</param>
|
||||
/// <param name="tensorMemoryOwnser">tensor的Memory,用完需要释放</param>
|
||||
/// <returns></returns>
|
||||
public static Tensor<float> ToTensorYapDnn(Mat inputImage, out IMemoryOwner<float> tensorMemoryOwnser)
|
||||
{
|
||||
using var rt = new ResourcesTracker();
|
||||
Mat dst;
|
||||
// 221*32是个什么鬼
|
||||
if (inputImage.Channels() > 1)
|
||||
{
|
||||
var resize = rt.T(ResizeHelper.ResizeTo(inputImage, 221, 32));
|
||||
dst = rt.NewMat(resize.Size(), MatType.CV_8UC1, Scalar.Black);
|
||||
Cv2.CvtColor(resize, dst, ColorConversionCodes.BGR2GRAY);
|
||||
}
|
||||
else
|
||||
{
|
||||
dst = rt.T(ResizeHelper.ResizeTo(inputImage, 221, 32));
|
||||
}
|
||||
|
||||
// 填充到 384x32
|
||||
var padded = rt.NewMat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
|
||||
padded[new Rect(0, 0, 221, 32)] = dst;
|
||||
// 使用向量运算代替循环
|
||||
var blob = rt.T(CvDnn.BlobFromImage(padded, 1.0 / 255.0, default, default, false, false));
|
||||
var nCols = padded.Cols * padded.Rows;
|
||||
tensorMemoryOwnser = MemoryPool<float>.Shared.Rent(nCols);
|
||||
// 内存复制,如果直接传指针构建的话速度还不如多复制一份
|
||||
blob.AsSpan<float>().CopyTo(tensorMemoryOwnser.Memory.Span);
|
||||
return new DenseTensor<float>(tensorMemoryOwnser.Memory[..nCols], [1, 1, 32, 384]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用于Det模型
|
||||
/// 归一化,标准化并返回Tensor。
|
||||
/// <br />
|
||||
/// 归一化:固定范围归一化
|
||||
/// <br />
|
||||
/// 标准化:
|
||||
/// Z-Score Normalization
|
||||
/// </summary>
|
||||
public static Tensor<float> NormalizeToTensorDnn(Mat src,
|
||||
float? scale, // scale float32
|
||||
float[]? mean, //mean
|
||||
float[]? std, //std
|
||||
out IMemoryOwner<float> tensorMemoryOwner, bool swapRb = false, bool crop = false, Size size = default)
|
||||
|
||||
{
|
||||
scale ??= 0.00392156862745f;
|
||||
mean ??= [0.485f, 0.456f, 0.406f];
|
||||
std ??= [0.229f, 0.224f, 0.225f];
|
||||
using var rt = new ResourcesTracker();
|
||||
// 获取图像参数
|
||||
var channels = src.Channels();
|
||||
if (channels != 3)
|
||||
throw new ArgumentException($"图像通道数必须为3,当前为{channels}");
|
||||
// var data = rt.T(OcrOperationImpl.NormalizeImageOperation(src, scale, mean, std));
|
||||
var stdMat = rt.NewMat();
|
||||
Mat[] bgr = [];
|
||||
try
|
||||
{
|
||||
bgr = src.Split();
|
||||
for (var i = 0; i < bgr.Length; ++i)
|
||||
bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1 / std[i],
|
||||
(0.0 - mean[i]) / std[i] / (float)scale);
|
||||
Cv2.Merge(bgr, stdMat);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var channel in bgr) channel.Dispose();
|
||||
}
|
||||
|
||||
//stdMat.GetArray<float>(out var data);
|
||||
// 使用DNN模块创建blob
|
||||
var blob = rt.T(CvDnn.BlobFromImage(
|
||||
stdMat,
|
||||
(double)scale,
|
||||
size,
|
||||
default,
|
||||
swapRb,
|
||||
crop
|
||||
));
|
||||
|
||||
// 租用内存并复制数据
|
||||
var total = (int)blob.Total();
|
||||
tensorMemoryOwner = MemoryPool<float>.Shared.Rent(total);
|
||||
blob.AsSpan<float>().CopyTo(tensorMemoryOwner.Memory.Span);
|
||||
// 计算输出形状
|
||||
return new DenseTensor<float>(
|
||||
tensorMemoryOwner.Memory[..total],
|
||||
new[] { 1, channels, stdMat.Rows, stdMat.Cols }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不支持通道转换
|
||||
/// <br />
|
||||
/// 用于PP-OCR的Rec模型,调整大小之后再归一化到-1~1,之后转换为Tensor
|
||||
/// </summary>
|
||||
public static Tensor<float> ResizeNormImg(Mat img, OcrShape imageShape,
|
||||
out IMemoryOwner<float> tensorMemoryOwner, bool padding = true,
|
||||
InterpolationFlags interpolation = InterpolationFlags.Linear)
|
||||
{
|
||||
using var rt = new ResourcesTracker();
|
||||
// var imgC = imageShape.Channel;
|
||||
var imgH = imageShape.Height;
|
||||
var imgW = imageShape.Width;
|
||||
|
||||
var h = img.Height;
|
||||
var w = img.Width;
|
||||
|
||||
var resizedImage = rt.NewMat();
|
||||
if (!padding)
|
||||
{
|
||||
Cv2.Resize(img, resizedImage, new Size(imgW, imgH), 0, 0, interpolation);
|
||||
// resized_w = imgW;
|
||||
}
|
||||
else
|
||||
{
|
||||
var ratio = w / (double)h;
|
||||
var resizedW = Math.Ceiling(imgH * ratio) > imgW ? imgW : (int)Math.Ceiling(imgH * ratio);
|
||||
Cv2.Resize(img, resizedImage, new Size(resizedW, imgH), 0, 0, interpolation);
|
||||
}
|
||||
|
||||
/*
|
||||
resized_image / 255
|
||||
resized_image -= 0.5
|
||||
resized_image /= 0.5
|
||||
*/
|
||||
// 归一化到 +-1
|
||||
// resizedImage.ConvertTo(resizedImage, MatType.CV_32F, 2 / 255f, 1);
|
||||
var blob = rt.T(CvDnn.BlobFromImage(
|
||||
resizedImage,
|
||||
2 / 255f,
|
||||
default,
|
||||
new Scalar(127.5, 127.5, 127.5),
|
||||
false,
|
||||
false
|
||||
));
|
||||
|
||||
var total = blob.Total();
|
||||
tensorMemoryOwner = MemoryPool<float>.Shared.Rent((int)total);
|
||||
blob.AsSpan<float>().CopyTo(tensorMemoryOwner.Memory.Span);
|
||||
return new DenseTensor<float>(
|
||||
tensorMemoryOwner.Memory[..(int)total],
|
||||
new[] { 1, resizedImage.Channels(), resizedImage.Rows, resizedImage.Cols }
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a label by its index.
|
||||
/// </summary>
|
||||
/// <param name="i">The index of the label.</param>
|
||||
/// <param name="labels">The labels to search for the index.</param>
|
||||
/// <returns>The label at the specified index.</returns>
|
||||
public static string GetLabelByIndex(int i, IReadOnlyList<string> labels)
|
||||
{
|
||||
return i switch
|
||||
{
|
||||
var x when x > 0 && x <= labels.Count => labels[x - 1],
|
||||
var x when x == labels.Count + 1 => " ",
|
||||
_ => throw new Exception(
|
||||
$"Unable to GetLabelByIndex: index {i} out of range {labels.Count}, OCR model or labels not matched?")
|
||||
};
|
||||
}
|
||||
|
||||
public static Mat Tensor2Mat(Tensor<float> tensor)
|
||||
{
|
||||
var dimensions = tensor.Dimensions;
|
||||
if (dimensions.Length != 4 || dimensions[0] != 1 || dimensions[1] != 1)
|
||||
throw new ArgumentException($"wrong tensor shape: {string.Join(",", dimensions.ToArray())}");
|
||||
if (tensor is not DenseTensor<float> denseTensor)
|
||||
return Mat.FromPixelData(dimensions[2], dimensions[3], MatType.CV_32FC1, tensor.ToArray());
|
||||
var mat = new Mat(new Size(dimensions[3], dimensions[2]), MatType.CV_32FC1);
|
||||
denseTensor.Buffer.Span.CopyTo(mat.AsSpan<float>());
|
||||
return mat;
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// ppocr的版本配置
|
||||
/// </summary>
|
||||
public readonly record struct OcrVersionConfig(
|
||||
string Name,
|
||||
OcrImgMode Mode,
|
||||
bool ChannelFirst,
|
||||
OcrNormalizeImage NormalizeImage,
|
||||
OcrShape Shape)
|
||||
{
|
||||
// 参数来自 https://github.com/PaddlePaddle/PaddleOCR/tree/main/configs/det/PP-OCRv3
|
||||
|
||||
public static OcrVersionConfig PpOcrV3 = new(
|
||||
"PP-OCRv3",
|
||||
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)
|
||||
);
|
||||
|
||||
public static OcrVersionConfig PpOcrV4 = new(
|
||||
"PP-OCRv4",
|
||||
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));
|
||||
|
||||
public static OcrVersionConfig PpOcrV5 = new(
|
||||
"PP-OCRv5",
|
||||
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,10 +0,0 @@
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
|
||||
/// <summary>
|
||||
/// 图像的颜色顺序
|
||||
/// </summary>
|
||||
public enum OcrImgMode
|
||||
{
|
||||
BGR,
|
||||
RGB
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
|
||||
/// <summary>
|
||||
/// Mat的通道顺序
|
||||
/// hwc: height width channel
|
||||
/// chw: channel height width
|
||||
/// </summary>
|
||||
public enum OcrMatOrder
|
||||
{
|
||||
Hwc,
|
||||
Chw
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
|
||||
/// <summary>
|
||||
/// 标准归一化的三个参数
|
||||
/// </summary>
|
||||
public record OcrNormalizeImage(float Scale, float[] Mean, float[] Std);
|
||||
@@ -1,6 +0,0 @@
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
|
||||
|
||||
/// <summary>
|
||||
/// 图像形状表示
|
||||
/// </summary>
|
||||
public readonly record struct OcrShape(int Channel, int Width, int Height);
|
||||
@@ -9,4 +9,4 @@ public interface IOcrService
|
||||
public string OcrWithoutDetector(Mat mat);
|
||||
|
||||
public OcrResult OcrResult(Mat mat);
|
||||
}
|
||||
}
|
||||
@@ -1,154 +1,17 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
public class OcrFactory : IDisposable
|
||||
public class OcrFactory
|
||||
{
|
||||
// public static IOcrService Media = Create(OcrEngineTypes.Media);
|
||||
public static IOcrService Paddle { get; } = Create(OcrEngineTypes.Paddle);
|
||||
|
||||
|
||||
public static IOcrService Paddle => App.ServiceProvider.GetRequiredService<OcrFactory>().PaddleOcr;
|
||||
private IOcrService PaddleOcr => _paddleOcrService ??= Create(OcrEngineTypes.Paddle);
|
||||
|
||||
private IOcrService? _paddleOcrService;
|
||||
private readonly ILogger<BgiOnnxFactory> _logger;
|
||||
private readonly OtherConfig.Ocr _config;
|
||||
|
||||
/// <summary>
|
||||
/// OCR 工厂,不可以直接实例化,请使用 App.ServiceProvider获取实例
|
||||
/// </summary>
|
||||
/// <param name="logger"></param>
|
||||
public OcrFactory(ILogger<BgiOnnxFactory> logger)
|
||||
public static IOcrService Create(OcrEngineTypes type)
|
||||
{
|
||||
_logger = logger;
|
||||
_config = GetConfig();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建
|
||||
/// </summary>
|
||||
private IOcrService Create(OcrEngineTypes type)
|
||||
{
|
||||
var result = type switch
|
||||
return type switch
|
||||
{
|
||||
OcrEngineTypes.Paddle => CreatePaddleOcrInstance(),
|
||||
_ => throw new ArgumentOutOfRangeException(Enum.GetName(type), type, "不支持的 OCR 引擎类型")
|
||||
};
|
||||
_logger.LogDebug("创建了类型为 {Type} 的 OCR服务", Enum.GetName(type));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 OCR 配置
|
||||
/// 为了单元测试
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private OtherConfig.Ocr GetConfig()
|
||||
{
|
||||
try
|
||||
{
|
||||
// 直接使用配置
|
||||
return TaskContext.Instance().Config.OtherConfig.OcrConfig;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 如果配置获取失败,使用默认配置
|
||||
_logger.LogWarning(e, "获取 OCR 配置失败,使用默认配置");
|
||||
return new OtherConfig.Ocr();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 若果配置中没有设置文化信息,则使用默认的文化信息
|
||||
/// 为了单元测试
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private CultureInfo GetCultureInfo()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new CultureInfo(TaskContext.Instance().Config.OtherConfig.GameCultureInfoName);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var result = new CultureInfo(new OtherConfig().GameCultureInfoName);
|
||||
_logger.LogInformation("获取游戏文化信息失败,使用默认文化信息: {CultureInfo}", result.Name);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private PaddleOcrService CreatePaddleOcrInstance()
|
||||
{
|
||||
return _config.PaddleOcrModelConfig switch
|
||||
{
|
||||
PaddleOcrModelConfig.V4Auto =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfoV4(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V4),
|
||||
PaddleOcrModelConfig.V5Auto =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.FromCultureInfo(GetCultureInfo()) ??
|
||||
PaddleOcrService.PaddleOcrModelType.V5),
|
||||
PaddleOcrModelConfig.V5 =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5),
|
||||
PaddleOcrModelConfig.V4 =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V4),
|
||||
PaddleOcrModelConfig.V4En =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V4En),
|
||||
PaddleOcrModelConfig.V5Korean =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Korean),
|
||||
PaddleOcrModelConfig.V5Latin =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Latin),
|
||||
PaddleOcrModelConfig.V5Eslav =>
|
||||
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
|
||||
PaddleOcrService.PaddleOcrModelType.V5Eslav),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(_config.PaddleOcrModelConfig),
|
||||
_config.PaddleOcrModelConfig, "不支持的 Paddle OCR 模型配置")
|
||||
OcrEngineTypes.Paddle => new PaddleOcrService(),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
public Task Unload()
|
||||
{
|
||||
if (_paddleOcrService is not IDisposable disposable)
|
||||
{
|
||||
_paddleOcrService = null;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
try
|
||||
{
|
||||
disposable.Dispose();
|
||||
_paddleOcrService = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "卸载 OCR 服务时发生错误");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Unload().GetAwaiter().GetResult();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
~OcrFactory()
|
||||
{
|
||||
Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,68 +1,41 @@
|
||||
using OpenCvSharp;
|
||||
using System.Linq;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a region detected in an OCR result using Paddle OCR.
|
||||
/// Sdcb.PaddleOCR
|
||||
// <summary>
|
||||
/// Represents a region detected in an OCR result using Paddle OCR.
|
||||
/// </summary>
|
||||
public record struct OcrResultRegion(RotatedRect Rect, string Text, float Score);
|
||||
|
||||
public readonly record struct OcrRecognizerResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OcrRecognizerResult" /> struct.
|
||||
/// </summary>
|
||||
/// <param name="text">The recognized text from the image.</param>
|
||||
/// <param name="score">The confidence score of the text recognition.</param>
|
||||
public OcrRecognizerResult(string text, float score)
|
||||
{
|
||||
Text = text;
|
||||
Score = score;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The recognized text from the image.
|
||||
/// </summary>
|
||||
public string Text { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The confidence score of the text recognition.
|
||||
/// </summary>
|
||||
public float Score { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents the OCR result of a paddle object detection model.
|
||||
/// Represents the OCR result of a paddle object detection model.
|
||||
/// </summary>
|
||||
public record OcrResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OcrResult" /> class with the specified <paramref name="Regions" />.
|
||||
/// Initializes a new instance of the <see cref="PaddleOcrResult"/> class with the specified <paramref name="Regions"/>.
|
||||
/// </summary>
|
||||
/// <param name="Regions">An array of <see cref="OcrResultRegion" /> objects representing the detected text regions.</param>
|
||||
/// <param name="Regions">An array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.</param>
|
||||
public OcrResult(OcrResultRegion[] Regions)
|
||||
{
|
||||
this.Regions = Regions;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an array of <see cref="OcrResultRegion" /> objects representing the detected text regions.
|
||||
/// Gets an array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.
|
||||
/// </summary>
|
||||
/// <value>An array of <see cref="OcrResultRegion" /> objects representing the detected text regions.</value>
|
||||
/// <value>An array of <see cref="PaddleOcrResultRegion"/> objects representing the detected text regions.</value>
|
||||
public OcrResultRegion[] Regions { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Concatenates the text from each <see cref="OcrResultRegion" /> object in <see cref="Regions" />
|
||||
/// and returns the resulting string, ordered by the region's center positions.
|
||||
/// Concatenates the text from each <see cref="PaddleOcrResultRegion"/> object in <see cref="Regions"/>
|
||||
/// and returns the resulting string, ordered by the region's center positions.
|
||||
/// </summary>
|
||||
/// <value>
|
||||
/// A string containing the concatenated text from each <see cref="OcrResultRegion" /> object
|
||||
/// in <see cref="Regions" />, ordered by the region's center positions.
|
||||
/// </value>
|
||||
/// <value>A string containing the concatenated text from each <see cref="PaddleOcrResultRegion"/> object
|
||||
/// in <see cref="Regions"/>, ordered by the region's center positions.</value>
|
||||
public string Text => string.Join("\n", Regions
|
||||
.OrderBy(x => x.Rect.Center.Y)
|
||||
.ThenBy(x => x.Rect.Center.X)
|
||||
.Select(x => x.Text));
|
||||
}
|
||||
}
|
||||
@@ -1,200 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <summary>Gets or sets the score threshold for filtering out possible text boxes.</summary>
|
||||
public float? BoxScoreThreshold { get; set; } = 0.7f;
|
||||
|
||||
/// <summary>Gets or sets the threshold to binarize the text region.</summary>
|
||||
public float? BoxThreshold { get; set; } = 0.3f;
|
||||
|
||||
/// <summary>Gets or sets the minimum size of the text boxes to be considered as valid.</summary>
|
||||
public int MinSize { get; set; } = 3;
|
||||
|
||||
/// <summary>Gets or sets the ratio for enlarging text boxes during post-processing.</summary>
|
||||
public float UnclipRatio { get; set; } = 2.0f;
|
||||
|
||||
~Det()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public RotatedRect[] Run(Mat src)
|
||||
{
|
||||
using var pred = RunRaw(src, out var resizedSize);
|
||||
using Mat cbuf = new();
|
||||
//OpenCvSharp.OpenCVException: 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols
|
||||
using var roi = pred[0, resizedSize.Height, 0, resizedSize.Width];
|
||||
roi.ConvertTo(cbuf, MatType.CV_8UC1, 255);
|
||||
using Mat dilated = new();
|
||||
using var binary = BoxThreshold != null
|
||||
? cbuf.Threshold((int)(BoxThreshold * 255), 255, ThresholdTypes.Binary)
|
||||
: cbuf;
|
||||
if (DilatedSize != null)
|
||||
{
|
||||
using var ones =
|
||||
Cv2.GetStructuringElement(MorphShapes.Rect, new Size(DilatedSize.Value, DilatedSize.Value));
|
||||
Cv2.Dilate(binary, dilated, ones);
|
||||
}
|
||||
else
|
||||
{
|
||||
Cv2.CopyTo(binary, dilated);
|
||||
}
|
||||
|
||||
var contours = dilated.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);
|
||||
// var size = src.Size();
|
||||
var scaleRate = 1.0 * src.Width / resizedSize.Width;
|
||||
|
||||
var rects = contours
|
||||
.Where(x => BoxScoreThreshold == null || GetScore(x, pred) > BoxScoreThreshold)
|
||||
.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) * scaleRate,
|
||||
(rect.Size.Height + UnclipRatio * minEdge) * scaleRate);
|
||||
RotatedRect largerRect = new(rect.Center * scaleRate, newSize, rect.Angle);
|
||||
return largerRect;
|
||||
})
|
||||
.OrderBy(v => v.Center.Y)
|
||||
.ThenBy(v => v.Center.X)
|
||||
.ToArray();
|
||||
//{
|
||||
// using Mat demo = dilated.CvtColor(ColorConversionCodes.GRAY2RGB);
|
||||
// demo.DrawContours(contours, -1, Scalar.Red);
|
||||
// Image(demo).Dump();
|
||||
//}
|
||||
return rects;
|
||||
}
|
||||
|
||||
public Mat RunRaw(Mat src, out Size resizedSize)
|
||||
{
|
||||
var padded = 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)")
|
||||
};
|
||||
// DetResizeForTest resize_long
|
||||
using (var resized = MatResize(padded, MaxSize))
|
||||
{
|
||||
resizedSize = new Size(resized.Width, resized.Height);
|
||||
padded = MatPadding32(resized);
|
||||
}
|
||||
|
||||
using (var _ = padded)
|
||||
{
|
||||
var inputTensor = OcrUtils.NormalizeToTensorDnn(padded, config.NormalizeImage.Scale,
|
||||
config.NormalizeImage.Mean, config.NormalizeImage.Std, out var owner);
|
||||
using (owner)
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
var output = results[0];
|
||||
if (output.ElementType is not TensorElementType.Float)
|
||||
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
|
||||
|
||||
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
|
||||
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
|
||||
var outputTensor = output.AsTensor<float>();
|
||||
return OcrUtils.Tensor2Mat(outputTensor);
|
||||
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Mat MatPadding32(Mat src)
|
||||
{
|
||||
var size = src.Size();
|
||||
Size newSize = new(
|
||||
32 * Math.Ceiling(1.0 * size.Width / 32),
|
||||
32 * Math.Ceiling(1.0 * size.Height / 32));
|
||||
return src.CopyMakeBorder(0, newSize.Height - size.Height, 0, newSize.Width - size.Width, BorderTypes.Constant,
|
||||
Scalar.Black);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按比例缩放图像,保持长边不超过 maxSize。
|
||||
/// </summary>
|
||||
/// <param name="src"></param>
|
||||
/// <param name="maxSize"></param>
|
||||
/// <returns></returns>
|
||||
private static Mat MatResize(Mat src, int? maxSize)
|
||||
{
|
||||
if (maxSize == null) return src.Clone();
|
||||
|
||||
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)
|
||||
{
|
||||
var width = pred.Width;
|
||||
var height = pred.Height;
|
||||
var boxX = contour.Select(v => v.X).ToArray();
|
||||
var boxY = contour.Select(v => v.Y).ToArray();
|
||||
|
||||
var xmin = Math.Clamp(boxX.Min(), 0, width - 1);
|
||||
var xmax = Math.Clamp(boxX.Max(), 0, width - 1);
|
||||
var ymin = Math.Clamp(boxY.Min(), 0, height - 1);
|
||||
var ymax = Math.Clamp(boxY.Max(), 0, height - 1);
|
||||
|
||||
var rootPoints = contour
|
||||
.Select(v => new Point(v.X - xmin, v.Y - ymin))
|
||||
.ToArray();
|
||||
using Mat mask = new(ymax - ymin + 1, xmax - xmin + 1, MatType.CV_8UC1, Scalar.Black);
|
||||
mask.FillPoly(new[] { rootPoints }, new Scalar(1));
|
||||
|
||||
using var croppedMat = pred[ymin, ymax + 1, xmin, xmax + 1];
|
||||
var score = (float)croppedMat.Mean(mask).Val0;
|
||||
|
||||
// Debug
|
||||
//{
|
||||
// using Mat cu = new Mat();
|
||||
// croppedMat.ConvertTo(cu, MatType.CV_8UC1, 255);
|
||||
// Util.HorizontalRun(true, Image(cu), Image(mask), score).Dump();
|
||||
//}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
public string GetConfigName => config.Name;
|
||||
}
|
||||
@@ -1,357 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using OpenCvSharp;
|
||||
using OpenCvSharp.Extensions;
|
||||
using YamlDotNet.Core;
|
||||
using YamlDotNet.Core.Events;
|
||||
using Size = OpenCvSharp.Size;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class PaddleOcrService : IOcrService, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Usage:
|
||||
/// https://github.com/sdcb/PaddleSharp/blob/master/docs/ocr.md
|
||||
/// 模型列表:
|
||||
/// https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.5/doc/doc_ch/models_list.md
|
||||
/// </summary>
|
||||
private readonly Det _localDetModel;
|
||||
|
||||
private readonly Rec _localRecModel;
|
||||
|
||||
public record PaddleOcrModelType(
|
||||
BgiOnnxModel DetectionModel,
|
||||
OcrVersionConfig DetectionVersion,
|
||||
BgiOnnxModel RecognitionModel,
|
||||
OcrVersionConfig RecognitionVersion,
|
||||
Func<IReadOnlyList<string>> RecLabel,
|
||||
String PreHeatImagePath
|
||||
)
|
||||
{
|
||||
public static string TestImagePath = Global.Absolute(@"Assets\Model\PaddleOCR\test_pp_ocr.png");
|
||||
|
||||
public static string TestNumberImagePath =
|
||||
Global.Absolute(@"Assets\Model\PaddleOCR\test_pp_ocr_number.png");
|
||||
|
||||
private static readonly Func<BgiOnnxModel, IReadOnlyList<string>> DefaultRecLabelFunc =
|
||||
recModel =>
|
||||
{
|
||||
const string modelConfigFileName = "inference.yml";
|
||||
var configFilePath = Path.Combine(
|
||||
Path.GetDirectoryName(recModel.ModalPath) ??
|
||||
throw new InvalidOperationException("Cannot get model directory"),
|
||||
modelConfigFileName);
|
||||
|
||||
if (!File.Exists(configFilePath))
|
||||
throw new FileNotFoundException(
|
||||
$"PaddleOCR config file {modelConfigFileName} not found: {configFilePath}");
|
||||
|
||||
using var reader = new StreamReader(configFilePath);
|
||||
var parser = new Parser(reader);
|
||||
|
||||
// Traverse YAML to find PostProcess:character_dict
|
||||
while (parser.MoveNext())
|
||||
{
|
||||
if (parser.Current is not YamlDotNet.Core.Events.Scalar { Value: "PostProcess" }) continue;
|
||||
parser.MoveNext(); // Should be MappingStart
|
||||
while (parser.MoveNext())
|
||||
{
|
||||
if (parser.Current is not YamlDotNet.Core.Events.Scalar { Value: "character_dict" }) continue;
|
||||
parser.MoveNext(); // Should be SequenceStart
|
||||
var result = new List<string>();
|
||||
while (parser.MoveNext())
|
||||
{
|
||||
switch (parser.Current)
|
||||
{
|
||||
case SequenceEnd:
|
||||
return result;
|
||||
case YamlDotNet.Core.Events.Scalar charScalar:
|
||||
result.Add(charScalar.Value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("未在 YAML 的 PostProcess 部分找到 character_dict。");
|
||||
};
|
||||
|
||||
|
||||
private static PaddleOcrModelType Create(
|
||||
BgiOnnxModel detectionModel,
|
||||
OcrVersionConfig detectionVersion,
|
||||
BgiOnnxModel recognitionModel,
|
||||
OcrVersionConfig recognitionVersion,
|
||||
String? preHeatImagePath = null,
|
||||
Func<IReadOnlyList<string>>? recLabel = null
|
||||
)
|
||||
{
|
||||
return new PaddleOcrModelType(
|
||||
detectionModel,
|
||||
detectionVersion,
|
||||
recognitionModel,
|
||||
recognitionVersion,
|
||||
recLabel ?? (() => DefaultRecLabelFunc(recognitionModel)),
|
||||
TestImagePath);
|
||||
}
|
||||
|
||||
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
|
||||
{
|
||||
return (
|
||||
new Det(DetectionModel, DetectionVersion, onnxFactory),
|
||||
new Rec(RecognitionModel, RecLabel(), RecognitionVersion, onnxFactory));
|
||||
}
|
||||
|
||||
public static readonly PaddleOcrModelType V4 = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV4,
|
||||
OcrVersionConfig.PpOcrV4,
|
||||
BgiOnnxModel.PaddleOcrRecV4,
|
||||
OcrVersionConfig.PpOcrV4);
|
||||
|
||||
public static readonly PaddleOcrModelType V4En = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV4,
|
||||
OcrVersionConfig.PpOcrV4,
|
||||
BgiOnnxModel.PaddleOcrRecV4En,
|
||||
OcrVersionConfig.PpOcrV4,
|
||||
TestNumberImagePath);
|
||||
|
||||
public static readonly PaddleOcrModelType V5 = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV5,
|
||||
OcrVersionConfig.PpOcrV5,
|
||||
BgiOnnxModel.PaddleOcrRecV5,
|
||||
OcrVersionConfig.PpOcrV5);
|
||||
|
||||
public static readonly PaddleOcrModelType V5Latin = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV5,
|
||||
OcrVersionConfig.PpOcrV5,
|
||||
BgiOnnxModel.PaddleOcrRecV5Latin,
|
||||
OcrVersionConfig.PpOcrV5);
|
||||
|
||||
public static readonly PaddleOcrModelType V5Eslav = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV5,
|
||||
OcrVersionConfig.PpOcrV5,
|
||||
BgiOnnxModel.PaddleOcrRecV5Eslav,
|
||||
OcrVersionConfig.PpOcrV5);
|
||||
|
||||
public static readonly PaddleOcrModelType V5Korean = Create(
|
||||
BgiOnnxModel.PaddleOcrDetV5,
|
||||
OcrVersionConfig.PpOcrV5,
|
||||
BgiOnnxModel.PaddleOcrRecV5Korean,
|
||||
OcrVersionConfig.PpOcrV5);
|
||||
|
||||
/// <summary>
|
||||
/// 这边多语言部分写的比较丑陋,但是能跑。可以根据PP-OCR的语言列表来优化。
|
||||
/// </summary>
|
||||
/// <param name="cultureInfo"></param>
|
||||
/// <returns></returns>
|
||||
public static PaddleOcrModelType? FromCultureInfo(CultureInfo cultureInfo)
|
||||
{
|
||||
HashSet<string> eslavLangs = new(StringComparer.OrdinalIgnoreCase)
|
||||
{ "ru", "be", "uk" };
|
||||
HashSet<string> latinLangs = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"af", "az", "bs", "cs", "cy", "da", "de", "es", "et", "fr", "ga", "hr", "hu", "id", "is", "it", "ku",
|
||||
"la",
|
||||
"lt", "lv", "mi", "ms", "mt", "nl", "no", "oc", "pi", "pl", "pt", "ro", "rs_latin", "sk", "sl", "sq",
|
||||
"sv",
|
||||
"sw", "tl", "tr", "uz", "vi", "french", "german"
|
||||
};
|
||||
HashSet<string> ocrV5Langs = new(StringComparer.OrdinalIgnoreCase)
|
||||
{ "zh", "chi", "zho", "en", "japan", "jp" };
|
||||
// HashSet<string> SPECIAL_LANGS = new(StringComparer.OrdinalIgnoreCase)
|
||||
// { "ch", "chinese_cht", "en", "japan", "korean" };
|
||||
|
||||
List<string> names =
|
||||
[
|
||||
cultureInfo.EnglishName.ToLowerInvariant(), cultureInfo.Name.ToLowerInvariant(),
|
||||
cultureInfo.ThreeLetterISOLanguageName.ToLowerInvariant(),
|
||||
cultureInfo.TwoLetterISOLanguageName.ToLowerInvariant()
|
||||
];
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (name.Equals("korean") || name.Equals("ko"))
|
||||
{
|
||||
return V5Korean;
|
||||
}
|
||||
|
||||
if (eslavLangs.Contains(name))
|
||||
{
|
||||
return V5Eslav;
|
||||
}
|
||||
|
||||
if (latinLangs.Contains(name))
|
||||
{
|
||||
return V5Latin;
|
||||
}
|
||||
|
||||
if (ocrV5Langs.Contains(name))
|
||||
{
|
||||
return V5;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 中英文优先使用V4模型,其他语言使用V5模型
|
||||
/// </summary>
|
||||
/// <param name="cultureInfo"></param>
|
||||
/// <returns></returns>
|
||||
public static PaddleOcrModelType? FromCultureInfoV4(CultureInfo cultureInfo)
|
||||
{
|
||||
var v5 = FromCultureInfo(cultureInfo);
|
||||
// 如果用的是v5, 那么优先用V4的细分模型
|
||||
if (v5 == V5)
|
||||
{
|
||||
List<string> names =
|
||||
[
|
||||
cultureInfo.EnglishName.ToLowerInvariant(), cultureInfo.Name.ToLowerInvariant(),
|
||||
cultureInfo.ThreeLetterISOLanguageName.ToLowerInvariant(),
|
||||
cultureInfo.TwoLetterISOLanguageName.ToLowerInvariant()
|
||||
];
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (name.Equals("en"))
|
||||
{
|
||||
return V4En;
|
||||
}
|
||||
else if (name.Equals("zh-hant") || name.Equals("zh-tw") || name.Equals("zh-hk"))
|
||||
{
|
||||
return V5;
|
||||
}
|
||||
}
|
||||
|
||||
return V4;
|
||||
}
|
||||
else
|
||||
{
|
||||
return v5;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public PaddleOcrService(BgiOnnxFactory bgiOnnxFactory, PaddleOcrModelType modelType)
|
||||
{
|
||||
var (modelsDet, modelsRec) = modelType.Build(bgiOnnxFactory);
|
||||
_localDetModel = modelsDet;
|
||||
_localRecModel = modelsRec;
|
||||
|
||||
// 预热模型
|
||||
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
|
||||
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
|
||||
// Debug输出结果
|
||||
var preHeatResult = RunAll(preHeatImageMat, 1);
|
||||
Debug.WriteLine(
|
||||
$"PaddleOcrService 预热完成,使用模型: {modelType.DetectionModel.Name} 和 {modelType.RecognitionModel.Name},结果: {preHeatResult.Text}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推荐传入三通道BGR mat,虽然四通道和单通道也做了兼容,但是三通道最快
|
||||
/// </summary>
|
||||
public string Ocr(Mat mat)
|
||||
{
|
||||
return OcrResult(mat).Text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推荐传入三通道BGR mat,虽然四通道和单通道也做了兼容,但是三通道最快
|
||||
/// </summary>
|
||||
public OcrResult OcrResult(Mat mat)
|
||||
{
|
||||
if (mat.Channels() == 4)
|
||||
{
|
||||
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
|
||||
return _OcrResult(mat3);
|
||||
}
|
||||
|
||||
return _OcrResult(mat);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推荐传入三通道BGR mat,虽然四通道和单通道也做了兼容,但是三通道最快
|
||||
/// </summary>
|
||||
public string OcrWithoutDetector(Mat mat)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var str = _localRecModel.Run(mat).Text;
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
|
||||
return str;
|
||||
}
|
||||
|
||||
private OcrResult _OcrResult(Mat mat)
|
||||
{
|
||||
var startTime = Stopwatch.GetTimestamp();
|
||||
var result = RunAll(mat);
|
||||
var time = Stopwatch.GetElapsedTime(startTime);
|
||||
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推荐传入三通道BGR mat,虽然四通道和单通道也做了兼容,但是三通道最快
|
||||
/// </summary>
|
||||
private OcrResult RunAll(Mat src, int recognizeBatchSize = 0)
|
||||
{
|
||||
var rects = _localDetModel.Run(src);
|
||||
Mat[] mats =
|
||||
rects.Select(rect =>
|
||||
{
|
||||
var roi = src[GetCropedRect(rect.BoundingRect(), src.Size())];
|
||||
return roi;
|
||||
})
|
||||
.ToArray();
|
||||
try
|
||||
{
|
||||
return new OcrResult(_localRecModel.Run(mats, recognizeBatchSize)
|
||||
.Select((result, i) => new OcrResultRegion(rects[i], result.Text, result.Score))
|
||||
.ToArray());
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var mat in mats) mat.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cropped region of the source image specified by the given rectangle, clamping the rectangle coordinates to
|
||||
/// the image bounds.
|
||||
/// </summary>
|
||||
/// <param name="rect">The rectangle to crop.</param>
|
||||
/// <param name="size">The size of the source image.</param>
|
||||
/// <returns>The cropped rectangle.</returns>
|
||||
private static Rect GetCropedRect(Rect rect, Size size)
|
||||
{
|
||||
return Rect.FromLTRB(
|
||||
Math.Clamp(rect.Left, 0, size.Width),
|
||||
Math.Clamp(rect.Top, 0, size.Height),
|
||||
Math.Clamp(rect.Right, 0, size.Width),
|
||||
Math.Clamp(rect.Bottom, 0, size.Height));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_localDetModel.Dispose();
|
||||
_localRecModel.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回(DetConfigName, RecConfigName)
|
||||
/// </summary>
|
||||
public (string, string) GetConfigName
|
||||
{
|
||||
get
|
||||
{
|
||||
return (this._localDetModel.GetConfigName, this._localRecModel.GetConfigName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
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;
|
||||
using BetterGenshinImpact.Core.Recognition.ONNX;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
using Microsoft.ML.OnnxRuntime.Tensors;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR.Paddle;
|
||||
|
||||
public class Rec(
|
||||
BgiOnnxModel model,
|
||||
IReadOnlyList<string> labels,
|
||||
OcrVersionConfig config,
|
||||
BgiOnnxFactory bgiOnnxFactory)
|
||||
: IDisposable
|
||||
{
|
||||
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
|
||||
|
||||
// _labels = File.ReadAllLines(labelFilePath);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
|
||||
~Rec()
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
_session.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Run OCR recognition on multiple images in batches.
|
||||
/// </summary>
|
||||
/// <param name="srcs">Array of images for OCR recognition.</param>
|
||||
/// <param name="batchSize">Size of the batch to run OCR recognition on.</param>
|
||||
/// <returns>Array of <see cref="OcrRecognizerResult" /> instances corresponding to OCR recognition results of the images.</returns>
|
||||
public OcrRecognizerResult[] Run(Mat[] srcs, int batchSize = 0)
|
||||
{
|
||||
if (srcs.Length == 0) return [];
|
||||
|
||||
var chooseBatchSize = batchSize != 0 ? batchSize : Math.Min(8, Environment.ProcessorCount);
|
||||
|
||||
return srcs
|
||||
.Select((x, i) => (mat: x, i))
|
||||
.OrderBy(x => x.mat.Width)
|
||||
.Chunk(chooseBatchSize)
|
||||
.Select(x => (result: RunMulti(x.Select(x1 => x1.mat).ToArray()), ids: x.Select(x1 => x1.i).ToArray()))
|
||||
.SelectMany(x => x.result.Zip(x.ids, (result, i) => (result, i)))
|
||||
.OrderBy(x => x.i)
|
||||
.Select(x => x.result)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
public OcrRecognizerResult Run(Mat src)
|
||||
{
|
||||
return RunMulti([src]).Single();
|
||||
}
|
||||
|
||||
private OcrRecognizerResult[] RunMulti(Mat[] srcs)
|
||||
{
|
||||
if (srcs.Length == 0) return [];
|
||||
|
||||
for (var i = 0; i < srcs.Length; ++i)
|
||||
{
|
||||
var src = srcs[i];
|
||||
if (src.Empty())
|
||||
throw new ArgumentException($"src[{i}] size should not be 0, wrong input picture provided?");
|
||||
}
|
||||
|
||||
var modelHeight = config.Shape.Height;
|
||||
var maxWidth = (int)Math.Ceiling(srcs.Max(src =>
|
||||
{
|
||||
var size = src.Size();
|
||||
return 1.0 * size.Width / size.Height * modelHeight;
|
||||
}));
|
||||
List<IMemoryOwner<float>> owners = [];
|
||||
(int[], float[])[] resultTensors;
|
||||
try
|
||||
{
|
||||
resultTensors = srcs
|
||||
// .AsParallel()
|
||||
.Select(src =>
|
||||
{
|
||||
using var channel3 = src.Channels() switch
|
||||
{
|
||||
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
|
||||
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
|
||||
3 => src,
|
||||
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
|
||||
};
|
||||
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
|
||||
out var owner);
|
||||
lock (owners)
|
||||
{
|
||||
owners.Add(owner);
|
||||
}
|
||||
|
||||
return result;
|
||||
})
|
||||
.Select(inputTensor =>
|
||||
{
|
||||
lock (_session)
|
||||
{
|
||||
// 多线程推理会出现问题,加锁解决。
|
||||
using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = _session.Run([
|
||||
NamedOnnxValue.CreateFromTensor(_session.InputNames[0], inputTensor)
|
||||
]);
|
||||
var output = results[0];
|
||||
if (output.ElementType is not TensorElementType.Float)
|
||||
throw new Exception($"Unexpected output tensor type: {output.ElementType}");
|
||||
|
||||
if (output.ValueType is not OnnxValueType.ONNX_TYPE_TENSOR)
|
||||
throw new Exception($"Unexpected output tensor value type: {output.ValueType}");
|
||||
var tensor = output.AsTensor<float>();
|
||||
// 因为一个已知bug,tensor中内存在dml下使用完后会被释放掉,锁之外的代码会报错
|
||||
return (tensor.Dimensions.ToArray(), tensor.ToArray());
|
||||
}
|
||||
}
|
||||
).ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
owners.ForEach(x => { x.Dispose(); });
|
||||
}
|
||||
|
||||
return resultTensors.SelectMany(resultTensor =>
|
||||
{
|
||||
var resultArray = resultTensor.Item2;
|
||||
var resultShape = resultTensor.Item1;
|
||||
GCHandle dataHandle = default;
|
||||
try
|
||||
{
|
||||
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
|
||||
var dataPtr = dataHandle.AddrOfPinnedObject();
|
||||
var labelCount = resultShape[2];
|
||||
var charCount = resultShape[1];
|
||||
|
||||
return Enumerable.Range(0, resultShape[0])
|
||||
.Select(i =>
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
var lastIndex = 0;
|
||||
float score = 0;
|
||||
for (var n = 0; n < charCount; ++n)
|
||||
{
|
||||
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
|
||||
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
|
||||
var maxIdx = new int[2];
|
||||
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
|
||||
|
||||
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
|
||||
{
|
||||
score += (float)maxVal;
|
||||
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
|
||||
}
|
||||
|
||||
lastIndex = maxIdx[1];
|
||||
}
|
||||
|
||||
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
|
||||
})
|
||||
.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
dataHandle.Free();
|
||||
}
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
public string GetConfigName => config.Name;
|
||||
}
|
||||
+21
-10
@@ -1,10 +1,10 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.GameTask.AutoSkip.Model;
|
||||
using BetterGenshinImpact.View.Drawable;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
@@ -12,27 +12,39 @@ public static class OcrResultExtension
|
||||
{
|
||||
public static bool RegionHasText(this OcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (ref readonly var item in result.Regions.AsSpan())
|
||||
foreach (ref readonly OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static OcrResultRegion FindRegionByText(this OcrResult result, ReadOnlySpan<char> text)
|
||||
{
|
||||
foreach (ref readonly var item in result.Regions.AsSpan())
|
||||
foreach (ref readonly OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.AsSpan().Contains(text, StringComparison.InvariantCulture))
|
||||
{
|
||||
return item;
|
||||
}
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
|
||||
public static Rect FindRectByText(this OcrResult result, string text)
|
||||
{
|
||||
foreach (ref var item in result.Regions.AsSpan())
|
||||
foreach (ref OcrResultRegion item in result.Regions.AsSpan())
|
||||
{
|
||||
if (item.Text.Contains(text))
|
||||
{
|
||||
return item.Rect.BoundingRect();
|
||||
}
|
||||
}
|
||||
|
||||
return default;
|
||||
}
|
||||
@@ -42,8 +54,7 @@ public static class OcrResultExtension
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(pen)).ToList();
|
||||
}
|
||||
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this OcrResult result, int offsetX, int offsetY,
|
||||
Pen? pen = null)
|
||||
public static List<RectDrawable> ToRectDrawableListOffset(this OcrResult result, int offsetX, int offsetY, Pen? pen = null)
|
||||
{
|
||||
return result.Regions.Select(item => item.Rect.BoundingRect().ToRectDrawable(offsetX, offsetY, pen)).ToList();
|
||||
}
|
||||
@@ -52,4 +63,4 @@ public static class OcrResultExtension
|
||||
{
|
||||
return new PaddleOcrResultRect(region.Rect.BoundingRect(), region.Text, region.Score);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1583 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user