Compare commits

...
58 Commits
Author SHA1 Message Date
辉鸭蛋 fe2fd5d67c fix merge 2024-05-28 18:02:56 +08:00
辉鸭蛋 08fbd6e2a2 +main 2024-05-28 10:28:16 +08:00
辉鸭蛋 e1f3b01eb1 add icon in mask window 2024-05-28 01:20:59 +08:00
辉鸭蛋 0973ca0887 use new icon 2024-05-28 01:08:42 +08:00
ema be4039a77a Update TriggerSettingsPage.xaml 2024-05-27 23:33:28 +08:00
ema 684fac7d29 fix style about CardExpander 2024-05-27 23:04:55 +08:00
辉鸭蛋 5c6a96957e add new icon font 2024-05-27 22:28:32 +08:00
ema 56477f3490 use font in mask window 2024-05-26 21:23:22 +08:00
辉鸭蛋 95757a5ed6 test PostMessage 2024-05-26 19:14:44 +08:00
ema c4eae50716 fix: hide mask window from Alt+Tab 2024-05-26 19:10:10 +08:00
ema 6da76f4ef7 Update README.md 2024-05-26 18:09:40 +08:00
辉鸭蛋 443f79bde3 Update README.md 2024-05-26 09:29:33 +08:00
辉鸭蛋 57e24c8e33 update readme 2024-05-25 20:10:02 +08:00
辉鸭蛋 edff49c9cb fix #394 2024-05-25 11:15:36 +08:00
辉鸭蛋 594b517936 0.30.2 2024-05-25 11:00:56 +08:00
辉鸭蛋 5f35d483c2 remove system version judgment #394 2024-05-25 11:00:30 +08:00
辉鸭蛋 b8e5c179fc fix the performance of mask windows at different resolutions - 0.30.1 2024-05-24 12:13:51 +08:00
辉鸭蛋 c5d9930a3d 0.30.0 2024-05-23 17:51:36 +08:00
辉鸭蛋 a84c94c5ce add auto cook #266 2024-05-23 00:27:13 +08:00
辉鸭蛋 a801bb2c4f modify home page text 2024-05-22 23:32:12 +08:00
辉鸭蛋 cb106db75f use 2048 block map 2024-05-22 15:38:13 +08:00
辉鸭蛋 772ab1b7e6 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-05-21 00:18:53 +08:00
辉鸭蛋 92be667328 big map tp 2024-05-21 00:18:44 +08:00
ema cb75cf8338 update: OSVERSIONINFOEX 2024-05-20 21:20:46 +08:00
辉鸭蛋 4bf5001a2c WindowsGraphicsCapture only support Windows 10 version 1903 or later #394 2024-05-20 11:56:04 +08:00
辉鸭蛋 6ffe7a670c prevent computer screen shutdown during auto wood #387 2024-05-19 21:28:49 +08:00
辉鸭蛋 54b669de90 press two esc to close tips #235 2024-05-19 21:18:04 +08:00
辉鸭蛋 65acb852f3 add enable switch for #398 2024-05-19 20:59:54 +08:00
辉鸭蛋 c014284b84 add auto fight strategy 2024-05-19 20:21:23 +08:00
辉鸭蛋 cf16969ea0 Merge pull request #398 from atiasn/wood-count 2024-05-18 23:03:38 +08:00
辉鸭蛋 89e505f4a5 fix capture mod for one key marco #396 2024-05-18 22:28:54 +08:00
辉鸭蛋 c686c4a4a6 fix automatic fishing bait selection error for multiple bait fishing points #396 2024-05-18 22:16:09 +08:00
辉鸭蛋 3cc313c204 fix incorrect auto tcg file names 2024-05-18 22:03:18 +08:00
atiasn 9e3d16c819 check wood 2024-05-17 21:57:53 +08:00
atiasn 8513c9ed4f return ocr 2024-05-16 19:40:27 +08:00
Atiasn bb3941d9f5 get best ocr 2024-05-16 18:12:59 +08:00
atiasn 66d1791218 Merge branch 'main' into wood-count 2024-05-16 01:00:04 +08:00
atiasn 27e6de0fbf delete indexOf 2024-05-16 00:59:17 +08:00
ema cb9dc4ca2e UI/UX: use MiSans-Regular as TextThemeFontFamily 2024-05-15 20:26:55 +08:00
NextKale cc16a60896 delete 2024-05-15 00:36:33 +08:00
atiasn 3792a5f0bf sleep 2024-05-15 00:19:07 +08:00
atiasn fec0e8ec39 wood counts 2024-05-15 00:06:09 +08:00
Atiasn bd4223ddaa wood class 2024-05-14 18:15:20 +08:00
Atiasn 3a35d537b6 woods 2024-05-14 17:06:21 +08:00
atiasn 87a39c95eb 只对首次进行OCR识别 2024-05-14 01:46:27 +08:00
Atiasn fb1eeed107 wood count 2024-05-13 16:40:04 +08:00
atiasn cfe9fc6389 伐木计数 2024-05-13 00:49:29 +08:00
ema 9378a134bd remove: package H.InputSimulator #154 2024-05-12 05:16:27 +08:00
辉鸭蛋 c27b5176e7 16:10 high dpi #373 2024-05-12 00:28:37 +08:00
辉鸭蛋 85e0c827ca fix task not work in 16:10 #373 2024-05-11 23:41:07 +08:00
辉鸭蛋 790c30183b edit ui 2024-05-10 21:07:30 +08:00
辉鸭蛋 6f67bea46c auto music: fix low resolution not work 2024-05-10 20:11:29 +08:00
辉鸭蛋 36dcbebdfa add GPU title flag 2024-04-06 12:00:14 +08:00
辉鸭蛋 ed63a68ee5 add switch inference device UI 2024-04-06 11:57:19 +08:00
辉鸭蛋 f14d4a4d10 Merge branch 'main' into feat-gpu 2024-04-06 11:25:04 +08:00
辉鸭蛋 d69242f7c2 edit onnx version 2024-04-06 11:23:14 +08:00
辉鸭蛋 034d695bf8 all use gpu 2024-04-06 02:43:43 +08:00
辉鸭蛋 4b41fdcecc test gpu 2024-04-06 00:26:55 +08:00
90 changed files with 1516 additions and 592 deletions

No files matched your search

+4 -1
View File
@@ -25,4 +25,7 @@ Tmp/
/packages/
node_modules/
*.zip
*.zip
# Rider
.idea
+6
View File
@@ -50,5 +50,11 @@
Height="23"
Click="GenAvatarData"
Content="生成侧面头像数据集" />
<Button Canvas.Left="10"
Canvas.Top="190"
Width="100"
Height="23"
Click="AutoCookTestCase"
Content="自动烹饪图像测试" />
</Canvas>
</Window>
+7 -1
View File
@@ -47,7 +47,8 @@ public partial class MainWindow : Window
private void DoMatchTest(object sender, System.Windows.RoutedEventArgs e)
{
// KeyPointMatchTest.Test();
EntireMapTest.Test();
// EntireMapTest.Test();
EntireMapTest.Storage();
}
private void MapDrawTeleportPoint(object sender, RoutedEventArgs e)
@@ -59,4 +60,9 @@ public partial class MainWindow : Window
{
AvatarClassifyGen.GenAll();
}
private void AutoCookTestCase(object sender, RoutedEventArgs e)
{
AutoCookTest.Test();
}
}
@@ -1,7 +1,10 @@
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
using OpenCvSharp.Detail;
using System.Diagnostics;
using System.Windows.Forms;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -45,4 +48,10 @@ public class EntireMapTest
}
speedTimer.DebugPrint();
}
public static void Storage()
{
var featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap2048BlockMat.Value, new FeatureStorage("mainMap2048Block"));
MessageBox.Show("特征点生成完成");
}
}
@@ -0,0 +1,17 @@
using OpenCvSharp;
namespace BetterGenshinImpact.Test.Simple;
internal class AutoCookTest
{
public static void Test()
{
var img = new Mat(@"E:\HuiTask\更好的原神\自动烹饪\2.png");
Cv2.CvtColor(img, img, ColorConversionCodes.BGR2RGB);
var img2 = new Mat();
// Cv2.InRange(img, new Scalar(255, 192, 64), new Scalar(255, 192, 64), img2);
Cv2.InRange(img, new Scalar(255, 255, 192), new Scalar(255, 255, 192), img2);
Cv2.ImShow("img", img2);
}
}
+2 -1
View File
@@ -8,8 +8,9 @@
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
<FontFamily x:Key="TextThemeFontFamily">/Assets/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
+7
View File
@@ -57,6 +57,7 @@ public partial class App : Application
{
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());
@@ -227,8 +228,14 @@ public partial class App : Application
private static void HandleException(Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
MessageBox.Show("程序异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
// log
GetLogger<App>().LogDebug(e, "UnHandle Exception");
}
}
Binary file not shown.
Binary file not shown.
+14 -4
View File
@@ -17,6 +17,7 @@
<None Remove="Assets\*.jpg" />
<None Remove="Assets\*.png" />
<None Remove="Assets\*.ico" />
<None Remove="Assets\Fonts\*.ttf" />
<None Remove="Assets\Highlighting\*.xshd" />
</ItemGroup>
@@ -24,17 +25,17 @@
<Resource Include="Assets\*.jpg" />
<Resource Include="Assets\*.png" />
<Resource Include="Assets\*.ico" />
<Resource Include="Assets\Fonts\*.ttf" />
<Resource Include="Assets\Highlighting\*.xshd" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AvalonEdit" Version="6.3.0.90" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="H.InputSimulator" Version="1.4.1" />
<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" Version="1.17.1" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" 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.Extensions" Version="4.8.0.20230708" />
@@ -42,17 +43,19 @@
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.77" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="Sdcb.PaddleInference" Version="2.5.0.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.cuda118_cudnn86_tr85_sm86_89" Version="2.5.1" />
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
<PackageReference Include="Sdcb.PaddleOCR.Models.Online" Version="2.7.0.1" />
<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" />
<PackageReference Include="YoloV8.Gpu" Version="2.0.1" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)' == 'Debug'">
@@ -466,6 +469,12 @@
<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>
@@ -544,7 +553,7 @@
<None Update="User\AutoGeniusInvokation\6.皇女科莱莫娜.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\AutoGeniusInvokation\7.莫娜皇女白术.txt">
<None Update="User\AutoGeniusInvokation\7.莫娜白术皇女.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\AutoGeniusInvokation\8.雷神柯莱刻晴[推荐].txt">
@@ -584,6 +593,7 @@
<ItemGroup>
<Folder Include="GameTask\Common\Element\Assets\MapPoint\" />
<Folder Include="View\Controls\WpfUi\" />
</ItemGroup>
</Project>
+14 -6
View File
@@ -13,6 +13,7 @@ using Fischless.GameCapture;
using System;
using System.ComponentModel;
using System.Text.Json.Serialization;
using BetterGenshinImpact.GameTask.AutoCook;
namespace BetterGenshinImpact.Core.Config;
@@ -40,11 +41,6 @@ public partial class AllConfig : ObservableObject
[ObservableProperty]
private string _notShowNewVersionNoticeEndVersion = "";
///// <summary>
///// 窗口捕获帧数/触发器触发频率
///// </summary>
//[ObservableProperty] private int _frameRate = 30;
/// <summary>
/// 触发器触发频率(ms)
/// </summary>
@@ -59,6 +55,12 @@ public partial class AllConfig : ObservableObject
[ObservableProperty]
private bool _wgcUseBitmapCache = true;
/// <summary>
/// 推理使用的设备
/// </summary>
[ObservableProperty]
private string _inferenceDevice = "CPU";
/// <summary>
/// 遮罩窗口配置
/// </summary>
@@ -90,10 +92,15 @@ public partial class AllConfig : ObservableObject
public AutoFishingConfig AutoFishingConfig { get; set; } = new();
/// <summary>
/// 自动钓鱼配置
/// 快速传送配置
/// </summary>
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
/// <summary>
/// 自动烹饪配置
/// </summary>
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 自动打牌配置
/// </summary>
@@ -145,6 +152,7 @@ public partial class AllConfig : ObservableObject
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
+1 -1
View File
@@ -5,7 +5,7 @@ namespace BetterGenshinImpact.Core.Config;
public class Global
{
public static string Version { get; } = "0.29.3";
public static string Version { get; } = "0.30.2";
public static string StartUpPath { get; set; } = AppContext.BaseDirectory;
@@ -148,4 +148,18 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _autoMusicGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动寻路
[ObservableProperty]
private string _autoTrackPathHotkey = "";
[ObservableProperty]
private string _autoTrackPathHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 测试
[ObservableProperty]
private string _test1Hotkey = "";
[ObservableProperty]
private string _test1HotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -69,6 +69,11 @@ public partial class MaskWindowConfig : ObservableObject
/// </summary>
public Rect UidCoverRect { get; set; } = new(1690, 1052, 173, 22);
/// <summary>
/// 1080p下UID遮盖的位置与大小
/// </summary>
public Rect UidCoverRightBottomRect { get; set; } = new(1920 - 1690, 1080 - 1052, 173, 22);
public Point EastPoint { get; set; } = new(274, 109);
public Point SouthPoint { get; set; } = new(150, 233);
public Point WestPoint { get; set; } = new(32, 109);
@@ -4,8 +4,10 @@ using Sdcb.PaddleInference;
using Sdcb.PaddleOCR;
using Sdcb.PaddleOCR.Models;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using BetterGenshinImpact.GameTask;
namespace BetterGenshinImpact.Core.Recognition.OCR;
@@ -28,7 +30,13 @@ public class PaddleOcrService : IOcrService
var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
var model = new FullOcrModel(localDetModel, localClsModel, localRecModel);
_paddleOcrAll = new PaddleOcrAll(model, PaddleDevice.Onnx())
Action<PaddleConfig> device = TaskContext.Instance().Config.InferenceDevice switch
{
"CPU" => PaddleDevice.Onnx(),
"GPU" => PaddleDevice.Gpu(),
_ => throw new InvalidEnumArgumentException("无效的推理设备")
};
_paddleOcrAll = new PaddleOcrAll(model, device)
{
AllowRotateDetection = false, /* 允许识别有角度的文字 */
Enable180Classification = false /* 允许识别旋转角度大于90度的文字 */
@@ -0,0 +1,16 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Model;
using Microsoft.ML.OnnxRuntime;
using System.ComponentModel;
namespace BetterGenshinImpact.Core.Recognition.ONNX;
public class BgiSessionOption : Singleton<BgiSessionOption>
{
public SessionOptions Options { get; set; } = TaskContext.Instance().Config.InferenceDevice switch
{
"CPU" => new SessionOptions(),
"GPU" => SessionOptions.MakeSessionOptionWithCudaProvider(),
_ => throw new InvalidEnumArgumentException("无效的推理设备")
};
}
@@ -1,10 +1,12 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -25,11 +27,10 @@ public class PickTextInference : ITextInference
public PickTextInference()
{
var options = new SessionOptions();
var modelPath = Global.Absolute("Assets\\Model\\Yap\\model_training.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("Yap模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, options);
_session = new InferenceSession(modelPath, BgiSessionOption.Instance.Options);
var wordJsonPath = Global.Absolute("Assets\\Model\\Yap\\index_2_word.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
@@ -81,8 +81,10 @@ public class FeatureMatcher
public Point2f[]? Match(Mat queryMat, int prevX, int prevY)
{
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(_trainMat, _splitRow, _splitCol, prevX, prevY);
Debug.WriteLine($"当前坐标({prevX},{prevY})在特征块({cellRow},{cellCol})中");
if (_lastMergedBlock == null || _lastMergedBlock.MergedCenterCellRow != cellRow || _lastMergedBlock.MergedCenterCellCol != cellCol)
{
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(_blocks, _trainRet, cellRow, cellCol);
}
@@ -124,8 +126,8 @@ public class FeatureMatcher
}
}
Debug.WriteLine($"max distance : {maxDistance}");
Debug.WriteLine($"min distance : {minDistance}");
// Debug.WriteLine($"max distance : {maxDistance}");
// Debug.WriteLine($"min distance : {minDistance}");
var pointsQuery = new List<Point2f>();
var pointsTrain = new List<Point2f>();
@@ -45,7 +45,7 @@ public class FeatureStorage(string name)
}
}
public Mat? LoadDescMat()
public Mat? LoadDescMat1()
{
CreateFolder();
// 格式: Surf_336767x128.mat
@@ -71,7 +71,25 @@ public class FeatureStorage(string name)
return new Mat(Convert.ToInt32(rowColPair[0]), Convert.ToInt32(rowColPair[1]), MatType.CV_32FC1, pointer);
}
public void SaveDescMat(Mat descMat)
public Mat? LoadDescMat()
{
CreateFolder();
var files = Directory.GetFiles(rootPath, $"{name}_{TypeName}.mat", SearchOption.AllDirectories);
if (files.Length == 0)
{
return null;
}
else if (files.Length > 1)
{
Debug.WriteLine($"[FeatureSerializer] Found multiple files: {string.Join(", ", files)}");
}
FileStorage fs = new(files[0], FileStorage.Modes.Read);
var mat = fs["desc"]?.ReadMat();
fs.Release();
return mat;
}
public void SaveDescMat1(Mat descMat)
{
CreateFolder();
// 删除旧文件
@@ -86,4 +104,21 @@ public class FeatureStorage(string name)
Marshal.Copy(descMat.Data, bytes, 0, bytes.Length);
File.WriteAllBytes(descPath, ObjectUtils.Serialize(bytes));
}
public void SaveDescMat(Mat descMat)
{
CreateFolder();
// 删除旧文件
var fileName = $"{name}_{TypeName}.mat";
var files = Directory.GetFiles(rootPath, fileName, SearchOption.AllDirectories);
foreach (var file in files)
{
File.Delete(file);
}
var descPath = Path.Combine(rootPath, fileName);
FileStorage fs = new(descPath, FileStorage.Modes.Write);
fs.Write("desc", descMat);
fs.Release();
}
}
@@ -165,26 +165,26 @@ public class KeyPointFeatureBlockHelper
}
}
// /// <summary>
// /// 按行拷贝matches到descriptor
// /// </summary>
// /// <param name="keyPointIndexList">记录了哪些行需要拷贝</param>
// /// <param name="descriptor">拷贝结果</param>
// /// <param name="matches">原始数据</param>
// [Obsolete]
// private static unsafe void InitBlockMat2(IReadOnlyList<int> keyPointIndexList, Mat descriptor, Mat matches)
// {
// int cols = matches.Cols;
// float* ptrDest = (float*)descriptor.DataPointer;
//
// for (int i = 0; i < keyPointIndexList.Count; i++)
// {
// var index = keyPointIndexList[i];
// float* ptrSrcRow = (float*)matches.Ptr(index);
// for (int j = 0; j < cols; j++)
// {
// *(ptrDest + i * cols + j) = ptrSrcRow[j];
// }
// }
// }
/// <summary>
/// 按行拷贝matches到descriptor
/// </summary>
/// <param name="keyPointIndexList">记录了哪些行需要拷贝</param>
/// <param name="descriptor">拷贝结果</param>
/// <param name="matches">原始数据</param>
[Obsolete]
private static unsafe void InitBlockMat2(IReadOnlyList<int> keyPointIndexList, Mat descriptor, Mat matches)
{
int cols = matches.Cols;
float* ptrDest = (float*)descriptor.DataPointer;
for (int i = 0; i < keyPointIndexList.Count; i++)
{
var index = keyPointIndexList[i];
float* ptrSrcRow = (float*)matches.Ptr(index);
for (int j = 0; j < cols; j++)
{
*(ptrDest + i * cols + j) = ptrSrcRow[j];
}
}
}
}
@@ -39,6 +39,23 @@ public class PostMessageSimulator
return this;
}
/// <summary>
/// 指定位置并按下左键
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public PostMessageSimulator LeftButtonClickBackground(int x, int y)
{
User32.PostMessage(_hWnd, User32.WindowMessage.WM_ACTIVATE, 1, 0);
var p = MakeLParam(x, y);
User32.PostMessage(_hWnd, WM_LBUTTONDOWN, 1, p);
Thread.Sleep(100);
User32.PostMessage(_hWnd, WM_LBUTTONUP, 0, p);
return this;
}
public static int MakeLParam(int x, int y) => (y << 16) | (x & 0xFFFF);
public PostMessageSimulator LeftButtonClick()
{
IntPtr p = (16 << 16) | 16;
@@ -1,15 +1,12 @@
using System;
using WindowsInput;
using Fischless.WindowsInput;
using System;
namespace BetterGenshinImpact.Core.Simulator;
public class Simulation
{
[Obsolete]
public static InputSimulator SendInput { get; } = new();
public static Fischless.WindowsInput.InputSimulator SendInputEx { get; } = new();
public static MouseEventSimulator MouseEvent { get; } = new();
public static PostMessageSimulator PostMessage(IntPtr hWnd)
@@ -0,0 +1,54 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System.Linq;
namespace BetterGenshinImpact.GameTask.AutoCook;
public class AutoCookTrigger : ITaskTrigger
{
private readonly ILogger<AutoCookTrigger> _logger = App.GetLogger<AutoCookTrigger>();
public string Name => "自动烹饪";
public bool IsEnabled { get; set; }
public int Priority => 50;
public bool IsExclusive { get; set; }
public void Init()
{
IsEnabled = TaskContext.Instance().Config.AutoCookConfig.Enabled;
IsExclusive = false;
}
public void OnCapture(CaptureContent content)
{
// 判断是否处于烹饪界面
IsExclusive = false;
content.CaptureRectArea.Find(ElementAssets.Instance.UiLeftTopCookIcon, _ =>
{
IsExclusive = true;
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
using var region = content.CaptureRectArea.DeriveCrop(0, captureRect.Height / 2, captureRect.Width, captureRect.Height / 2);
var perfectBarRects = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 192, 64), 0, 8);
if (perfectBarRects.Count >= 2)
{
// 点击烹饪按钮
var btnList = ContoursHelper.FindSpecifyColorRects(region.SrcMat, new Scalar(255, 255, 192), 12, 12);
if (btnList.Count >= 1)
{
if (btnList.Count > 1)
{
_logger.LogWarning("自动烹饪:{Text}", "识别到多个结束烹饪按钮");
btnList = [.. btnList.OrderByDescending(r => r.Width)];
}
var btn = btnList[0];
var x = btn.X + btn.Width / 2;
var y = btn.Y + btn.Height / 2;
region.ClickTo(x, y);
_logger.LogInformation("自动烹饪:{Text}", "点击结束按钮");
}
}
});
}
}
@@ -0,0 +1,17 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
namespace BetterGenshinImpact.GameTask.AutoCook;
/// <summary>
///自动烹饪配置
/// </summary>
[Serializable]
public partial class AutoCookConfig : ObservableObject
{
/// <summary>
/// 触发器是否启用
/// </summary>
[ObservableProperty]
private bool _enabled = false;
}
@@ -1,5 +1,6 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
@@ -36,7 +37,7 @@ public class AutoDomainTask
private readonly PostMessageSimulator _simulator;
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"));
private readonly YoloV8 _predictor;
private readonly AutoDomainConfig _config;
@@ -47,7 +48,7 @@ public class AutoDomainTask
_taskParam = taskParam;
_simulator = AutoFightContext.Instance.Simulator;
_config = TaskContext.Instance().Config.AutoDomainConfig;
_predictor = new(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"), BgiSessionOption.Instance.Options);
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
}
@@ -191,7 +192,7 @@ public class AutoDomainTask
using var fRectArea = GetRectAreaFromDispatcher().Find(AutoPickAssets.Instance.FRo);
if (!fRectArea.IsEmpty())
{
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
Sleep(5000, _taskParam.Cts);
@@ -254,7 +255,7 @@ public class AutoDomainTask
// 组合键好像不能直接用 postmessage
if (!_config.WalkToF)
{
Simulation.SendInputEx.Keyboard.KeyDown(VK.VK_SHIFT);
Simulation.SendInput.Keyboard.KeyDown(VK.VK_SHIFT);
}
try
@@ -269,7 +270,7 @@ public class AutoDomainTask
else
{
Logger.LogInformation("检测到交互键");
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
break;
}
}
@@ -280,7 +281,7 @@ public class AutoDomainTask
Sleep(50);
if (!_config.WalkToF)
{
Simulation.SendInputEx.Keyboard.KeyUp(VK.VK_SHIFT);
Simulation.SendInput.Keyboard.KeyUp(VK.VK_SHIFT);
}
}
});
@@ -399,7 +400,7 @@ public class AutoDomainTask
CancellationTokenSource treeCts = new CancellationTokenSource();
_taskParam.Cts.Token.Register(treeCts.Cancel);
// 中键回正视角
Simulation.SendInputEx.Mouse.MiddleButtonClick();
Simulation.SendInput.Mouse.MiddleButtonClick();
Sleep(900, _taskParam.Cts);
// 左右移动直到石化古树位于屏幕中心任务
@@ -612,7 +613,7 @@ public class AutoDomainTask
moveAngle *= 2;
}
Simulation.SendInputEx.Mouse.MoveMouseBy(-moveAngle, 0);
Simulation.SendInput.Mouse.MoveMouseBy(-moveAngle, 0);
continuousCount = 0;
}
else if (angle is > 180 and < 360)
@@ -624,7 +625,7 @@ public class AutoDomainTask
moveAngle *= 2;
}
Simulation.SendInputEx.Mouse.MoveMouseBy(moveAngle, 0);
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
continuousCount = 0;
}
else
@@ -108,9 +108,9 @@ public class Avatar
using var confirmRectArea = region.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
Sleep(600, Cts);
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_M);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
throw new Exception("存在角色被击败,按 M 键打开地图,并停止自动秘境。");
}
}
@@ -260,7 +260,7 @@ public class Avatar
Sleep(300, Cts);
for (int j = 0; j < 10; j++)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(1000, 0);
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
Sleep(50); // 持续操作不应该被cts取消
}
@@ -419,7 +419,7 @@ public class Avatar
/// <param name="pixelDeltaY"></param>
public void MoveCamera(int pixelDeltaX, int pixelDeltaY)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(pixelDeltaX, pixelDeltaY);
Simulation.SendInput.Mouse.MoveMouseBy(pixelDeltaX, pixelDeltaY);
}
/// <summary>
@@ -459,7 +459,7 @@ public class Avatar
return;
}
Simulation.SendInputEx.Mouse.MoveMouseBy(1000, 0);
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
ms -= 50;
Sleep(50); // 持续操作不应该被cts取消
}
@@ -527,7 +527,7 @@ public class Avatar
public void MoveBy(int x, int y)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(x, y);
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
}
public void KeyDown(string key)
@@ -10,6 +10,7 @@ using System.Threading;
using BetterGenshinImpact.Core.Config;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.Service;
using Microsoft.Extensions.Logging;
@@ -127,6 +128,14 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
/// </summary>
private Task FightTask(CancellationTokenSource cts)
{
// 切换截图模式
var dispatcherCaptureMode = TaskTriggerDispatcher.Instance().GetCacheCaptureMode();
if (dispatcherCaptureMode != DispatcherCaptureModeEnum.CacheCaptureWithTrigger)
{
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.CacheCaptureWithTrigger);
Sleep(TaskContext.Instance().Config.TriggerInterval * 2, cts); // 等待缓存图像
}
var imageRegion = GetRectAreaFromDispatcher();
var combatScenes = new CombatScenes().InitializeTeam(imageRegion);
if (!combatScenes.CheckTeamInitialized())
@@ -1,6 +1,7 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFishing.Assets;
@@ -35,7 +36,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
private readonly ILogger<AutoFishingTrigger> _logger = App.GetLogger<AutoFishingTrigger>();
private readonly IOcrService _ocrService = OcrFactory.Paddle;
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx"));
private readonly YoloV8 _predictor = new(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx"), BgiSessionOption.Instance.Options);
public string Name => "自动钓鱼";
public bool IsEnabled { get; set; }
@@ -273,18 +274,18 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
// 往左移动是正数,往右移动是负数
if (fishpond.FishpondRect.Left > centerX)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(100, 0);
Simulation.SendInput.Mouse.MoveMouseBy(100, 0);
}
if (fishpond.FishpondRect.Right < centerX)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(-100, 0);
Simulation.SendInput.Mouse.MoveMouseBy(-100, 0);
}
// 鱼塘尽量在上半屏幕
if (fishpond.FishpondRect.Bottom > centerY)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(0, -100);
Simulation.SendInput.Mouse.MoveMouseBy(0, -100);
}
if ((fishpond.FishpondRect.Left < centerX && fishpond.FishpondRect.Right > centerX && fishpond.FishpondRect.Bottom >= centerY) || fishpond.FishpondRect.Width < content.CaptureRectArea.SrcBitmap.Width / 4)
@@ -322,7 +323,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
// 30s 没有上钩,重新抛竿
if (_throwRodWaitFrameNum >= content.FrameRate * TaskContext.Instance().Config.AutoFishingConfig.AutoThrowRodTimeOut)
{
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_throwRodWaitFrameNum = 0;
_waitBiteContinuouslyFrameNum = 0;
Debug.WriteLine("超时自动收竿");
@@ -365,9 +366,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
private string ChooseBait(CaptureContent content, Fishpond fishpond)
{
// 打开换饵界面
Simulation.SendInputEx.Mouse.RightButtonClick();
Simulation.SendInput.Mouse.RightButtonClick();
Sleep(100);
Simulation.SendInputEx.Mouse.MoveMouseBy(0, 200); // 鼠标移走,防止干扰
Simulation.SendInput.Mouse.MoveMouseBy(0, 200); // 鼠标移走,防止干扰
Sleep(500);
_selectedBaitName = fishpond.Fishes[0].FishType.BaitName; // 选择最多鱼吃的饵料
@@ -398,7 +399,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
resRa.Click();
Sleep(700);
// 可能重复点击,所以固定界面点击下
captureRegion.ClickTo((int)(captureRegion.Width * 0.675), (int)(captureRegion.Height / 2d));
captureRegion.ClickTo((int)(captureRegion.Width * 0.675), (int)(captureRegion.Height / 3d));
Sleep(200);
// 点击确定
Bv.ClickWhiteConfirmButton(captureRegion);
@@ -417,7 +418,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
private void ApproachFishAndThrowRod(CaptureContent content)
{
// 预抛竿
Simulation.SendInputEx.Mouse.LeftButtonDown();
Simulation.SendInput.Mouse.LeftButtonDown();
_logger.LogInformation("长按预抛竿");
Sleep(3000);
@@ -451,7 +452,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
var moveX = 100 * (cX - rdX) / ra.SrcBitmap.Width;
var moveY = 100 * (cY - rdY) / ra.SrcBitmap.Height;
Simulation.SendInputEx.Mouse.MoveMouseBy(moveX, moveY);
Simulation.SendInput.Mouse.MoveMouseBy(moveX, moveY);
if (noPlacementTimes > 25)
{
@@ -503,10 +504,10 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
// 没有找到目标鱼,重新选择鱼饵
_logger.LogInformation("没有找到目标鱼,1.直接抛竿");
Simulation.SendInputEx.Mouse.LeftButtonUp();
Simulation.SendInput.Mouse.LeftButtonUp();
Sleep(1500);
_logger.LogInformation("没有找到目标鱼,2.收杆");
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
Sleep(800);
_logger.LogInformation("没有找到目标鱼,3.准备重新选择鱼饵");
_selectedBaitName = string.Empty;
@@ -569,12 +570,12 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
var moveY = 100 * (cY - rdY) / content.CaptureRectArea.SrcBitmap.Height;
_logger.LogInformation("失败 随机移动 {DX}, {DY}", moveX, moveY);
Simulation.SendInputEx.Mouse.MoveMouseBy(moveX, moveY);
Simulation.SendInput.Mouse.MoveMouseBy(moveX, moveY);
}
else if (state == 0)
{
// 成功 抛竿
Simulation.SendInputEx.Mouse.LeftButtonUp();
Simulation.SendInput.Mouse.LeftButtonUp();
_logger.LogInformation("尝试钓取 {Text}", currentFish.FishType.ChineseName);
_isThrowRod = true;
VisionContext.Instance().DrawContent.RemoveRect("Target");
@@ -589,13 +590,13 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
dx = dx / dl * 30;
dy = dy / dl * 30;
// _logger.LogInformation("太近 移动 {DX}, {DY}", dx, dy);
Simulation.SendInputEx.Mouse.MoveMouseBy((int)(-dx / 1.5), (int)(-dy * 1.5));
Simulation.SendInput.Mouse.MoveMouseBy((int)(-dx / 1.5), (int)(-dy * 1.5));
}
else if (state == 2)
{
// 太远
// _logger.LogInformation("太远 移动 {DX}, {DY}", dx, dy);
Simulation.SendInputEx.Mouse.MoveMouseBy((int)(dx / 1.5), (int)(dy * 1.5));
Simulation.SendInput.Mouse.MoveMouseBy((int)(dx / 1.5), (int)(dy * 1.5));
}
}
@@ -621,9 +622,9 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
if (TaskContext.Instance().Config.AutoFishingConfig.AutoThrowRodEnabled)
{
// 下移视角方便看鱼
Simulation.SendInputEx.Mouse.MoveMouseBy(0, 400);
Simulation.SendInput.Mouse.MoveMouseBy(0, 400);
Sleep(500);
Simulation.SendInputEx.Mouse.MoveMouseBy(0, 500);
Simulation.SendInput.Mouse.MoveMouseBy(0, 500);
Sleep(500);
}
}
@@ -661,7 +662,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
//_logger.LogInformation("移动鼠标 {X} {Y}", 0, moveY);
Simulation.SendInputEx.Mouse.MoveMouseBy(0, moveY);
Simulation.SendInput.Mouse.MoveMouseBy(0, moveY);
return (0, minDistance);
}
@@ -681,7 +682,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
//_logger.LogInformation("移动鼠标 {X} {Y}", moveX, 0);
Simulation.SendInputEx.Mouse.MoveMouseBy(moveX, 0);
Simulation.SendInput.Mouse.MoveMouseBy(moveX, 0);
return (minDistance, 0);
}
@@ -714,7 +715,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
}
//_logger.LogInformation("移动鼠标 {X} {Y}", moveX, moveY);
Simulation.SendInputEx.Mouse.MoveMouseBy(moveX, moveY);
Simulation.SendInput.Mouse.MoveMouseBy(moveX, moveY);
return (dpX, dpY);
}
@@ -846,7 +847,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
using var liftRodButtonRa = content.CaptureRectArea.Find(_autoFishingAssets.LiftRodButtonRo);
if (!liftRodButtonRa.IsEmpty())
{
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_logger.LogInformation(@"┌------------------------┐");
_logger.LogInformation(" 自动提竿(图像识别)");
_isFishingProcess = true;
@@ -863,7 +864,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
currentBiteWordsTips.Width, currentBiteWordsTips.Height)));
if (!string.IsNullOrEmpty(text) && StringUtils.RemoveAllSpace(text).Contains("上钩"))
{
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_logger.LogInformation(@"┌------------------------┐");
_logger.LogInformation(" 自动提竿(OCR)");
_isFishingProcess = true;
@@ -882,7 +883,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
if (_biteTipsExitCount >= content.FrameRate / 2d)
{
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_logger.LogInformation(@"┌------------------------┐");
_logger.LogInformation(" 自动提竿(文字块)");
_isFishingProcess = true;
@@ -906,7 +907,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
/// <param name="fishBarMat"></param>
private void Fishing(CaptureContent content, Mat fishBarMat)
{
var simulator = Simulation.SendInputEx;
var simulator = Simulation.SendInput;
var rects = AutoFishingImageRecognition.GetFishBarRect(fishBarMat);
if (rects != null && rects.Count > 0)
{
@@ -539,7 +539,7 @@ public class GeniusInvokationControl
public void ActionPhaseElementalTuning(int currentCardCount)
{
var rect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
var m = Simulation.SendInputEx.Mouse;
var m = Simulation.SendInput.Mouse;
ClickExtension.Click(rect.X + rect.Width / 2d, rect.Y + rect.Height - 50);
Sleep(1500);
if (currentCardCount == 1)
@@ -1,17 +1,12 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using OpenCvSharp.Aruco;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
@@ -19,17 +14,8 @@ using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoMusicGame;
public class AutoMusicGameTask
public class AutoMusicGameTask(AutoMusicGameParam taskParam)
{
private readonly AutoMusicGameParam _taskParam;
// private readonly int _judgeLineDisY; // 判定线的Y相对底部坐标
// private readonly int[] _judgeLineX;
// private readonly User32.VK[] _keyMap;
// private readonly Dictionary<User32.VK, bool> _keyStatus = new Dictionary<User32.VK, bool>();
//
// private PostMessageSimulator _simulator;
private readonly ConcurrentDictionary<User32.VK, int> _keyX = new()
{
[User32.VK.VK_A] = 417,
@@ -42,24 +28,7 @@ public class AutoMusicGameTask
private readonly int _keyY = 916;
private readonly IntPtr _hWnd;
public AutoMusicGameTask(AutoMusicGameParam taskParam)
{
_taskParam = taskParam;
// var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
// var rect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
// var w = rect.Width;
// _judgeLineDisY = (int)(130 * assetScale); // 127 是线的位置
// int k1 = (int)(520 * assetScale);
// int k2 = (int)(745 * assetScale);
// _judgeLineX = [0, k1, k2, w / 2, w - k2, w - k1, w];
// _keyMap = [User32.VK.VK_A, User32.VK.VK_S, User32.VK.VK_D, User32.VK.VK_J, User32.VK.VK_K, User32.VK.VK_L];
_hWnd = TaskContext.Instance().GameHandle;
// _simulator = Simulation.PostMessage(TaskContext.Instance().GameHandle);
}
private readonly IntPtr _hWnd = TaskContext.Instance().GameHandle;
public async void Start()
{
@@ -75,6 +44,7 @@ public class AutoMusicGameTask
Init();
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var taskFactory = new TaskFactory();
var taskList = new List<Task>();
@@ -83,9 +53,9 @@ public class AutoMusicGameTask
foreach (var keyValuePair in _keyX)
{
var (x, y) = gameCaptureRegion.ConvertPositionToGameCaptureRegion(keyValuePair.Value, _keyY);
var (x, y) = gameCaptureRegion.ConvertPositionToGameCaptureRegion((int)(keyValuePair.Value * assetScale), (int)(_keyY * assetScale));
// 添加任务
taskList.Add(taskFactory.StartNew(() => DoWhitePressWin32(_taskParam.Cts, keyValuePair.Key, new Point(x, y))));
taskList.Add(taskFactory.StartNew(() => DoWhitePressWin32(taskParam.Cts, keyValuePair.Key, new Point(x, y))));
}
Task.WaitAll([.. taskList]);
@@ -146,198 +116,23 @@ public class AutoMusicGameTask
}
}
// private void NotWhiteWin32(ConcurrentDictionary<User32.VK, Point> posDic)
// {
// Parallel.ForEach(posDic, kvp => { WhitePressWin32(kvp.Key, kvp.Value); });
//
// // foreach (var keyValuePair in posDic)
// // {
// // WhitePressWin32(keyValuePair.Key, keyValuePair.Value);
// // }
// }
//
// private void WhitePressWin32(User32.VK key, Point point)
// {
// Stopwatch sw = new();
// sw.Start();
// var hdc = User32.GetDC(TaskContext.Instance().GameHandle);
// var c = Gdi32.GetPixel(hdc, point.X, point.Y);
//
// if (c.B < 220)
// {
// KeyDown(key);
// }
// else
// {
// KeyUp(key);
// }
// Gdi32.DeleteDC(hdc);
// sw.Stop();
// Debug.WriteLine($"GetPixel 耗时:{sw.ElapsedMilliseconds} ({point.X},{point.Y})颜色{c.R},{c.G},{c.B}");
// }
//
// private void NotWhite()
// {
// var gameCaptureRegion = CaptureToRectArea();
// var srcMat = gameCaptureRegion.SrcMat;
// Parallel.ForEach(_keyX, kvp => { WhitePress(srcMat, kvp.Key, kvp.Value); });
// gameCaptureRegion.Dispose();
// }
//
// private unsafe void WhitePress(Mat srcMat, User32.VK key, int x)
// {
// // 获取图像的指针
// byte* ptr = (byte*)srcMat.Data.ToPointer();
//
// // 计算特定坐标下的像素偏移量
// long offset = srcMat.Step() * _keyY + srcMat.Channels() * x;
//
// // 获取像素的 RGB 值
// // byte r = ptr[offset];
// byte g = ptr[offset + 1];
// // byte b = ptr[offset + 2];
// if (g < 240)
// {
// KeyDown(key);
// }
// else
// {
// KeyUp(key);
// }
// }
//
// private void AllPress()
// {
// using var gameCaptureRegion = CaptureToRectArea();
// var srcMat = gameCaptureRegion.SrcMat[new Rect(0, gameCaptureRegion.Height - gameCaptureRegion.Height / 4, gameCaptureRegion.Width, gameCaptureRegion.Height / 4)];
// Parallel.Invoke(() => { PressPurple(srcMat); }, () => { PressYellow(srcMat); });
// }
//
// private void PressYellow(Mat srcMat)
// {
// ContoursHelper.FindSpecifyColorRects(srcMat, new Scalar(230, 176, 60), new Scalar(244, 191, 75), 50, 50).ForEach(rect =>
// {
// if (srcMat.Height - rect.Height - rect.Y < _judgeLineDisY)
// {
// var x = rect.X + rect.Width / 2;
// var key = GetKey(x);
// if (key != User32.VK.VK_0)
// {
// KeyPress(key);
// }
// else
// {
// Logger.LogWarning("X轴位找到对应值");
// }
// }
// });
// }
//
// private void PressPurple(Mat srcMat)
// {
// ContoursHelper.FindSpecifyColorRects(srcMat, new Scalar(143, 119, 238), new Scalar(163, 140, 245), 50, 50).ForEach(rect =>
// {
// if (srcMat.Height - rect.Height - rect.Y <= 150 * assetScale)
// {
// var x = rect.X + rect.Width / 2;
// var key = GetKey(x);
// if (key != User32.VK.VK_0)
// {
// PurpleKeyPress(key);
// }
// else
// {
// Logger.LogWarning("X轴位找到对应值");
// }
// }
// });
// }
//
// private User32.VK GetKey(int i)
// {
// for (int j = 0; j < _judgeLineX.Length - 1; j++)
// {
// if (_judgeLineX[j] <= i && i < _judgeLineX[j + 1])
// {
// return _keyMap[j];
// }
// }
//
// return User32.VK.VK_0;
// }
// private void KeyPress(User32.VK key)
// {
// _simulator.KeyPress(key);
// }
//
// private void PurpleKeyPress(User32.VK key)
// {
// if (_keyStatus.TryGetValue(key, out var v))
// {
// if (v)
// {
// KeyUp(key);
// _keyStatus[key] = false;
// }
// else
// {
// _keyStatus[key] = true;
// KeyDown(key);
// }
// }
// else
// {
// _keyStatus[key] = true;
// KeyDown(key);
// }
// }
private void KeyUp(User32.VK key)
{
Simulation.SendInputEx.Keyboard.KeyUp(key);
Simulation.SendInput.Keyboard.KeyUp(key);
}
private void KeyDown(User32.VK key)
{
Simulation.SendInputEx.Keyboard.KeyDown(key);
Simulation.SendInput.Keyboard.KeyDown(key);
}
// private void KeyUpOnce(User32.VK key)
// {
// if (_keyStatus.TryGetValue(key, out var v))
// {
// if (v)
// {
// _keyStatus[key] = false;
// _simulator.KeyUp(key);
// }
// }
// }
//
// private void KeyDownOnce(User32.VK key)
// {
// if (_keyStatus.TryGetValue(key, out var v))
// {
// if (!v)
// {
// _keyStatus[key] = true;
// _simulator.KeyDown(key);
// }
// }
// else
// {
// _simulator.KeyDown(key);
// }
// }
private void Init()
{
LogScreenResolution();
Logger.LogInformation("→ {Text}", "活动音游,启动!");
SystemControl.ActivateWindow();
TaskTriggerDispatcher.Instance().StopTimer();
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, taskParam.Cts); // 等待缓存图像
}
private void LogScreenResolution()
@@ -1,9 +1,5 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoPick
{
@@ -175,7 +175,7 @@ public class AutoPickTrigger : ITaskTrigger
if (_whiteList.Contains(text))
{
LogPick(content, text);
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F);
return;
}
@@ -195,7 +195,7 @@ public class AutoPickTrigger : ITaskTrigger
speedTimer.Record("黑名单判断");
LogPick(content, text);
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F);
}
});
speedTimer.DebugPrint();
@@ -182,7 +182,7 @@ public class AutoSkipTrigger : ITaskTrigger
_prevPlayingTime = DateTime.Now;
if (TaskContext.Instance().Config.AutoSkipConfig.QuicklySkipConversationsEnabled)
{
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_SPACE);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
}
// 对话选项选择
@@ -221,7 +221,7 @@ public class AutoSkipTrigger : ITaskTrigger
var rate = blackCount * 1d / (grayMat.Width * grayMat.Height);
if (rate is >= 0.5 and < 0.98999)
{
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_logger.LogInformation("自动剧情:{Text} 比例 {Rate}", "点击黑屏", rate.ToString("F"));
@@ -367,7 +367,7 @@ public class AutoSkipTrigger : ITaskTrigger
content.CaptureRectArea.Find(_autoSkipAssets.PrimogemRo, primogemRa =>
{
Thread.Sleep(100);
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
_prevGetDailyRewardsTime = DateTime.MinValue;
primogemRa.Dispose();
});
@@ -92,7 +92,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
}
// 任务文字有动效,等待2s重新截图
Simulation.SendInputEx.Mouse.MoveMouseBy(0, 7000);
Simulation.SendInput.Mouse.MoveMouseBy(0, 7000);
Sleep(2000, param.Cts);
// OCR 任务文字 在小地图下方
@@ -111,7 +111,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
// 距离大于150米,先传送到最近的传送点
// J 打开任务 切换追踪打开地图 中心点就是任务点
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_J);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_J);
Sleep(800, param.Cts);
// TODO 识别是否在任务界面
// 切换追踪
@@ -177,7 +177,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
private void StartTrackPoint()
{
// V键直接追踪
Simulation.SendInputEx.Keyboard.KeyPress(User32.VK.VK_V);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_V);
Sleep(3000, param.Cts);
var ra = GetRectAreaFromDispatcher();
@@ -211,10 +211,10 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
var centerY = blueTrackPointRa.Y + blueTrackPointRa.Height / 2;
if (centerY > CaptureRect.Height / 2)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(-50, 0);
Simulation.SendInput.Mouse.MoveMouseBy(-50, 0);
if (wDown)
{
Simulation.SendInputEx.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
wDown = false;
}
Debug.WriteLine("使追踪点位于俯视角上方");
@@ -232,7 +232,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
};
if (moveX != 0)
{
Simulation.SendInputEx.Mouse.MoveMouseBy(moveX, 0);
Simulation.SendInput.Mouse.MoveMouseBy(moveX, 0);
Debug.WriteLine("调整方向:" + moveX);
}
@@ -240,7 +240,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
if (!wDown)
{
Simulation.SendInputEx.Keyboard.KeyDown(User32.VK.VK_W);
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
wDown = true;
}
}
@@ -249,7 +249,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
{
if (wDown)
{
Simulation.SendInputEx.Keyboard.KeyUp(User32.VK.VK_W);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
wDown = false;
}
// 识别距离
@@ -271,7 +271,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
Logger.LogInformation("未找到追踪点");
}
Simulation.SendInputEx.Mouse.MoveMouseBy(0, 500); // 保证俯视角
Simulation.SendInput.Mouse.MoveMouseBy(0, 500); // 保证俯视角
Sleep(100);
}
// });
@@ -42,7 +42,7 @@ public class OneKeyExpeditionTask
// 3.退出派遣页面 ESC
Sleep(500);
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_ESCAPE);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
Logger.LogInformation("探索派遣:{Text}", "完成");
});
}
@@ -1,10 +1,18 @@
using System;
using System.Diagnostics;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.Model.Enum;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -12,6 +20,7 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath;
public class AutoTrackPathTask
{
private readonly AutoTrackPathParam _taskParam;
private readonly Random _rd = new Random();
public AutoTrackPathTask(AutoTrackPathParam taskParam)
{
@@ -23,7 +32,6 @@ public class AutoTrackPathTask
var hasLock = false;
try
{
AutoFightAssets.DestroyInstance();
hasLock = await TaskSemaphore.WaitAsync(0);
if (!hasLock)
{
@@ -32,6 +40,8 @@ public class AutoTrackPathTask
}
Init();
Tp(4726.575195, 1852.823975);
}
catch (NormalEndException)
{
@@ -59,6 +69,7 @@ public class AutoTrackPathTask
private void Init()
{
SystemControl.ActivateWindow();
Logger.LogInformation("→ {Text}", "自动路线,启动!");
TaskTriggerDispatcher.Instance().SetCacheCaptureMode(DispatcherCaptureModeEnum.OnlyCacheCapture);
Sleep(TaskContext.Instance().Config.TriggerInterval * 5, _taskParam.Cts); // 等待缓存图像
}
@@ -105,10 +116,52 @@ public class AutoTrackPathTask
// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
// M 打开地图识别当前位置,中心点为当前位置
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_M);
Sleep(1000);
// 计算传送点位置离哪个地图切换后的中心点最近,切换到该地图
var bigMapCenterPoint = GetPositionFromBigMap();
// 移动部分内容测试移动偏移
var (xOffset, yOffset) = (x - bigMapCenterPoint.X, y - bigMapCenterPoint.Y);
var diffMouseX = 100; // 每次移动的距离
if (xOffset < 0)
{
diffMouseX = -diffMouseX;
}
var diffMouseY = 100; // 每次移动的距离
if (yOffset < 0)
{
diffMouseY = -diffMouseY;
}
// 先移动到屏幕中心附近随机点位置,避免地图移动无效
MouseMoveMapX(diffMouseX);
MouseMoveMapY(diffMouseY);
var newBigMapCenterPoint = GetPositionFromBigMap();
var diffMapX = newBigMapCenterPoint.X - bigMapCenterPoint.X;
var diffMapY = newBigMapCenterPoint.Y - bigMapCenterPoint.Y;
Debug.WriteLine($"每100移动的地图距离:({diffMapX},{diffMapY})");
if (diffMapX > 0 && diffMapY > 0)
{
// // 计算需要移动的次数
var moveCount = (int)(xOffset / diffMapX); // 向下取整 本来还要加1的,但是已经移动了一次了
Debug.WriteLine("X需要移动的次数:" + moveCount);
for (var i = 0; i < moveCount; i++)
{
MouseMoveMapX(diffMouseX);
}
moveCount = (int)(yOffset / diffMapY); // 向下取整 本来还要加1的,但是已经移动了一次了
Debug.WriteLine("Y需要移动的次数:" + moveCount);
for (var i = 0; i < moveCount; i++)
{
MouseMoveMapY(diffMouseY);
}
}
// 快速移动到目标传送点所在的区域
@@ -117,6 +170,57 @@ public class AutoTrackPathTask
// 触发一次快速传送功能
}
public void MouseMoveMapX(int dx)
{
var moveUnit = dx > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(200);
for (var i = 0; i < dx / moveUnit; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy(moveUnit, 0).Sleep(60); // 60 保证没有惯性
}
Simulation.SendInput.Mouse.LeftButtonUp().Sleep(200);
}
public void MouseMoveMapY(int dy)
{
var moveUnit = dy > 0 ? 20 : -20;
GameCaptureRegion.GameRegionMove((rect, _) => (rect.Width / 2d + _rd.Next(-rect.Width / 6, rect.Width / 6), rect.Height / 2d + _rd.Next(-rect.Height / 6, rect.Height / 6)));
Simulation.SendInput.Mouse.LeftButtonDown().Sleep(200);
// 原神地图在小范围内移动是无效的,所以先随便移动一下,所以肯定少移动一次
for (var i = 0; i < dy / moveUnit; i++)
{
Simulation.SendInput.Mouse.MoveMouseBy(0, moveUnit).Sleep(60);
}
Simulation.SendInput.Mouse.LeftButtonUp().Sleep(200);
}
public Point GetPositionFromBigMap()
{
var bigMapRect = GetBigMapRect();
// 中心点
var bigMapCenterPoint = bigMapRect.GetCenterPoint();
Debug.WriteLine("识别大地图中心点:" + bigMapCenterPoint);
var gamePoint = MapCoordinate.Main2048ToGame(bigMapCenterPoint);
Debug.WriteLine("转换到游戏坐标:" + gamePoint);
return gamePoint;
}
public Rect GetBigMapRect()
{
// 判断是否在地图界面
using var ra = GetRectAreaFromDispatcher();
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
return EntireMap.Instance.GetBigMapPositionByFeatureMatch(ra.SrcGreyMat);
}
else
{
throw new InvalidOperationException("当前不在地图界面");
}
}
public void TpByF1(string name)
{
// 传送到指定传送点
@@ -78,7 +78,7 @@ public class PathPointRecorder : Singleton<PathPointRecorder>
continue;
}
var rect = _bigMap.GetMapPositionByFeatureMatch(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
var rect = _bigMap.GetMiniMapPositionByFeatureMatch(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
if (rect != Rect.Empty)
{
way.AddPoint(rect);
@@ -14,8 +14,14 @@ public class AutoWoodAssets : BaseAssets<AutoWoodAssets>
public RecognitionObject ConfirmRo;
public RecognitionObject EnterGameRo;
// 木头数量
public Rect WoodCountUpperRect;
private AutoWoodAssets()
{
WoodCountUpperRect = new Rect((int)(100 * AssetScale), (int)(450 * AssetScale), (int)(300 * AssetScale), (int)(250 * AssetScale));
//「王树瑞佑」
TheBoonOfTheElderTreeRo = new RecognitionObject
{
@@ -1,13 +1,8 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoWood;
/// <summary>
/// 自动伐木配置
/// </summary>
@@ -17,5 +12,19 @@ public partial class AutoWoodConfig : ObservableObject
/// <summary>
/// 使用小道具后的额外延迟(毫秒)
/// </summary>
[ObservableProperty] private int _afterZSleepDelay = 0;
}
[ObservableProperty]
private int _afterZSleepDelay = 0;
/// <summary>
/// 木材数量OCR是否启用
/// </summary>
[ObservableProperty]
private bool _woodCountOcrEnabled = true;
// /// <summary>
// /// 按下两次ESC键,原因见:
// /// https://github.com/babalae/better-genshin-impact/issues/235
// /// </summary>
// [ObservableProperty]
// private bool _pressTwoEscEnabled = false;
}
@@ -1,17 +1,21 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoWood.Assets;
using BetterGenshinImpact.GameTask.AutoWood.Utils;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Genshin.Settings;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.View.Drawable;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.User32;
using GC = System.GC;
@@ -21,12 +25,14 @@ namespace BetterGenshinImpact.GameTask.AutoWood;
/// <summary>
/// 自动伐木
/// </summary>
public class AutoWoodTask
public partial class AutoWoodTask
{
private readonly AutoWoodAssets _assets;
private bool _first = true;
private readonly WoodStatisticsPrinter _printer;
private readonly Login3rdParty _login3rdParty;
private VK _zKey = VK.VK_Z;
@@ -36,11 +42,13 @@ public class AutoWoodTask
_login3rdParty = new();
AutoWoodAssets.DestroyInstance();
_assets = AutoWoodAssets.Instance;
_printer = new WoodStatisticsPrinter(_assets);
}
public void Start(WoodTaskParam taskParam)
{
var hasLock = false;
var runTimeWatch = new Stopwatch();
try
{
hasLock = TaskSemaphore.Wait(0);
@@ -51,7 +59,8 @@ public class AutoWoodTask
}
TaskTriggerDispatcher.Instance().StopTimer();
Logger.LogInformation("→ {Text} 设置伐木总次数:{Cnt}", "自动伐木,启动!", taskParam.WoodRoundNum);
Kernel32.SetThreadExecutionState(Kernel32.EXECUTION_STATE.ES_CONTINUOUS | Kernel32.EXECUTION_STATE.ES_SYSTEM_REQUIRED | Kernel32.EXECUTION_STATE.ES_DISPLAY_REQUIRED);
Logger.LogInformation("→ {Text} 设置伐木总次数:{Cnt},设置木材数量上限:{MaxCnt}", "自动伐木,启动!", taskParam.WoodRoundNum, taskParam.WoodDailyMaxCount);
_login3rdParty.RefreshAvailabled();
if (_login3rdParty.Type == Login3rdParty.The3rdPartyType.Bilibili)
@@ -75,8 +84,25 @@ public class AutoWoodTask
}
SystemControl.ActivateWindow();
// 伐木开始计时
runTimeWatch.Start();
for (var i = 0; i < taskParam.WoodRoundNum; i++)
{
if (TaskContext.Instance().Config.AutoWoodConfig.WoodCountOcrEnabled)
{
if (_printer.WoodStatisticsAlwaysEmpty())
{
Logger.LogInformation("连续{Cnt}次获取木材数量为0。判定附近没有能响应「王树瑞佑」的树木!或者已达每日数量上限", _printer.NothingCount);
break;
}
if (_printer.ReachedWoodMaxCount)
{
Logger.LogInformation("{Names}已达到设置的上限:{MaxCnt}", _printer.WoodTotalDict.Keys, taskParam.WoodDailyMaxCount);
break;
}
}
Logger.LogInformation("第{Cnt}次伐木", i + 1);
if (taskParam.Cts.IsCancellationRequested)
{
@@ -102,6 +128,11 @@ public class AutoWoodTask
{
VisionContext.Instance().DrawContent.ClearAll();
TaskSettingsPageViewModel.SetSwitchAutoWoodButtonText(false);
// 伐木结束计时
runTimeWatch.Stop();
Kernel32.SetThreadExecutionState(Kernel32.EXECUTION_STATE.ES_CONTINUOUS);
var elapsedTime = runTimeWatch.Elapsed;
Logger.LogInformation(@"本次伐木总耗时:{Time:hh\:mm\:ss}", elapsedTime);
Logger.LogInformation("← {Text}", "退出自动伐木");
TaskTriggerDispatcher.Instance().StartTimer();
@@ -112,6 +143,246 @@ public class AutoWoodTask
}
}
private partial class WoodStatisticsPrinter(AutoWoodAssets assert)
{
public bool ReachedWoodMaxCount;
public int NothingCount;
public readonly ConcurrentDictionary<string, int> WoodTotalDict = new();
private bool _firstWoodOcr = true;
private string _firstWoodOcrText = "";
private readonly Dictionary<string, int> _woodMetricsDict = new();
private readonly Dictionary<string, bool> _woodNotPrintDict = new();
// from:https://api-static.mihoyo.com/common/blackboard/ys_obc/v1/home/content/list?app_sn=ys_obc&channel_id=13
private static readonly List<string> ExistWoods =
[
"悬铃木", "白梣木", "炬木", "椴木", "香柏木", "刺葵木", "柽木", "辉木", "业果木", "证悟木", "枫木", "垂香木",
"杉木", "竹节", "却砂木", "松木", "萃华木", "桦木", "孔雀木", "梦见木", "御伽木"
];
[GeneratedRegex("([^\\d\\n]+)[×x](\\d+)")]
private static partial Regex _parseWoodStatisticsRegex();
public bool WoodStatisticsAlwaysEmpty()
{
return NothingCount >= 3;
}
public void PrintWoodStatistics(WoodTaskParam taskParam)
{
var woodStatisticsText = GetWoodStatisticsText(taskParam);
if (string.IsNullOrEmpty(woodStatisticsText))
{
NothingCount++;
Logger.LogWarning("未能识别到伐木的统计数据");
return;
}
ParseWoodStatisticsText(taskParam, woodStatisticsText);
CheckAndPrintWoodQuantities(taskParam);
}
private string GetWoodStatisticsText(WoodTaskParam taskParam)
{
var firstOcrResultList = new List<string>();
// 创建一个计时器,循环识别文本,直到超时
var stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < 3500)
{
// OCR识别木材文本
var recognizedText = WoodTextAreaOcr();
if (_firstWoodOcr)
{
// 首次时会重复OCR识别,然后找到最好的OCR结果(即最长的那个)
var isFound = HasDetectedWoodText(recognizedText);
if (isFound) firstOcrResultList.Add(recognizedText);
if (firstOcrResultList.Count != 0 && !isFound) break;
SleepDurationBetweenOcrs(taskParam);
}
else
{
var isFound = HasDetectedWoodText(recognizedText);
if (!isFound)
{
SleepDurationBetweenOcrs(taskParam);
continue;
}
NothingCount = 0;
// 等待伐木的木材数量显示全,再次OCR识别。
// SleepDurationBetweenOcrs(taskParam);
// return WoodTextAreaOcr();
// 直接返回首次的识别结果
return _firstWoodOcrText;
}
}
stopwatch.Stop(); // 停止计时
_firstWoodOcrText = FindBestOcrResult(firstOcrResultList);
return _firstWoodOcrText;
}
private void SleepDurationBetweenOcrs(WoodTaskParam taskParam)
{
Sleep(_firstWoodOcr ? 300 : 100, taskParam.Cts);
}
private string WoodTextAreaOcr()
{
// OCR识别文本区域
var woodCountRect = CaptureToRectArea().DeriveCrop(assert.WoodCountUpperRect);
return OcrFactory.Paddle.Ocr(woodCountRect.SrcGreyMat);
}
private bool HasDetectedWoodText(string recognizedText)
{
if (!_firstWoodOcr)
{
return !string.IsNullOrEmpty(recognizedText) &&
recognizedText.Contains("获得");
}
return !string.IsNullOrEmpty(recognizedText) &&
recognizedText.Contains("获得") &&
(recognizedText.Contains('×') || recognizedText.Contains('x'));
}
private void ParseWoodStatisticsText(WoodTaskParam taskParam, string text)
{
// 从识别的文本中提取木材名称和数量
// 格式示例:"获得\n竹节×30\n杉木×20"
if (!text.Contains('×') && !text.Contains('X'))
{
Logger.LogWarning("未能正确解析木材信息格式:{woodText}", text);
return;
}
// 匹配模式 "名称×数量"
var matches = _parseWoodStatisticsRegex().Matches(text);
// 如果OCR识别木材的种类小于等于首次保存的一样时,直接使用首次的木材数量。
if (!_firstWoodOcr && 1 <= matches.Count && matches.Count <= _woodMetricsDict.Count)
{
foreach (var entry in _woodMetricsDict.Where(entry => entry.Value <= taskParam.WoodDailyMaxCount))
{
UpdateWoodCount(entry.Key, entry.Value);
}
}
else
{
foreach (Match match in matches)
{
if (match.Success)
{
var materialName = match.Groups[1].Value.Trim();
var quantityStr = match.Groups[2].Value.Trim();
var quantity = int.Parse(quantityStr);
Debug.WriteLine($"首次获取木材的名称:{materialName}, 数量:{quantity}");
UpdateWoodCount(materialName, quantity);
}
else
{
Logger.LogWarning("识别到的数量不是有效的整数:{woodText}", text);
}
}
// 所有数据都保存一遍后,首次OCR识别结束
_firstWoodOcr = false;
}
}
private void UpdateWoodCount(string materialName, int quantity)
{
// 检查字典中是否已包含这种木材名称
if (!ExistWoods.Contains(materialName))
{
Logger.LogWarning("未知的木材名:{woodName},数量{Cnt}", materialName, quantity);
return;
}
WoodTotalDict.AddOrUpdate(
key: materialName,
addValue: quantity,
updateValueFactory: (_, existingValue) => existingValue + quantity
);
if (_firstWoodOcr)
{
// 记录木材单次获取的值
_woodMetricsDict.Add(materialName, quantity);
}
}
private static string FindBestOcrResult(List<string> firstOcrResultList)
{
// return firstOcrResultList.Count == 0 ? "" : firstOcrResultList.OrderByDescending(s => s.Length).First();
if (firstOcrResultList.Count == 0) return "";
// 先排序再查找
var sortedOcrResults = firstOcrResultList.OrderByDescending(s => s.Length).ToList();
int? targetLength = null;
foreach (var ocrResult in sortedOcrResults)
{
if (targetLength == null)
{
targetLength = ocrResult.Length;
}
else if (ocrResult.Length != targetLength)
{
// 如果当前结果长度与第一个匹配项的长度不同,则跳过
continue;
}
// 分解 OCR 结果中的多个条目
var matches = _parseWoodStatisticsRegex().Matches(ocrResult);
var isFound = true;
foreach (Match match in matches)
{
if (!match.Success)
{
isFound = false;
continue;
}
var materialName = match.Groups[1].Value.Trim();
Debug.WriteLine($"第一次获取的木材名称:{materialName}");
if (!ExistWoods.Contains(materialName))
{
isFound = false;
}
}
if (isFound) return ocrResult;
}
// 如果没有找到匹配的结果
return "";
}
private void CheckAndPrintWoodQuantities(WoodTaskParam taskParam)
{
if (WoodTotalDict.IsEmpty)
{
ReachedWoodMaxCount = false;
NothingCount++;
return;
}
foreach (var entry in WoodTotalDict)
{
if (_woodNotPrintDict.GetValueOrDefault(entry.Key)) continue;
// 打印每个条目的键(木材名称)和值(数量)
Logger.LogInformation("木材{woodName}累积获取数量:{Cnt}", entry.Key, entry.Value);
// 检查木材是否超过上限
if (entry.Value < taskParam.WoodDailyMaxCount) continue;
Logger.LogInformation("木材{Name}已达到数量设置的上限:{Count}", entry.Key, taskParam.WoodDailyMaxCount);
_woodNotPrintDict.TryAdd(entry.Key, true);
}
// 如果木材统计的最小值都大于设置的上限,则停止伐木
ReachedWoodMaxCount = WoodTotalDict.Values.Min() >= taskParam.WoodDailyMaxCount;
}
}
private void Felling(WoodTaskParam taskParam, bool isLast = false)
{
// 1. 按 z 触发「王树瑞佑」
@@ -122,6 +393,13 @@ public class AutoWoodTask
return;
}
// 打印伐木的统计数据(可选)
if (TaskContext.Instance().Config.AutoWoodConfig.WoodCountOcrEnabled)
{
_printer.PrintWoodStatistics(taskParam);
if (_printer.WoodStatisticsAlwaysEmpty() || _printer.ReachedWoodMaxCount) return;
}
// 2. 按下 ESC 打开菜单 并退出游戏
PressEsc(taskParam);
@@ -154,7 +432,7 @@ public class AutoWoodTask
}
else
{
Simulation.SendInputEx.Keyboard.KeyPress(_zKey);
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Debug.WriteLine("[AutoWood] Z");
_first = false;
}
@@ -175,7 +453,7 @@ public class AutoWoodTask
#endif
}
Simulation.SendInputEx.Keyboard.KeyPress(_zKey);
Simulation.SendInput.Keyboard.KeyPress(_zKey);
Debug.WriteLine("[AutoWood] Z");
Sleep(500, taskParam.Cts);
}, TimeSpan.FromSeconds(1), 120);
@@ -188,7 +466,12 @@ public class AutoWoodTask
private void PressEsc(WoodTaskParam taskParam)
{
SystemControl.Focus(TaskContext.Instance().GameHandle);
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_ESCAPE);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
// if (TaskContext.Instance().Config.AutoWoodConfig.PressTwoEscEnabled)
// {
// Sleep(1500, taskParam.Cts);
// Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
// }
Debug.WriteLine("[AutoWood] Esc");
Sleep(800, taskParam.Cts);
// 确认在菜单界面
@@ -201,9 +484,10 @@ public class AutoWoodTask
using var ra = contentRegion.Find(_assets.MenuBagRo);
if (ra.IsEmpty())
{
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
throw new RetryException("未检测到弹出菜单");
}
}, TimeSpan.FromSeconds(1), 3);
}, TimeSpan.FromSeconds(1.2), 5);
}
catch (Exception e)
{
@@ -7,13 +7,17 @@ namespace BetterGenshinImpact.GameTask.AutoWood;
public class WoodTaskParam : BaseTaskParam
{
public int WoodRoundNum { get; set; }
public int WoodDailyMaxCount { get; set; }
public WoodTaskParam(CancellationTokenSource cts, int woodRoundNum) : base(cts)
public WoodTaskParam(CancellationTokenSource cts, int woodRoundNum, int woodDailyMaxCount) : base(cts)
{
WoodRoundNum = woodRoundNum;
if (woodRoundNum == 0)
{
WoodRoundNum = 9999;
}
WoodDailyMaxCount = woodDailyMaxCount;
if (WoodDailyMaxCount is 0 or >= 2000) WoodDailyMaxCount = 2000;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

@@ -16,6 +16,8 @@ public class ElementAssets : BaseAssets<ElementAssets>
public RecognitionObject PaimonMenuRo;
public RecognitionObject BlueTrackPoint;
public RecognitionObject UiLeftTopCookIcon;
private ElementAssets()
{
// 按钮
@@ -83,5 +85,15 @@ public class ElementAssets : BaseAssets<ElementAssets>
Threshold = 0.6,
DrawOnWindow = true
}.InitTemplate();
// 左上角UI元素
UiLeftTopCookIcon = new RecognitionObject
{
Name = "UiLeftTopCookIcon",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage(@"Common\Element", "ui_left_top_cook_icon.png"),
RegionOfInterest = new Rect(0, 0, (int)(150 * AssetScale), (int)(120 * AssetScale)),
DrawOnWindow = false
}.InitTemplate();
}
}
@@ -1,16 +1,14 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using OpenCvSharp;
using System;
using System.Diagnostics;
using BetterGenshinImpact.Model;
using Point = OpenCvSharp.Point;
using Size = OpenCvSharp.Size;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.AutoTrackPath;
namespace BetterGenshinImpact.GameTask.Common.Map;
@@ -50,7 +48,8 @@ public class EntireMap : Singleton<EntireMap>
// _cityMap2048BlockMat = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\cityMap2048Block.png", ImreadModes.Grayscale);
// Mat grey = new();
// Cv2.CvtColor(_mainMap100BlockMat, grey, ColorConversionCodes.BGR2GRAY);
_featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap1024BlockMat.Value, new FeatureStorage("mainMap1024BlockMat"));
// _featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap1024BlockMat.Value, new FeatureStorage("mainMap1024Block"));
_featureMatcher = new FeatureMatcher(MapAssets.Instance.MainMap2048BlockMat.Value, new FeatureStorage("mainMap2048Block"));
}
/// <summary>
@@ -75,13 +74,15 @@ public class EntireMap : Singleton<EntireMap>
new System.Windows.Rect(p.X, p.Y, TemplateSizeRoi.Width, TemplateSizeRoi.Height)));
}
private int _failCnt = 0;
/// <summary>
/// 基于特征匹配获取地图位置(1024区块)
/// 支持大地图和小地图
/// 基于特征匹配获取地图位置
/// 移动匹配
/// </summary>
/// <param name="greyMat">灰度图</param>
/// <returns></returns>
public Rect GetMapPositionByFeatureMatch(Mat greyMat)
public Rect GetMiniMapPositionByFeatureMatch(Mat greyMat)
{
try
{
@@ -102,11 +103,41 @@ public class EntireMap : Singleton<EntireMap>
var rect = Cv2.BoundingRect(pArray);
_prevX = rect.X + rect.Width / 2;
_prevY = rect.Y + rect.Height / 2;
_failCnt = 0;
return rect;
}
catch
{
(_prevX, _prevY) = (-1, -1);
Debug.WriteLine("Feature Match Failed");
_failCnt++;
if (_failCnt > 5)
{
Debug.WriteLine("Feature Match Failed Too Many Times, 重新从全地图进行特征匹配");
_failCnt = 0;
(_prevX, _prevY) = (-1, -1);
}
return Rect.Empty;
}
}
/// <summary>
/// 基于特征匹配获取地图位置 全部匹配
/// </summary>
/// <param name="greyMat"></param>
/// <returns></returns>
public Rect GetBigMapPositionByFeatureMatch(Mat greyMat)
{
try
{
var pArray = _featureMatcher.Match(greyMat);
if (pArray == null || pArray.Length < 4)
{
throw new InvalidOperationException();
}
return Cv2.BoundingRect(pArray);
}
catch
{
Debug.WriteLine("Feature Match Failed");
return Rect.Empty;
}
@@ -133,11 +164,13 @@ public class EntireMap : Singleton<EntireMap>
public void GetMapPositionAndDrawByFeatureMatch(Mat captureGreyMat)
{
var rect = GetMapPositionByFeatureMatch(captureGreyMat);
var rect = GetMiniMapPositionByFeatureMatch(captureGreyMat);
if (rect != Rect.Empty)
{
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "UpdateBigMapRect", new object(),
new System.Windows.Rect(rect.X / 10.24, rect.Y / 10.24, rect.Width / 10.24, rect.Height / 10.24)));
new System.Windows.Rect(rect.X / 20.48, rect.Y / 20.48, rect.Width / 20.48, rect.Height / 20.48)));
// WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(this, "UpdateBigMapRect", new object(),
// new System.Windows.Rect(rect.X / 10.24, rect.Y / 10.24, rect.Width / 10.24, rect.Height / 10.24)));
}
}
}
@@ -42,4 +42,31 @@ public class MapCoordinate
{
return new Point((GameMapLeftCols + 1) * GameMapBlockWidth - point.X, (GameMapUpRows + 1) * GameMapBlockWidth - point.Y);
}
/// <summary>
/// 原神游戏坐标系 -> 主地图1024区块坐标系
/// </summary>
/// <param name="position">[a,b,c]</param>
/// <returns></returns>
public static Point GameToMain2048(decimal[] position)
{
// 四舍六入五取偶
var a = position[0]; // 上
var c = position[2]; // 左
// 转换1024区块坐标,大地图坐标系正轴是往左上方向的
// 这里写最左上角的区块坐标(GameMapUpRows,GameMapLeftCols)/(上,左),截止4.5版本,最左上角的区块坐标是(5,7)
return new Point((int)(((GameMapLeftCols + 1) * GameMapBlockWidth - c) * 2), (int)(((GameMapUpRows + 1) * GameMapBlockWidth - a) * 2));
}
/// <summary>
/// 主地图1024区块坐标系 -> 原神游戏坐标系
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public static Point Main2048ToGame(Point point)
{
return new Point((GameMapLeftCols + 1) * GameMapBlockWidth - point.X / 2, (GameMapUpRows + 1) * GameMapBlockWidth - point.Y / 2);
}
}
@@ -75,7 +75,7 @@ public class GameLoadingTrigger : ITaskTrigger
// 随便找个相对点击的位置
// _clickOffset?.Click(955, 666);
_postMessageSimulator?.LeftButtonClick();
Simulation.SendInputEx.Mouse.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
_enterGameClickCount++;
}
else
+90 -89
View File
@@ -20,110 +20,111 @@ using BetterGenshinImpact.GameTask.QuickSereniteaPot.Assets;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.View.Drawable;
namespace BetterGenshinImpact.GameTask
namespace BetterGenshinImpact.GameTask;
internal class GameTaskManager
{
internal class GameTaskManager
public static Dictionary<string, ITaskTrigger>? TriggerDictionary { get; set; }
/// <summary>
/// 一定要在任务上下文初始化完毕后使用
/// </summary>
/// <returns></returns>
public static List<ITaskTrigger> LoadTriggers()
{
public static Dictionary<string, ITaskTrigger>? TriggerDictionary { get; set; }
/// <summary>
/// 一定要在任务上下文初始化完毕后使用
/// </summary>
/// <returns></returns>
public static List<ITaskTrigger> LoadTriggers()
ReloadAssets();
TriggerDictionary = new Dictionary<string, ITaskTrigger>()
{
ReloadAssets();
TriggerDictionary = new Dictionary<string, ITaskTrigger>()
{ "RecognitionTest", new TestTrigger() },
{ "GameLoading", new GameLoadingTrigger() },
{ "AutoPick", new AutoPick.AutoPickTrigger() },
{ "QuickTeleport", new QuickTeleport.QuickTeleportTrigger() },
{ "AutoSkip", new AutoSkip.AutoSkipTrigger() },
{ "AutoFishing", new AutoFishing.AutoFishingTrigger() },
{ "AutoCook", new AutoCook.AutoCookTrigger() }
};
var loadedTriggers = TriggerDictionary.Values.ToList();
loadedTriggers.ForEach(i => i.Init());
loadedTriggers = loadedTriggers.OrderByDescending(i => i.Priority).ToList();
return loadedTriggers;
}
public static void RefreshTriggerConfigs()
{
if (TriggerDictionary is { Count: > 0 })
{
TriggerDictionary["AutoPick"].IsEnabled = TaskContext.Instance().Config.AutoPickConfig.Enabled;
// 用于刷新AutoPick的黑白名单
TriggerDictionary["AutoPick"].Init();
TriggerDictionary["AutoSkip"].IsEnabled = TaskContext.Instance().Config.AutoSkipConfig.Enabled;
TriggerDictionary["AutoFishing"].IsEnabled = TaskContext.Instance().Config.AutoFishingConfig.Enabled;
// 钓鱼有很多变量要初始化,直接重新newZA
if (TriggerDictionary["AutoFishing"].IsEnabled == false)
{
{ "RecognitionTest", new TestTrigger() },
{ "GameLoading", new GameLoadingTrigger() },
{ "AutoPick", new AutoPick.AutoPickTrigger() },
{ "QuickTeleport", new QuickTeleport.QuickTeleportTrigger() },
{ "AutoSkip", new AutoSkip.AutoSkipTrigger() },
{ "AutoFishing", new AutoFishing.AutoFishingTrigger() }
};
TriggerDictionary["AutoFishing"].Init();
}
TriggerDictionary["QuickTeleport"].IsEnabled = TaskContext.Instance().Config.QuickTeleportConfig.Enabled;
TriggerDictionary["GameLoading"].Init();
TriggerDictionary["AutoCook"].Init();
// 清理画布
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(new object(), "RemoveAllButton", new object(), ""));
VisionContext.Instance().DrawContent.ClearAll();
}
ReloadAssets();
}
var loadedTriggers = TriggerDictionary.Values.ToList();
public static void ReloadAssets()
{
AutoPickAssets.DestroyInstance();
AutoSkipAssets.DestroyInstance();
AutoFishingAssets.DestroyInstance();
QuickTeleportAssets.DestroyInstance();
AutoWoodAssets.DestroyInstance();
AutoGeniusInvokationAssets.DestroyInstance();
AutoFightAssets.DestroyInstance();
ElementAssets.DestroyInstance();
QuickSereniteaPotAssets.DestroyInstance();
GameLoadingAssets.DestroyInstance();
}
loadedTriggers.ForEach(i => i.Init());
loadedTriggers = loadedTriggers.OrderByDescending(i => i.Priority).ToList();
return loadedTriggers;
/// <summary>
/// 获取素材图片并缩放
/// todo 支持多语言
/// </summary>
/// <param name="featName">任务名称</param>
/// <param name="assertName">素材文件名</param>
/// <param name="flags"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
public static Mat LoadAssetImage(string featName, string assertName, ImreadModes flags = ImreadModes.Color)
{
var info = TaskContext.Instance().SystemInfo;
var assetsFolder = Global.Absolute($@"GameTask\{featName}\Assets\{info.GameScreenSize.Width}x{info.GameScreenSize.Height}");
if (!Directory.Exists(assetsFolder))
{
assetsFolder = Global.Absolute($@"GameTask\{featName}\Assets\1920x1080");
}
public static void RefreshTriggerConfigs()
if (!Directory.Exists(assetsFolder))
{
if (TriggerDictionary is { Count: > 0 })
{
TriggerDictionary["AutoPick"].IsEnabled = TaskContext.Instance().Config.AutoPickConfig.Enabled;
// 用于刷新AutoPick的黑白名单
TriggerDictionary["AutoPick"].Init();
TriggerDictionary["AutoSkip"].IsEnabled = TaskContext.Instance().Config.AutoSkipConfig.Enabled;
TriggerDictionary["AutoFishing"].IsEnabled = TaskContext.Instance().Config.AutoFishingConfig.Enabled;
// 钓鱼有很多变量要初始化,直接重新newZA
if (TriggerDictionary["AutoFishing"].IsEnabled == false)
{
TriggerDictionary["AutoFishing"].Init();
}
TriggerDictionary["QuickTeleport"].IsEnabled = TaskContext.Instance().Config.QuickTeleportConfig.Enabled;
TriggerDictionary["GameLoading"].Init();
// 清理画布
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(new object(), "RemoveAllButton", new object(), ""));
VisionContext.Instance().DrawContent.ClearAll();
}
ReloadAssets();
throw new FileNotFoundException($"未找到{featName}的素材文件夹");
}
public static void ReloadAssets()
var filePath = Path.Combine(assetsFolder, assertName);
if (!File.Exists(filePath))
{
AutoPickAssets.DestroyInstance();
AutoSkipAssets.DestroyInstance();
AutoFishingAssets.DestroyInstance();
QuickTeleportAssets.DestroyInstance();
AutoWoodAssets.DestroyInstance();
AutoGeniusInvokationAssets.DestroyInstance();
AutoFightAssets.DestroyInstance();
ElementAssets.DestroyInstance();
QuickSereniteaPotAssets.DestroyInstance();
GameLoadingAssets.DestroyInstance();
throw new FileNotFoundException($"未找到{featName}中的{assertName}文件");
}
/// <summary>
/// 获取素材图片并缩放
/// todo 支持多语言
/// </summary>
/// <param name="featName">任务名称</param>
/// <param name="assertName">素材文件名</param>
/// <param name="flags"></param>
/// <returns></returns>
/// <exception cref="FileNotFoundException"></exception>
public static Mat LoadAssetImage(string featName, string assertName, ImreadModes flags = ImreadModes.Color)
var mat = Mat.FromStream(File.OpenRead(filePath), flags);
if (info.GameScreenSize.Width != 1920)
{
var info = TaskContext.Instance().SystemInfo;
var assetsFolder = Global.Absolute($@"GameTask\{featName}\Assets\{info.GameScreenSize.Width}x{info.GameScreenSize.Height}");
if (!Directory.Exists(assetsFolder))
{
assetsFolder = Global.Absolute($@"GameTask\{featName}\Assets\1920x1080");
}
if (!Directory.Exists(assetsFolder))
{
throw new FileNotFoundException($"未找到{featName}的素材文件夹");
}
var filePath = Path.Combine(assetsFolder, assertName);
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"未找到{featName}中的{assertName}文件");
}
var mat = Mat.FromStream(File.OpenRead(filePath), flags);
if (info.GameScreenSize.Width != 1920)
{
mat = ResizeHelper.Resize(mat, info.AssetScale);
}
return mat;
mat = ResizeHelper.Resize(mat, info.AssetScale);
}
return mat;
}
}
@@ -7,7 +7,7 @@ namespace BetterGenshinImpact.GameTask.Macro
{
public static void Done()
{
Simulation.SendInputEx.Mouse.MoveMouseBy(TaskContext.Instance().Config.MacroConfig.RunaroundMouseXInterval, 0);
Simulation.SendInput.Mouse.MoveMouseBy(TaskContext.Instance().Config.MacroConfig.RunaroundMouseXInterval, 0);
Thread.Sleep(TaskContext.Instance().Config.MacroConfig.RunaroundInterval);
}
}
@@ -9,5 +9,6 @@ public class ScaleConverter(double scale) : INodeConverter
public (int x, int y, int w, int h) ToPrev(int x, int y, int w, int h)
{
return ((int)(x * scale), (int)(y * scale), (int)(w * scale), (int)(h * scale));
// return (x, y, (int)(w * scale), (int)(h * scale));
}
}
@@ -14,7 +14,7 @@ public class DesktopRegion() : Region(0, 0, PrimaryScreen.WorkingArea.Width, Pri
{
public void DesktopRegionClick(int x, int y, int w, int h)
{
Simulation.SendInputEx.Mouse.MoveMouseTo((x + (w * 1d / 2)) * 65535 / Width,
Simulation.SendInput.Mouse.MoveMouseTo((x + (w * 1d / 2)) * 65535 / Width,
(y + (h * 1d / 2)) * 65535 / Height).LeftButtonClick().Sleep(50).LeftButtonUp();
}
@@ -25,13 +25,13 @@ public class DesktopRegion() : Region(0, 0, PrimaryScreen.WorkingArea.Width, Pri
/// <param name="cy"></param>
public static void DesktopRegionClick(double cx, double cy)
{
Simulation.SendInputEx.Mouse.MoveMouseTo(cx * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
Simulation.SendInput.Mouse.MoveMouseTo(cx * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
cy * 65535 * 1d / PrimaryScreen.WorkingArea.Height).LeftButtonDown().Sleep(50).LeftButtonUp();
}
public static void DesktopRegionMove(double cx, double cy)
{
Simulation.SendInputEx.Mouse.MoveMouseTo(cx * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
Simulation.SendInput.Mouse.MoveMouseTo(cx * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
cy * 65535 * 1d / PrimaryScreen.WorkingArea.Height);
}
@@ -69,11 +69,12 @@ public class GameCaptureRegion(Bitmap bitmap, int initX, int initY, Region? owne
var scale = Width / 1920d;
var newMat = new Mat();
Cv2.Resize(SrcMat, newMat, new Size(1920, 1080));
Cv2.Resize(SrcMat, newMat, new Size(1920, Height / scale));
_srcGreyMat?.Dispose();
_srcMat?.Dispose();
_srcBitmap?.Dispose();
return new ImageRegion(newMat, X, Y, this, new ScaleConverter(scale));
return new ImageRegion(newMat, 0, 0, this, new ScaleConverter(scale));
// return new ImageRegion(newMat, 0, 0, this, new TranslationConverter(0, 0));
}
/// <summary>
@@ -7,5 +7,6 @@ public enum IndependentTaskEnum
AutoFight,
AutoDomain,
AutoTrack,
AutoTrackPath,
AutoMusicGame,
}
@@ -89,7 +89,15 @@ namespace BetterGenshinImpact.GameTask.Model
ScaleTo1080PRatio = GameScreenSize.Width / 1920d; // 1080P 为标准
CaptureAreaRect = SystemControl.GetCaptureRect(hWnd);
ScaleMax1080PCaptureRect = new Rect(CaptureAreaRect.X, CaptureAreaRect.Y, CaptureAreaRect.Width > 1920 ? 1920 : CaptureAreaRect.Width, CaptureAreaRect.Height > 1080 ? 1080 : CaptureAreaRect.Height);
if (CaptureAreaRect.Width > 1920)
{
var scale = CaptureAreaRect.Width / 1920d;
ScaleMax1080PCaptureRect = new Rect(CaptureAreaRect.X, CaptureAreaRect.Y, 1920, (int)(CaptureAreaRect.Height / scale));
}
else
{
ScaleMax1080PCaptureRect = new Rect(CaptureAreaRect.X, CaptureAreaRect.Y, CaptureAreaRect.Width, CaptureAreaRect.Height);
}
}
}
}
@@ -6,6 +6,7 @@ using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using Point = OpenCvSharp.Point;
@@ -95,19 +96,25 @@ public class TestTrigger : ITaskTrigger
//}
// 小地图匹配测试
// var tar = ElementAssets.Instance.PaimonMenuRo.TemplateImageGreyMat!;
// var p = MatchTemplateHelper.MatchTemplate(content.CaptureRectArea.SrcGreyMat, tar, TemplateMatchModes.CCoeffNormed, null, 0.9);
// if (p.X == 0 || p.Y == 0)
// {
// return;
// }
//
// _bigMap.Value.GetMapPositionAndDrawByFeatureMatch(new Mat(content.CaptureRectArea.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
var tar = ElementAssets.Instance.PaimonMenuRo.TemplateImageGreyMat!;
var p = MatchTemplateHelper.MatchTemplate(content.CaptureRectArea.SrcGreyMat, tar, TemplateMatchModes.CCoeffNormed, null, 0.9);
if (p.X == 0 || p.Y == 0)
{
return;
}
var miniMapMat = new Mat(content.CaptureRectArea.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210));
var mask = new Mat(new Size(miniMapMat.Width, miniMapMat.Height), MatType.CV_8UC1, Scalar.Black);
Cv2.Circle(mask, new Point(miniMapMat.Width / 2, miniMapMat.Height / 2), 90, Scalar.White, -1);
var res = new Mat();
Cv2.BitwiseAnd(miniMapMat, miniMapMat, res, mask);
EntireMap.Instance.GetMapPositionAndDrawByFeatureMatch(res);
Cv2.ImWrite(Global.Absolute(@"log\minimap.png"), res);
// 大地图测试
var mat = content.CaptureRectArea.SrcGreyMat;
// mat = mat.Resize(new Size(240, 135));
EntireMap.Instance.GetMapPositionAndDrawByFeatureMatch(mat);
// var mat = content.CaptureRectArea.SrcGreyMat;
// // mat = mat.Resize(new Size(240, 135));
// EntireMap.Instance.GetMapPositionAndDrawByFeatureMatch(mat);
// Bv.BigMapIsUnderground(content.CaptureRectArea);
}
@@ -30,13 +30,13 @@ public class QuickBuyTask
// 选中左边点 742x601
GameCaptureRegion.GameRegion1080PPosMove(742, 601);
TaskControl.CheckAndSleep(100);
Simulation.SendInputEx.Mouse.LeftButtonDown();
Simulation.SendInput.Mouse.LeftButtonDown();
TaskControl.CheckAndSleep(50);
// 向右滑动
Simulation.SendInputEx.Mouse.MoveMouseBy(1000, 0);
Simulation.SendInput.Mouse.MoveMouseBy(1000, 0);
TaskControl.CheckAndSleep(200);
Simulation.SendInputEx.Mouse.LeftButtonUp();
Simulation.SendInput.Mouse.LeftButtonUp();
TaskControl.CheckAndSleep(100);
// 点击弹出页的购买/兑换 1100x780
@@ -60,7 +60,7 @@ public class QuickSereniteaPotTask
try
{
// 打开背包
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_B);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_B);
TaskControl.CheckAndSleep(500);
WaitForBagToOpen();
@@ -79,7 +79,7 @@ public class QuickSereniteaPotTask
TaskControl.CheckAndSleep(800);
// 按F进入
Simulation.SendInputEx.Keyboard.KeyPress(VK.VK_F);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_F);
}
catch (Exception e)
{
@@ -44,9 +44,9 @@ public class QuickTeleportAssets : BaseAssets<QuickTeleportAssets>
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("QuickTeleport", "GoTeleport.png"),
RegionOfInterest = new Rect((int)(1440 * AssetScale),
(int)(979 * AssetScale),
(int)(60 * AssetScale),
(int)(60 * AssetScale)),
CaptureRect.Height - (int)(120 * AssetScale),
(int)(100 * AssetScale),
(int)(120 * AssetScale)),
DrawOnWindow = false
}.InitTemplate();
@@ -25,6 +25,7 @@ using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoSkip.Model;
using Vanara.PInvoke;
using BetterGenshinImpact.GameTask.AutoMusicGame;
using BetterGenshinImpact.GameTask.AutoTrackPath;
namespace BetterGenshinImpact.GameTask
{
@@ -225,6 +226,10 @@ namespace BetterGenshinImpact.GameTask
{
Task.Run(() => { new AutoTrackTask((AutoTrackParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoTrackPath)
{
Task.Run(() => { new AutoTrackPathTask((AutoTrackPathParam)param).Start(); });
}
else if (taskType == IndependentTaskEnum.AutoMusicGame)
{
Task.Run(() => { new AutoMusicGameTask((AutoMusicGameParam)param).Start(); });
@@ -11,7 +11,7 @@ public static class ClickExtension
public static void Click(this Point point)
{
Simulation.SendInputEx.Mouse.MoveMouseTo(point.X * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
Simulation.SendInput.Mouse.MoveMouseTo(point.X * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
point.Y * 65535 * 1d / PrimaryScreen.WorkingArea.Height).LeftButtonDown().Sleep(50).LeftButtonUp();
}
@@ -23,13 +23,13 @@ public static class ClickExtension
public static IMouseSimulator Click(double x, double y)
{
return Simulation.SendInputEx.Mouse.MoveMouseTo(x * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
return Simulation.SendInput.Mouse.MoveMouseTo(x * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
y * 65535 * 1d / PrimaryScreen.WorkingArea.Height).LeftButtonDown().Sleep(50).LeftButtonUp();
}
public static IMouseSimulator Move(double x, double y)
{
return Simulation.SendInputEx.Mouse.MoveMouseTo(x * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
return Simulation.SendInput.Mouse.MoveMouseTo(x * 65535 * 1d / PrimaryScreen.WorkingArea.Width,
y * 65535 * 1d / PrimaryScreen.WorkingArea.Height);
}
@@ -0,0 +1,91 @@
// ReSharper disable InconsistentNaming
using System;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Helpers;
public static class OsVersionHelper
{
private static Version? versionCache;
private static readonly Version _osVersion = GetOSVersion();
public static bool IsWindowsNT { get; } = Environment.OSVersion.Platform == PlatformID.Win32NT;
public static bool IsWindowsXP { get; } = IsWindowsNT && _osVersion == new Version(5, 0);
public static bool IsWindowsXP_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(5, 0);
public static bool IsWindowsVista { get; } = IsWindowsNT && _osVersion == new Version(6, 0);
public static bool IsWindowsVista_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(6, 0);
public static bool IsWindows7 { get; } = IsWindowsNT && _osVersion == new Version(6, 1);
public static bool IsWindows7_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(6, 1);
public static bool IsWindows8 { get; } = IsWindowsNT && _osVersion == new Version(6, 2);
public static bool IsWindows8_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(6, 2);
public static bool IsWindows81 { get; } = IsWindowsNT && _osVersion == new Version(6, 3);
public static bool IsWindows81_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(6, 3);
public static bool IsWindows10 { get; } = IsWindowsNT && _osVersion == new Version(10, 0);
public static bool IsWindows10_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0);
public static bool IsWindows10_1507 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 10240);
public static bool IsWindows10_1507_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 10240);
public static bool IsWindows10_1511 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 10586);
public static bool IsWindows10_1511_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 10586);
public static bool IsWindows10_1607 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 14393);
public static bool IsWindows10_1607_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 14393);
public static bool IsWindows10_1703 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 15063);
public static bool IsWindows10_1703_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 15063);
public static bool IsWindows10_1709 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 16299);
public static bool IsWindows10_1709_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 16299);
public static bool IsWindows10_1803 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 17134);
public static bool IsWindows10_1803_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 17134);
public static bool IsWindows10_1809 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 17763);
public static bool IsWindows10_1809_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 17763);
public static bool IsWindows10_1903 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 18362);
public static bool IsWindows10_1903_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 18362);
public static bool IsWindows10_1909 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 18363);
public static bool IsWindows10_1909_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 18363);
public static bool IsWindows10_2004 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 19041);
public static bool IsWindows10_2004_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 19041);
public static bool IsWindows10_2009 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 19042);
public static bool IsWindows10_2009_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 19042);
public static bool IsWindows10_21H1 { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 19043);
public static bool IsWindows10_21H1_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 19043);
public static bool IsWindows11 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 22000);
public static bool IsWindows11_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 22000);
public static bool IsWindows11_22523 { get; } = IsWindowsNT && _osVersion == new Version(10, 0, 22523);
public static bool IsWindows11_22523_OrGreater { get; } = IsWindowsNT && _osVersion >= new Version(10, 0, 22523);
public static Version GetOSVersion()
{
if (versionCache is null)
{
if (NtDll.RtlGetVersion(out var osv) != 0)
{
throw new PlatformNotSupportedException("Setup can only run on Windows.");
}
versionCache = new Version((int)osv.dwMajorVersion, (int)osv.dwMinorVersion, (int)osv.dwBuildNumber, (int)osv.dwPlatformId);
}
return versionCache;
}
public static void ThrowIfNotVista()
{
if (!IsWindowsVista_OrGreater)
{
throw new PlatformNotSupportedException("Only supported on Windows Vista or newer.");
}
}
public static void ThrowIfNotWin7()
{
if (!IsWindows7_OrGreater)
{
throw new PlatformNotSupportedException("Only supported on Windows 7 or newer.");
}
}
public static void ThrowIfNotXP()
{
if (!IsWindowsXP_OrGreater)
{
throw new PlatformNotSupportedException("Only supported on Windows XP or newer.");
}
}
}
+6 -2
View File
@@ -16,13 +16,17 @@ internal static class RuntimeHelper
public static bool IsElevated { get; } = GetElevated();
public static bool IsDebuggerAttached => Debugger.IsAttached;
public static bool IsDesignMode { get; } = GetDesignMode();
public static bool IsDebug =>
#if DEBUG
true;
#else
false;
#endif
public static bool IsGpuPackage => true;
private static bool GetElevated()
{
using WindowsIdentity identity = WindowsIdentity.GetCurrent();
@@ -81,9 +85,9 @@ internal static class RuntimeHelper
catch (Exception ex)
{
Debug.WriteLine(ex);
MessageBox.Show("以管理员权限启动 BetterGI 失败,非管理员权限下所有模拟操作功能均不可用!\r\n请尝试 右键 —— 以管理员身份运行 的方式启动 BetterGI",
MessageBox.Show("以管理员权限启动 BetterGI 失败,非管理员权限下所有模拟操作功能均不可用!\r\n请尝试 右键 —— 以管理员身份运行 的方式启动 BetterGI",
"警告", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
return;
}
}
catch (Win32Exception)
@@ -0,0 +1,5 @@
仆人 e
钟离 s(0.1),e(hold)
班尼特 e,q
枫原万叶 attack,dash,e,attack,q
仆人 e,charge(0.52),attack(2),dash,attack(2),dash
@@ -1,7 +1,7 @@
角色定义:
角色1=莫娜|水{技能3消耗=1水骰子+2任意,技能2消耗=3水骰子,技能1消耗=3水骰子}
角色3=皇女|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=3雷骰子}
角色2=白术|草{技能3消耗=1草骰子+2任意,技能2消耗=3草骰子,技能1消耗=4草骰子}
角色3=皇女|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=3雷骰子}
---
策略定义:
@@ -3,10 +3,15 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="CaptureTestWindow" Height="450" Width="800">
Title="CaptureTestWindow"
Width="800"
Height="450"
FontFamily="{DynamicResource TextThemeFontFamily}"
mc:Ignorable="d">
<Grid>
<Image x:Name="DisplayCaptureResultImage" Height="Auto" Width="Auto" />
<Image x:Name="DisplayCaptureResultImage"
Width="Auto"
Height="Auto" />
</Grid>
</Window>
@@ -0,0 +1,15 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
<FontFamily x:Key="FgiIconFontFamily">/Assets/Fonts/#FgiRegular</FontFamily>
<Style x:Key="FaFontIconStyle" TargetType="ui:FontIcon">
<Setter Property="Width" Value="32" />
<Setter Property="Margin" Value="0,0,-8,0" />
<Setter Property="FontFamily" Value="{StaticResource FgiIconFontFamily}" />
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="0.79167" ScaleY="0.79167" />
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
+1
View File
@@ -18,6 +18,7 @@
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ExtendsContentIntoTitleBar="True"
FontFamily="{StaticResource TextThemeFontFamily}"
Visibility="{Binding IsVisible, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter}}"
WindowStartupLocation="CenterScreen"
WindowState="{Binding WindowState, Mode=TwoWay}"
+7 -4
View File
@@ -8,6 +8,7 @@
Width="500"
Height="800"
AllowsTransparency="True"
FontFamily="{DynamicResource TextThemeFontFamily}"
ShowInTaskbar="False"
Topmost="True"
WindowStyle="None">
@@ -63,9 +64,10 @@
Height="188"
Style="{StaticResource OuterDraggableResizableItemStyle}">
<RichTextBox x:Name="LogTextBox"
Padding="0,5,0,0"
Background="Transparent"
BorderThickness="0"
FontFamily="Cascadia Mono, Consolas, Courier New, monospace"
FontFamily="Cascadia Mono, Consolas, Courier New, monospace, /Assets/Fonts/MiSans-Regular.ttf#MiSans"
FontSize="12"
Foreground="LightGray"
IsHitTestVisible="False"
@@ -97,10 +99,12 @@
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Margin" Value="0,0,8,0"/>
<Setter Property="Margin" Value="0,0,8,0" />
</Style>
</StackPanel.Resources>
<TextBlock Text="{Binding Name}" FontSize="12">
<TextBlock FontFamily="{StaticResource FgiIconFontFamily}"
FontSize="12"
Text="{Binding Name}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="LightGray" />
@@ -123,7 +127,6 @@
Canvas.Top="150"
Canvas.Left="470"
Style="{StaticResource DraggableResizableItemStyle}">
<Grid>
<Rectangle Fill="White" IsHitTestVisible="False" Opacity="0.2" />
<TextBlock Text="识别窗口" Foreground="White" TextAlignment="Center" VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
+26 -3
View File
@@ -28,10 +28,19 @@ public partial class MaskWindow : Window
{
private static MaskWindow? _maskWindow;
private static readonly Typeface MyTypeface = new FontFamily("Microsoft Yahei UI").GetTypefaces().First();
private static readonly Typeface _typeface;
static MaskWindow()
{
if (Application.Current.TryFindResource("TextThemeFontFamily") is FontFamily fontFamily)
{
_typeface = fontFamily.GetTypefaces().First();
}
else
{
_typeface = new FontFamily("Microsoft Yahei UI").GetTypefaces().First();
}
DefaultStyleKeyProperty.OverrideMetadata(typeof(MaskWindow), new FrameworkPropertyMetadata(typeof(MaskWindow)));
}
@@ -97,6 +106,7 @@ public partial class MaskWindow : Window
{
base.OnSourceInitialized(e);
this.SetLayeredWindow();
this.HideFromAltTab();
}
private void LogTextBoxTextChanged(object sender, TextChangedEventArgs e)
@@ -166,7 +176,7 @@ public partial class MaskWindow : Window
drawingContext.DrawText(new FormattedText(drawable.Text,
CultureInfo.GetCultureInfo("zh-cn"),
FlowDirection.LeftToRight,
MyTypeface,
_typeface,
36, Brushes.Black, 1), drawable.Point);
}
}
@@ -185,6 +195,19 @@ public partial class MaskWindow : Window
file static class MaskWindowExtension
{
public static void HideFromAltTab(this Window window)
{
HideFromAltTab(new WindowInteropHelper(window).Handle);
}
public static void HideFromAltTab(nint hWnd)
{
int style = User32.GetWindowLong(hWnd, User32.WindowLongFlags.GWL_EXSTYLE);
style |= (int)User32.WindowStylesEx.WS_EX_TOOLWINDOW;
User32.SetWindowLong(hWnd, User32.WindowLongFlags.GWL_EXSTYLE, style);
}
public static void SetLayeredWindow(this Window window, bool isLayered = true)
{
SetLayeredWindow(new WindowInteropHelper(window).Handle, isLayered);
@@ -207,4 +230,4 @@ file static class MaskWindowExtension
_ = User32.SetWindowLong(hWnd, User32.WindowLongFlags.GWL_EXSTYLE, style);
}
}
}
@@ -15,6 +15,7 @@
d:DesignWidth="600"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
+30 -2
View File
@@ -13,6 +13,7 @@
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
@@ -79,7 +80,7 @@
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="BetterGI · 更好的原神,启动!"
Text="BetterGI 截图器,启动!"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
@@ -193,6 +194,33 @@
IsChecked="{Binding Config.WgcUseBitmapCache, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="切换AI推理设备"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="GPU推理需要安装CUDA,切换后需要重启程序"
TextWrapping="Wrap" />
<ComboBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
ItemsSource="{Binding InferenceDevices}"
SelectedItem="{Binding Config.InferenceDevice, Mode=TwoWay}" />
</Grid>
<Separator Margin="-18,0" BorderThickness="0,1,0,0" />
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -298,7 +326,7 @@
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="启动 BetterGI 时,如果原神未启动,则自动启动原神。"
Text="启动截图器时,如果原神未启动,则自动启动原神。"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
+12 -12
View File
@@ -3,17 +3,18 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hotKey="clr-namespace:BetterGenshinImpact.View.Controls.HotKey"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:model="clr-namespace:BetterGenshinImpact.Model"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:hotKey="clr-namespace:BetterGenshinImpact.View.Controls.HotKey"
Title="HotkeyPage"
d:DataContext="{d:DesignInstance Type=pages:HotKeyPageViewModel}"
d:DesignHeight="850"
d:DesignWidth="600"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
@@ -30,8 +31,8 @@
<ui:TextBlock Grid.Row="1"
Margin="0,0,0,8"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
TextWrapping="Wrap"
Text="全局热键:只支持组合键和功能键,软件启动直接生效。键鼠监听:支持任意键盘单键、鼠标侧键,功能启动后才生效(推荐)。点击类型按钮可以切换快捷键类型。其中存在长按需求的功能不能使用全局热键。" />
Text="全局热键:只支持组合键和功能键,软件启动直接生效。键鼠监听:支持任意键盘单键、鼠标侧键,功能启动后才生效(推荐)。点击类型按钮可以切换快捷键类型。其中存在长按需求的功能不能使用全局热键。"
TextWrapping="Wrap" />
<ItemsControl Grid.Row="2" ItemsSource="{Binding HotKeySettingModels}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type model:HotKeySettingModel}">
@@ -44,18 +45,17 @@
<ui:TextBlock Grid.Column="0"
VerticalAlignment="Center"
Text="{Binding FunctionName}" />
<ui:Button Grid.Column="1"
HorizontalAlignment="Right"
<ui:Button Grid.Column="1"
Margin="0,0,8,0"
Content="{Binding HotKeyTypeName, Mode=OneWay}"
HorizontalAlignment="Right"
Command="{Binding SwitchHotKeyTypeCommand}"
IsEnabled="{Binding SwitchHotkeyTypeEnabled, Mode=OneWay}"
/>
Content="{Binding HotKeyTypeName, Mode=OneWay}"
IsEnabled="{Binding SwitchHotkeyTypeEnabled, Mode=OneWay}" />
<hotKey:HotKeyTextBox Grid.Column="2"
HotKeyTypeName="{Binding HotKeyTypeName, Mode=OneWay}"
Hotkey="{Binding HotKey}"
Style="{StaticResource DefaultTextBoxStyle}"
TextAlignment="Center" />
HotKeyTypeName="{Binding HotKeyTypeName, Mode=OneWay}"
Hotkey="{Binding HotKey}"
Style="{StaticResource DefaultTextBoxStyle}"
TextAlignment="Center" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
@@ -12,6 +12,7 @@
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<StackPanel Margin="42,16,42,12">
@@ -13,6 +13,7 @@
d:DesignWidth="600"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
@@ -91,26 +92,26 @@
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="测试"
TextWrapping="Wrap" />
Grid.Column="0"
FontTypography="Body"
Text="测试"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="发送测试载荷"
TextWrapping="Wrap" />
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="发送测试载荷"
TextWrapping="Wrap" />
<ui:Button Grid.Row="0"
Grid.Column="1"
HorizontalAlignment="Right"
Margin="0,0,36,0"
Content="发送"
HorizontalAlignment="Right"
Command="{Binding TestWebhookCommand}"
Content="发送"
IsEnabled="{Binding IsLoading, Converter={StaticResource InverseBooleanConverter}}" />
<ui:TextBlock Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Right"
Margin="0,0,36,0"
HorizontalAlignment="Right"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="{Binding WebhookStatus}"
TextWrapping="Wrap" />
@@ -13,6 +13,7 @@
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<Grid>
@@ -15,6 +15,7 @@
d:DesignWidth="750"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
@@ -80,9 +81,10 @@
<ui:TextBlock Margin="0,0,0,8"
FontTypography="BodyStrong"
Text="独立任务设置" />
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon PlayingCards20}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf6d2;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -179,9 +181,10 @@
</StackPanel>
</ui:CardExpander>
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon LeafThree24}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf6b2;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -240,6 +243,57 @@
Margin="0,0,36,0"
Text="{Binding AutoWoodRoundNum, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="启用伐木数量限制(建议1080P以上分辨率)"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="伐木后识别并累计木材数,达到上限后自动停止伐木"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.AutoWoodConfig.WoodCountOcrEnabled, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="伐木数量上限(原神每日每种木材最多2000)"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="启用伐木数量限制后生效,达到配置上限后自动停止伐木"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
MinWidth="90"
Margin="0,0,36,0"
Text="{Binding AutoWoodDailyMaxCount, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -266,12 +320,39 @@
Margin="0,0,36,0"
Text="{Binding Config.AutoWoodConfig.AfterZSleepDelay, Mode=TwoWay}" />
</Grid>
<!--<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="按下两次ESC(其中一下ESC是消除木材已满的提示)"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="多木材点情况下,一种木材已满的时候使用这个功能"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.AutoWoodConfig.PressTwoEscEnabled, Mode=TwoWay}" />
</Grid>-->
</StackPanel>
</ui:CardExpander>
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon ArrowSyncCircle24}">
<!-- 自动战斗 -->
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf71d;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -368,9 +449,11 @@
</StackPanel>
</ui:CardExpander>
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon BuildingBankToolbox24}">
<!-- 自动刷本 -->
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf438;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -597,9 +680,13 @@
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon PeopleQueue24}"
Visibility="{markup:Converter Value={x:Static helpers:RuntimeHelper.IsDebuggerAttached},
Converter={StaticResource BooleanToVisibilityConverter}}">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf54b;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -663,7 +750,11 @@
</StackPanel>
</ui:CardExpander>
<ui:CardControl Margin="0,0,0,12" Icon="{ui:SymbolIcon MusicNote224}">
<!-- 活动音游(限时,已失效) -->
<ui:CardControl Margin="0,0,0,12"
Icon="{ui:SymbolIcon MusicNote224}"
Visibility="{markup:Converter Value={x:Static helpers:RuntimeHelper.IsDebuggerAttached},
Converter={StaticResource BooleanToVisibilityConverter}}">
<ui:CardControl.Header>
<Grid>
<Grid.RowDefinitions>
@@ -673,13 +764,16 @@
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="活动音游"
Text="活动音游(限时,已失效)"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="下落模式必须选择垂落模式,进入演奏界面使用,建议配置快捷键"
TextWrapping="Wrap" />
TextWrapping="Wrap">
进入演奏界面使用,下落模式必须选择垂落模式 -<Hyperlink Command="{Binding GoToAutoMusicGameUrlCommand}" Foreground="{ui:ThemeResource TextFillColorSecondaryBrush}">
点击查看使用教程
</Hyperlink>
</ui:TextBlock>
</Grid>
</ui:CardControl.Header>
<ui:Button Margin="0,0,36,0"
@@ -2,9 +2,9 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BetterGenshinImpact.View.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:system="clr-namespace:System;assembly=System.Runtime"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="HomePage"
d:DataContext="{d:DesignInstance Type=pages:TriggerSettingsPageViewModel}"
@@ -12,9 +12,12 @@
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<StackPanel Margin="42,16,42,12">
<ui:TextBlock Margin="0,0,0,8"
FontTypography="BodyStrong"
Text="实时触发的自动化任务设置" />
@@ -160,9 +163,10 @@
</ui:CardExpander>
<!-- 自动剧情 -->
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon PlayCircle24}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf075;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -331,9 +335,10 @@
<!-- 自动邀约 -->
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon CommentMultiple24}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xe5c8;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -482,9 +487,10 @@
</ui:CardExpander>
<!-- 快速传送 -->
<ui:CardExpander Margin="0,0,0,12"
ContentPadding="0"
Icon="{ui:SymbolIcon DoorArrowLeft24}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf3c5;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
<ui:CardExpander.Header>
<Grid>
<Grid.RowDefinitions>
@@ -596,6 +602,33 @@
</StackPanel>
</ui:CardExpander>
<!-- 自动烹饪 -->
<ui:CardControl Margin="0,0,0,12">
<ui:CardControl.Icon>
<ui:FontIcon Glyph="&#xe43f;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardControl.Icon>
<ui:CardControl.Header>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="自动烹饪"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
TextWrapping="Wrap">
手动烹饪时,自动在完美状态下结束烹饪(不用的时候请关闭)
</ui:TextBlock>
</Grid>
</ui:CardControl.Header>
<ui:ToggleSwitch Margin="0,0,36,0" IsChecked="{Binding Config.AutoCookConfig.Enabled, Mode=TwoWay}" />
</ui:CardControl>
<!-- 一键战斗 -->
<!--<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" Icon="{ui:SymbolIcon ArrowSync24}">
<ui:CardExpander.Header>
+13 -12
View File
@@ -3,27 +3,28 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="选择捕获窗口" Height="450" Width="800">
Title="选择捕获窗口"
Width="800"
Height="450"
FontFamily="{DynamicResource TextThemeFontFamily}"
mc:Ignorable="d">
<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<StackPanel
Grid.Row="0"
Margin="5,0"
Orientation="Horizontal"
Background="White">
<StackPanel Grid.Row="0"
Margin="5,0"
Background="White"
Orientation="Horizontal">
<TextBlock FontSize="20" Text="双击选中要捕获的窗口" />
</StackPanel>
<ListBox
x:Name="WindowList"
Grid.Row="1"
Padding="0,10"
BorderThickness="0">
<ListBox x:Name="WindowList"
Grid.Row="1"
Padding="0,10"
BorderThickness="0">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl MouseDoubleClick="WindowsOnMouseDoubleClick">
@@ -12,6 +12,7 @@
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ExtendsContentIntoTitleBar="True"
FontFamily="{DynamicResource TextThemeFontFamily}"
Tag="JsonMonoDialog"
WindowStartupLocation="CenterOwner"
mc:Ignorable="d">
@@ -14,6 +14,7 @@
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ExtendsContentIntoTitleBar="True"
FontFamily="{DynamicResource TextThemeFontFamily}"
ResizeMode="CanMinimize"
WindowStartupLocation="CenterScreen"
WindowStyle="SingleBorderWindow"
@@ -12,6 +12,7 @@
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
ExtendsContentIntoTitleBar="True"
FontFamily="{DynamicResource TextThemeFontFamily}"
ResizeMode="CanMinimize"
WindowStartupLocation="CenterScreen"
WindowStyle="SingleBorderWindow"
@@ -23,7 +23,7 @@ public partial class MainWindowViewModel : ObservableObject, IViewModel
{
private readonly ILogger<MainWindowViewModel> _logger;
private readonly IConfigService _configService;
public string Title => $"BetterGI · 更好的原神 · {Global.Version}{(RuntimeHelper.IsDebug ? " · Dev" : string.Empty)}";
public string Title => $"BetterGI · 更好的原神 · {Global.Version}{(RuntimeHelper.IsDebug ? " · Dev" : string.Empty)}{(RuntimeHelper.IsGpuPackage ? " · GPU" : string.Empty)}";
[ObservableProperty]
public bool _isVisible = true;
@@ -30,7 +30,6 @@ namespace BetterGenshinImpact.ViewModel
[ObservableProperty] private Point _westPoint = new(32, 109);
[ObservableProperty] private Point _northPoint = new(150, -9);
public MaskWindowViewModel()
{
WeakReferenceMessenger.Default.Register<PropertyChangedMessage<object>>(this, (sender, msg) =>
@@ -74,11 +73,11 @@ namespace BetterGenshinImpact.ViewModel
{
if (Config != null)
{
StatusList.Add(new StatusItem("自动拾取", Config.AutoPickConfig));
StatusList.Add(new StatusItem("自动剧情", Config.AutoSkipConfig));
StatusList.Add(new StatusItem("自动邀约", Config.AutoSkipConfig, "AutoHangoutEventEnabled"));
StatusList.Add(new StatusItem("自动钓鱼", Config.AutoFishingConfig));
StatusList.Add(new StatusItem("快速传送", Config.QuickTeleportConfig));
StatusList.Add(new StatusItem("\uf256 拾取", Config.AutoPickConfig));
StatusList.Add(new StatusItem("\uf075 剧情", Config.AutoSkipConfig));
StatusList.Add(new StatusItem("\ue5c8 邀约", Config.AutoSkipConfig, "AutoHangoutEventEnabled"));
StatusList.Add(new StatusItem("\uf578 钓鱼", Config.AutoFishingConfig));
StatusList.Add(new StatusItem("\uf3c5 传送", Config.QuickTeleportConfig));
}
}
@@ -98,12 +97,13 @@ namespace BetterGenshinImpact.ViewModel
// 比较特殊,必须要启动过任务调度器才能够获取到缩放信息
if (TaskContext.Instance().SystemInfo != null)
{
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var captureRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
var assetScale = TaskContext.Instance().SystemInfo.ScaleTo1080PRatio;
var dpiScale = TaskContext.Instance().DpiScale;
UidCoverRect = new Rect(Config.MaskWindowConfig.UidCoverRect.X * assetScale / dpiScale,
Config.MaskWindowConfig.UidCoverRect.Y * assetScale / dpiScale,
Config.MaskWindowConfig.UidCoverRect.Width * assetScale / dpiScale,
Config.MaskWindowConfig.UidCoverRect.Height * assetScale / dpiScale);
UidCoverRect = new Rect((captureRect.Width - Config.MaskWindowConfig.UidCoverRightBottomRect.X * assetScale) / dpiScale,
(captureRect.Height - Config.MaskWindowConfig.UidCoverRightBottomRect.Y * assetScale) / dpiScale,
Config.MaskWindowConfig.UidCoverRightBottomRect.Width * assetScale / dpiScale,
Config.MaskWindowConfig.UidCoverRightBottomRect.Height * assetScale / dpiScale);
EastPoint = new Point(Config.MaskWindowConfig.EastPoint.X * assetScale / dpiScale,
Config.MaskWindowConfig.EastPoint.Y * assetScale / dpiScale);
SouthPoint = new Point(Config.MaskWindowConfig.SouthPoint.X * assetScale / dpiScale,
@@ -131,4 +131,4 @@ namespace BetterGenshinImpact.ViewModel
}
}
}
}
}
@@ -13,6 +13,7 @@ using Fischless.GameCapture;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Interop;
using Windows.System;
@@ -47,11 +48,21 @@ public partial class HomePageViewModel : ObservableObject, INavigationAware, IVi
// 记录上次使用原神的句柄
private IntPtr _hWnd;
[ObservableProperty] private string[] _inferenceDevices = ["CPU", "GPU"];
public HomePageViewModel(IConfigService configService, TaskTriggerDispatcher taskTriggerDispatcher)
{
_taskDispatcher = taskTriggerDispatcher;
Config = configService.Get();
ReadGameInstallPath();
// WindowsGraphicsCapture 只支持 Win10 18362 及以上的版本 (Windows 10 version 1903 or later)
// https://github.com/babalae/better-genshin-impact/issues/394
if (!OsVersionHelper.IsWindows10_1903_OrGreater)
{
_modeNames = _modeNames.Where(x => x != CaptureModes.WindowsGraphicsCapture.ToString()).ToArray();
}
WeakReferenceMessenger.Default.Register<PropertyChangedMessage<object>>(this, (sender, msg) =>
{
if (msg.PropertyName == "Close")
@@ -7,6 +7,7 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common;
@@ -18,7 +19,9 @@ using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using BetterGenshinImpact.GameTask.QucikBuy;
using BetterGenshinImpact.GameTask.QuickSereniteaPot;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Model;
using Vanara.PInvoke;
namespace BetterGenshinImpact.ViewModel.Pages;
@@ -275,14 +278,6 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
(_, _) => { _taskSettingsPageViewModel.OnSwitchAutoDomain(); }
));
// HotKeySettingModels.Add(new HotKeySettingModel(
// "(测试)启动/停止自动追踪",
// nameof(Config.HotKeyConfig.AutoTrackHotkey),
// Config.HotKeyConfig.AutoTrackHotkey,
// Config.HotKeyConfig.AutoTrackHotkeyType,
// (_, _) => { _taskSettingsPageViewModel.OnSwitchAutoTrack(); }
// ));
HotKeySettingModels.Add(new HotKeySettingModel(
"快捷点击原神内确认按钮",
nameof(Config.HotKeyConfig.ClickGenshinConfirmButtonHotkey),
@@ -331,16 +326,6 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
OnKeyUpAction = (_, _) => { OneKeyFightTask.Instance.KeyUp(); }
});
// HotKeySettingModels.Add(new HotKeySettingModel(
// "(测试)地图路线录制",
// nameof(Config.HotKeyConfig.MapPosRecordHotkey),
// Config.HotKeyConfig.MapPosRecordHotkey,
// Config.HotKeyConfig.MapPosRecordHotkeyType,
// (_, _) =>
// {
// PathPointRecorder.Instance.Switch();
// }));
HotKeySettingModels.Add(new HotKeySettingModel(
"启动/停止自动活动音游",
nameof(Config.HotKeyConfig.AutoMusicGameHotkey),
@@ -348,6 +333,50 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
Config.HotKeyConfig.AutoMusicGameHotkeyType,
(_, _) => { _taskSettingsPageViewModel.OnSwitchAutoMusicGame(); }
));
if (RuntimeHelper.IsDebug)
{
HotKeySettingModels.Add(new HotKeySettingModel(
"(测试)启动/停止自动追踪",
nameof(Config.HotKeyConfig.AutoTrackHotkey),
Config.HotKeyConfig.AutoTrackHotkey,
Config.HotKeyConfig.AutoTrackHotkeyType,
(_, _) => { _taskSettingsPageViewModel.OnSwitchAutoTrack(); }
));
HotKeySettingModels.Add(new HotKeySettingModel(
"(测试)地图路线录制",
nameof(Config.HotKeyConfig.MapPosRecordHotkey),
Config.HotKeyConfig.MapPosRecordHotkey,
Config.HotKeyConfig.MapPosRecordHotkeyType,
(_, _) =>
{
PathPointRecorder.Instance.Switch();
}));
HotKeySettingModels.Add(new HotKeySettingModel(
"(测试)自动寻路",
nameof(Config.HotKeyConfig.AutoTrackPathHotkey),
Config.HotKeyConfig.AutoTrackPathHotkey,
Config.HotKeyConfig.AutoTrackPathHotkeyType,
(_, _) => { _taskSettingsPageViewModel.OnSwitchAutoTrackPath(); }
));
PostMessageSimulator? postMessageSimulator = null;
HotKeySettingModels.Add(new HotKeySettingModel(
"(测试)按键模拟测试",
nameof(Config.HotKeyConfig.Test1Hotkey),
Config.HotKeyConfig.Test1Hotkey,
Config.HotKeyConfig.Test1HotkeyType,
(_, _) =>
{
if (postMessageSimulator == null)
{
postMessageSimulator = Simulation.PostMessage(TaskContext.Instance().GameHandle);
}
// postMessageSimulator.KeyPressBackground(User32.VK.VK_W);
postMessageSimulator.LeftButtonClickBackground(1340, 655);
}
));
}
}
private string ToChinese(bool enabled)
@@ -18,6 +18,7 @@ using Wpf.Ui;
using Wpf.Ui.Controls;
using MessageBox = System.Windows.MessageBox;
using BetterGenshinImpact.GameTask.AutoMusicGame;
using BetterGenshinImpact.GameTask.AutoTrackPath;
namespace BetterGenshinImpact.ViewModel.Pages;
@@ -35,6 +36,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
[ObservableProperty] private string _switchAutoGeniusInvokationButtonText = "启动";
[ObservableProperty] private int _autoWoodRoundNum;
[ObservableProperty] private int _autoWoodDailyMaxCount = 2000;
[ObservableProperty] private string _switchAutoWoodButtonText = "启动";
[ObservableProperty] private string[] _combatStrategyList;
@@ -42,6 +44,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
[ObservableProperty] private string _switchAutoDomainButtonText = "启动";
[ObservableProperty] private string _switchAutoFightButtonText = "启动";
[ObservableProperty] private string _switchAutoTrackButtonText = "启动";
[ObservableProperty] private string _switchAutoTrackPathButtonText = "启动";
[ObservableProperty] private string _switchAutoMusicGameButtonText = "启动";
public TaskSettingsPageViewModel(IConfigService configService, INavigationService navigationService, TaskTriggerDispatcher taskTriggerDispatcher)
@@ -166,7 +169,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
{
_cts?.Cancel();
_cts = new CancellationTokenSource();
var param = new WoodTaskParam(_cts, AutoWoodRoundNum);
var param = new WoodTaskParam(_cts, AutoWoodRoundNum, AutoWoodDailyMaxCount);
_taskDispatcher.StartIndependentTask(IndependentTaskEnum.AutoWood, param);
SwitchAutoWoodButtonText = "停止";
}
@@ -186,7 +189,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
[RelayCommand]
public void OnGoToAutoWoodUrl()
{
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E4%BC%90%E6%9C%A8") { UseShellExecute = true });
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/feats/felling.html") { UseShellExecute = true });
}
[RelayCommand]
@@ -334,6 +337,40 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/feats/track.html") { UseShellExecute = true });
}
[RelayCommand]
public void OnSwitchAutoTrackPath()
{
try
{
lock (_locker)
{
if (SwitchAutoTrackPathButtonText == "启动")
{
_cts?.Cancel();
_cts = new CancellationTokenSource();
var param = new AutoTrackPathParam(_cts);
_taskDispatcher.StartIndependentTask(IndependentTaskEnum.AutoTrackPath, param);
SwitchAutoTrackPathButtonText = "停止";
}
else
{
_cts?.Cancel();
SwitchAutoTrackPathButtonText = "启动";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
[RelayCommand]
public void OnGoToAutoTrackPathUrl()
{
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/feats/track.html") { UseShellExecute = true });
}
[RelayCommand]
public void OnSwitchAutoMusicGame()
{
@@ -365,7 +402,7 @@ public partial class TaskSettingsPageViewModel : ObservableObject, INavigationAw
[RelayCommand]
public void OnGoToAutoMusicGameUrl()
{
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/") { UseShellExecute = true });
Process.Start(new ProcessStartInfo("https://bgi.huiyadan.com/feats/music.html") { UseShellExecute = true });
}
public static void SetSwitchAutoTrackButtonText(bool running)
@@ -59,7 +59,7 @@ public static class OsVersionHelper
throw new PlatformNotSupportedException("Setup can only run on Windows.");
}
versionCache = new Version(osv.MajorVersion, osv.MinorVersion, osv.BuildNumber, osv.Revision);
versionCache = new Version(osv.MajorVersion, osv.MinorVersion, osv.BuildNumber, osv.PlatformId);
}
return versionCache;
}
-1
View File
@@ -177,7 +177,6 @@ public struct OSVERSIONINFOEX
public int MajorVersion;
public int MinorVersion;
public int BuildNumber;
public int Revision;
public int PlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
-4
View File
@@ -1,9 +1,5 @@
using MicaSetup.Design.Controls;
using MicaSetup.Design.Controls;
using MicaSetup.Helper;
using System;
using System.ComponentModel;
using System.Windows.Media;
+2 -3
View File
@@ -1,5 +1,4 @@
using System.Diagnostics;
using Vanara.PInvoke;
namespace Fischless.KeyboardCapture;
@@ -117,8 +116,8 @@ public class KeyboardReader : IDisposable
DateTime now = DateTime.Now;
#if true
//Debug.WriteLine(e.KeyCode);
#if false
Debug.WriteLine(e.KeyCode);
#endif
KeyboardItem item;
+6 -1
View File
@@ -26,6 +26,7 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
* 与凯瑟琳对话时有橙色选项会 [自动领取「每日委托」奖励](https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E9%A2%86%E5%8F%96%E3%80%8E%E6%AF%8F%E6%97%A5%E5%A7%94%E6%89%98%E3%80%8F%E5%A5%96%E5%8A%B1)、[自动重新派遣](https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E9%87%8D%E6%96%B0%E6%B4%BE%E9%81%A3)
* [自动邀约](https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E9%82%80%E7%BA%A6):自动剧情开启的情况下此功能才会生效,自动选择邀约选项
* [全自动钓鱼](https://bgi.huiyadan.com/doc.html#%E5%85%A8%E8%87%AA%E5%8A%A8%E9%92%93%E9%B1%BC):AI 识别自动抛竿,鱼上钩时自动收杆,并自动完成钓鱼进度
* [自动烹饪](https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E7%83%B9%E9%A5%AA):自动在完美区域完成食物烹饪,暂不支持“仙跳墙”
* [全自动七圣召唤](https://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E4%B8%83%E5%9C%A3%E5%8F%AC%E5%94%A4):帮助你轻松完成七圣召唤角色邀请、每周来客挑战等 PVE 内容
* [自动伐木](http://bgi.huiyadan.com/doc.html#%E8%87%AA%E5%8A%A8%E4%BC%90%E6%9C%A8):自动 <kbd>Z</kbd> 键使用「王树瑞佑」,利用上下线可以刷新木材的原理,挂机刷满一背包的木材
* [自动战斗](http://bgi.huiyadan.com/feats/domain.html):编写战斗脚本,让队伍按照你的策略进行自动战斗
@@ -98,6 +99,10 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
格式化:[CodeMaid.config](CodeMaid.config)、[Settings.XamlStyler](Settings.XamlStyler);
## 许可证
![GPL-v3](https://www.gnu.org/graphics/gplv3-127x51.png)
## 问题反馈
提 [Issue](https://github.com/babalae/genius-invokation-auto-toy/issues) 或 QQ群[906536632](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=_nmC8Neh7mZaGb2hIsO3p4-DKdxBlReQ&authKey=X7rGdx4jbA%2Bs2Juotlov0cg57%2Bv8CwRdjMgYYsxPtdtkl5NKniJhbDILKhWCYS4B&noverify=0&group_code=906536632)
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[906536632](http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=_nmC8Neh7mZaGb2hIsO3p4-DKdxBlReQ&authKey=X7rGdx4jbA%2Bs2Juotlov0cg57%2Bv8CwRdjMgYYsxPtdtkl5NKniJhbDILKhWCYS4B&noverify=0&group_code=906536632)