forked from dvize/Donuts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.cs
344 lines (274 loc) · 12.9 KB
/
Plugin.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using SPT.Reflection.Patching;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Donuts.Models;
using Donuts.Patches;
using EFT;
using EFT.Communications;
using Newtonsoft.Json;
using UnityEngine;
//disable the ide0007 warning for the entire file
#pragma warning disable IDE0007
namespace Donuts
{
[BepInPlugin("com.dvize.Donuts", "dvize.Donuts", "1.5.1")]
[BepInDependency("com.SPT.core", "3.9.0")]
[BepInDependency("xyz.drakia.waypoints")]
[BepInDependency("com.Arys.UnityToolkit")]
public class DonutsPlugin : BaseUnityPlugin
{
internal static PluginGUIHelper pluginGUIHelper;
internal static ConfigEntry<KeyboardShortcut> toggleGUIKey;
internal static KeyCode escapeKey;
internal static new ManualLogSource Logger;
DonutsPlugin()
{
Logger ??= BepInEx.Logging.Logger.CreateLogSource(nameof(DonutsPlugin));
}
private async void Awake()
{
// Run dependency checker
if (!DependencyChecker.ValidateDependencies(Logger, Info, this.GetType(), Config))
{
throw new Exception($"Missing Dependencies");
}
pluginGUIHelper = gameObject.AddComponent<PluginGUIHelper>();
toggleGUIKey = Config.Bind(
"Config Settings",
"Key To Enable/Disable Config Interface",
new KeyboardShortcut(KeyCode.F8),
"Key to Enable/Disable Donuts Configuration Menu");
escapeKey = KeyCode.Escape;
// Patches
new NewGameDonutsPatch().Enable();
new BotGroupAddEnemyPatch().Enable();
new BotMemoryAddEnemyPatch().Enable();
new MatchEndPlayerDisposePatch().Enable();
new PatchStandbyTeleport().Enable();
new BotProfilePreparationHook().Enable();
new AddEnemyPatch().Enable();
new ShootDataNullRefPatch().Enable();
new CoverPointMasterNullRef().Enable();
new DelayedGameStartPatch().Enable();
await SetupScenariosUI();
ImportConfig();
}
private async Task SetupScenariosUI()
{
await LoadDonutsFoldersAsync();
var scenarioValuesList = DefaultPluginVars.pmcScenarioCombinedArray?.ToList() ?? new List<string>();
var scavScenarioValuesList = DefaultPluginVars.scavScenarioCombinedArray?.ToList() ?? new List<string>();
await AddScenarioNamesToListAsync(DefaultPluginVars.pmcScenarios, scenarioValuesList, folder => folder.Name);
await AddScenarioNamesToListAsync(DefaultPluginVars.pmcRandomScenarios, scenarioValuesList, folder => folder.RandomScenarioConfig);
await AddScenarioNamesToListAsync(DefaultPluginVars.scavScenarios, scavScenarioValuesList, folder => folder.Name);
await AddScenarioNamesToListAsync(DefaultPluginVars.randomScavScenarios, scavScenarioValuesList, folder => folder.RandomScenarioConfig);
DefaultPluginVars.pmcScenarioCombinedArray = scenarioValuesList.ToArray();
DefaultPluginVars.scavScenarioCombinedArray = scavScenarioValuesList.ToArray();
// Dynamically initialize the scenario settings
DefaultPluginVars.pmcScenarioSelection = new Setting<string>(
"PMC Raid Spawn Preset Selection",
"Select a preset to use when spawning as PMC",
DefaultPluginVars.pmcScenarioSelection?.Value ?? "live-like",
"live-like",
null,
null,
DefaultPluginVars.pmcScenarioCombinedArray
);
DefaultPluginVars.scavScenarioSelection = new Setting<string>(
"SCAV Raid Spawn Preset Selection",
"Select a preset to use when spawning as SCAV",
DefaultPluginVars.scavScenarioSelection?.Value ?? "live-like",
"live-like",
null,
null,
DefaultPluginVars.scavScenarioCombinedArray
);
#if DEBUG
Logger.LogWarning($"Loaded PMC Scenarios: {string.Join(", ", DefaultPluginVars.pmcScenarioCombinedArray)}");
Logger.LogWarning($"Loaded Scav Scenarios: {string.Join(", ", DefaultPluginVars.scavScenarioCombinedArray)}");
#endif
// Call InitializeDropdownIndices to ensure scenarios are loaded and indices are set
DrawMainSettings.InitializeDropdownIndices();
}
private void Update()
{
if (ImGUIToolkit.IsSettingKeybind())
{
// If setting a keybind, do not trigger functionality
return;
}
if (IsKeyPressed(toggleGUIKey.Value) || IsKeyPressed(escapeKey))
{
if (IsKeyPressed(escapeKey))
{
//check if the config window is open
if (DefaultPluginVars.showGUI)
{
DefaultPluginVars.showGUI = false;
}
}
else
{
DefaultPluginVars.showGUI = !DefaultPluginVars.showGUI;
}
}
if (IsKeyPressed(DefaultPluginVars.CreateSpawnMarkerKey.Value))
{
EditorFunctions.CreateSpawnMarker();
}
if (IsKeyPressed(DefaultPluginVars.WriteToFileKey.Value))
{
EditorFunctions.WriteToJsonFile();
}
if (IsKeyPressed(DefaultPluginVars.DeleteSpawnMarkerKey.Value))
{
EditorFunctions.DeleteSpawnMarker();
}
}
public static void ImportConfig()
{
// Get the path of the currently executing assembly
var dllPath = Assembly.GetExecutingAssembly().Location;
var configDirectory = Path.Combine(Path.GetDirectoryName(dllPath), "Config");
var configFilePath = Path.Combine(configDirectory, "DefaultPluginVars.json");
if (!File.Exists(configFilePath))
{
Logger.LogError($"Config file not found: {configFilePath}, creating a new one");
PluginGUIHelper.ExportConfig();
return;
}
string json = File.ReadAllText(configFilePath);
DefaultPluginVars.ImportFromJson(json);
}
#region Donuts Non-Raid Related Methods
private async Task LoadDonutsFoldersAsync()
{
var dllPath = Assembly.GetExecutingAssembly().Location;
var directoryPath = Path.GetDirectoryName(dllPath);
DefaultPluginVars.pmcScenarios = await LoadFoldersAsync(Path.Combine(directoryPath, "ScenarioConfig.json"));
DefaultPluginVars.pmcRandomScenarios = await LoadFoldersAsync(Path.Combine(directoryPath, "RandomScenarioConfig.json"));
DefaultPluginVars.scavScenarios = await LoadFoldersAsync(Path.Combine(directoryPath, "ScavScenarioConfig.json"));
DefaultPluginVars.randomScavScenarios = await LoadFoldersAsync(Path.Combine(directoryPath, "RandomScavScenarioConfig.json"));
await PopulateScenarioValuesAsync();
DrawMainSettings.InitializeDropdownIndices(); // Re-initialize dropdown indices after loading scenarios
}
private async Task PopulateScenarioValuesAsync()
{
DefaultPluginVars.pmcScenarioCombinedArray = await GenerateScenarioValuesAsync(DefaultPluginVars.pmcScenarios, DefaultPluginVars.pmcRandomScenarios);
DefaultPluginVars.scavScenarioCombinedArray = await GenerateScenarioValuesAsync(DefaultPluginVars.scavScenarios, DefaultPluginVars.randomScavScenarios);
}
private async Task<string[]> GenerateScenarioValuesAsync(List<Folder> scenarios, List<Folder> randomScenarios)
{
var valuesList = new List<string>();
await AddScenarioNamesToListAsync(scenarios, valuesList, folder => folder.Name);
await AddScenarioNamesToListAsync(randomScenarios, valuesList, folder => folder.RandomScenarioConfig);
return valuesList.ToArray();
}
private async Task AddScenarioNamesToListAsync(IEnumerable<Folder> folders, List<string> valuesList, Func<Folder, string> getNameFunc)
{
if (folders != null)
{
foreach (var folder in folders)
{
var name = getNameFunc(folder);
Logger.LogWarning($"Adding scenario: {name}");
valuesList.Add(name);
}
}
}
private static async Task<List<Folder>> LoadFoldersAsync(string filePath)
{
if (!File.Exists(filePath))
{
Logger.LogWarning($"File not found: {filePath}");
return new List<Folder>();
}
var fileContent = await Task.Run(() => File.ReadAllText(filePath));
var folders = JsonConvert.DeserializeObject<List<Folder>>(fileContent);
if (folders == null || folders.Count == 0)
{
Logger.LogError("No Donuts Folders found in Scenario Config file, disabling plugin");
Debug.Break();
return new List<Folder>();
}
Logger.LogWarning($"Loaded {folders.Count} Donuts Scenario Folders");
return folders;
}
#endregion
#region Donuts Raid Related Scenario Selection Methods
internal static Folder GrabDonutsFolder(string folderName)
{
return DefaultPluginVars.pmcScenarios.FirstOrDefault(folder => folder.Name == folderName);
}
internal static string RunWeightedScenarioSelection()
{
try
{
var scenarioSelection = DefaultPluginVars.pmcScenarioSelection.Value;
if (SPT.SinglePlayer.Utils.InRaid.RaidChangesUtil.IsScavRaid)
{
Logger.LogWarning("This is a SCAV raid, using SCAV raid preset selector");
scenarioSelection = DefaultPluginVars.scavScenarioSelection.Value;
}
var selectedFolder = DefaultPluginVars.pmcScenarios.FirstOrDefault(folder => folder.Name == scenarioSelection)
?? DefaultPluginVars.pmcRandomScenarios.FirstOrDefault(folder => folder.RandomScenarioConfig == scenarioSelection);
if (selectedFolder != null)
{
return SelectPreset(selectedFolder);
}
return null;
}
catch (Exception e)
{
Logger.LogError("Error in RunWeightedScenarioSelection: " + e);
return null;
}
}
private static string SelectPreset(Folder folder)
{
if (folder.presets == null || folder.presets.Count == 0) return folder.Name;
var totalWeight = folder.presets.Sum(preset => preset.Weight);
var randomWeight = UnityEngine.Random.Range(0, totalWeight);
var selectedPreset = folder.presets
.Aggregate((currentPreset, nextPreset) =>
randomWeight < (currentPreset.Weight += nextPreset.Weight) ? currentPreset : nextPreset);
LogSelectedPreset(selectedPreset.Name);
return selectedPreset.Name;
}
private static void LogSelectedPreset(string selectedPreset)
{
Console.WriteLine($"Donuts: Random Selected Preset: {selectedPreset}");
if (DefaultPluginVars.ShowRandomFolderChoice.Value && DonutComponent.methodCache.TryGetValue("DisplayMessageNotification", out var displayMessageNotificationMethod))
{
var txt = $"Donuts Random Selected Preset: {selectedPreset}";
EFT.UI.ConsoleScreen.Log(txt);
displayMessageNotificationMethod.Invoke(null, new object[] { txt, ENotificationDurationType.Long, ENotificationIconType.Default, Color.yellow });
}
}
#endregion
internal static bool IsKeyPressed(KeyboardShortcut key)
{
if (!UnityInput.Current.GetKeyDown(key.MainKey)) return false;
return key.Modifiers.All(modifier => UnityInput.Current.GetKey(modifier));
}
internal static bool IsKeyPressed(KeyCode key)
{
if (!UnityInput.Current.GetKeyDown(key)) return false;
return true;
}
}
//re-initializes each new game
internal class NewGameDonutsPatch : ModulePatch
{
protected override MethodBase GetTargetMethod() => typeof(GameWorld).GetMethod(nameof(GameWorld.OnGameStarted));
[PatchPrefix]
public static void PatchPrefix() => DonutComponent.Enable();
}
}