-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedStatic.V1Ext_Update1.cs
More file actions
435 lines (389 loc) · 20.3 KB
/
SharedStatic.V1Ext_Update1.cs
File metadata and controls
435 lines (389 loc) · 20.3 KB
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
using Hi3Helper.Plugin.Core.Management;
using Hi3Helper.Plugin.Core.Management.PresetConfig;
using Hi3Helper.Plugin.Core.Utility;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using static Hi3Helper.Plugin.Core.Utility.GameManagerExtension;
#if !MANUALCOM
using System.Runtime.InteropServices.Marshalling;
#endif
namespace Hi3Helper.Plugin.Core;
public partial class SharedStaticV1Ext
{
// Update1
internal delegate HResult LaunchGameFromGameManagerAsyncDelegate(
nint gameManagerP,
nint pluginP,
nint presetConfigP,
nint printGameLogCallbackP,
nint arguments,
int argumentsLen,
int runBoostedInt,
int processPriorityInt,
ref Guid cancelToken,
out nint taskResult);
internal delegate HResult WaitRunningGameAsyncDelegate(
nint gameManagerP,
nint pluginP,
nint presetConfigP,
ref Guid cancelToken,
out nint taskResult);
internal delegate HResult IsGameRunningDelegate(
nint gameManagerP,
nint presetConfigP,
out int isGameRunning,
out DateTime processStartTime);
}
public partial class SharedStaticV1Ext<T>
{
private static void InitExtension_Update1Exports()
{
/* ----------------------------------------------------------------------
* Update 1 Feature Sets
* ----------------------------------------------------------------------
* This feature sets includes the following feature:
* - Game Launch
* - LaunchGameFromGameManagerAsync
* - WaitRunningGameAsync
* - Game Process Management
* - IsGameRunning
* - KillRunningGame
*/
// -> Plugin Async Game Launch Callback for Specific Game Region based on its IGameManager instance.
TryRegisterApiExport<LaunchGameFromGameManagerAsyncDelegate>("LaunchGameFromGameManagerAsync", LaunchGameFromGameManagerAsync);
// -> Plugin Game Run Check for Specific Game Region based on its IGameManager instance.
TryRegisterApiExport<IsGameRunningDelegate>("IsGameRunning", IsGameRunning);
// -> Plugin Async Game Run Awaiter for Specific Game Region based on its IGameManager instance.
TryRegisterApiExport<WaitRunningGameAsyncDelegate>("WaitRunningGameAsync", WaitRunningGameAsync);
// -> Plugin Game Process Killer for Specific Game Region based on its IGameManager instance.
TryRegisterApiExport<IsGameRunningDelegate>("KillRunningGame", KillRunningGame);
}
#region ABI Proxies
/// <summary>
/// This method is an ABI proxy function between the PInvoke Export and the actual plugin's method.<br/>
/// See the documentation for <see cref="SharedStaticV1Ext{T}.LaunchGameFromGameManagerCoreAsync(RunGameFromGameManagerContext, string?, bool, ProcessPriorityClass, CancellationToken)"/> method for more information.
/// </summary>
private static unsafe HResult LaunchGameFromGameManagerAsync(nint gameManagerP,
nint pluginP,
nint presetConfigP,
nint printGameLogCallbackP,
nint arguments,
int argumentsLen,
int runBoostedInt,
int processPriorityInt,
ref Guid cancelToken,
out nint taskResult)
{
taskResult = nint.Zero;
try
{
InstanceLogger.LogTrace("[LaunchGameFromGameManagerAsync] pluginP: {A:x8} | gameManagerP: {B:x8} | presetConfigP: {C:x8} | printGameLogCallbackP: {D:x8}", pluginP, gameManagerP, presetConfigP, printGameLogCallbackP);
#if MANUALCOM
IPlugin? plugin = ComWrappers.ComInterfaceDispatch.GetInstance<IPlugin>((ComWrappers.ComInterfaceDispatch*)pluginP);
IGameManager? gameManager = ComWrappers.ComInterfaceDispatch.GetInstance<IGameManager>((ComWrappers.ComInterfaceDispatch*)gameManagerP);
IPluginPresetConfig? presetConfig = ComWrappers.ComInterfaceDispatch.GetInstance<IPluginPresetConfig>((ComWrappers.ComInterfaceDispatch*)presetConfigP);
#else
IPlugin? plugin = ComInterfaceMarshaller<IPlugin>.ConvertToManaged((void*)pluginP);
IGameManager? gameManager = ComInterfaceMarshaller<IGameManager>.ConvertToManaged((void*)gameManagerP);
IPluginPresetConfig? presetConfig = ComInterfaceMarshaller<IPluginPresetConfig>.ConvertToManaged((void*)presetConfigP);
#endif
PrintGameLog? printGameLogCallback = printGameLogCallbackP == nint.Zero
? null
: Marshal.GetDelegateForFunctionPointer<PrintGameLog>(printGameLogCallbackP);
if (ThisExtensionExport == null)
{
throw new NullReferenceException("The ThisPluginExport field is null!");
}
if (gameManager == null)
{
throw new NullReferenceException("Cannot cast IGameManager from the pointer, hence it gives null!");
}
if (plugin == null)
{
throw new NullReferenceException("Cannot cast IPlugin from the pointer, hence it gives null!");
}
if (presetConfig == null)
{
throw new NullReferenceException("Cannot cast IPluginPresetConfig from the pointer, hence it gives null!");
}
CancellationTokenSource? cts = null;
if (Unsafe.IsNullRef(ref cancelToken))
{
cts = ComCancellationTokenVault.RegisterToken(in cancelToken);
}
RunGameFromGameManagerContext context = new()
{
GameManager = gameManager,
PresetConfig = presetConfig,
Plugin = plugin,
PrintGameLogCallback = printGameLogCallback,
PluginHandle = nint.Zero
};
bool isRunBoosted = runBoostedInt == 1;
ProcessPriorityClass processPriorityClass = (ProcessPriorityClass)processPriorityInt;
string? startArguments = null;
if (argumentsLen > 0)
{
char* argumentsP = (char*)arguments;
ReadOnlySpan<char> argumentsSpan = Mem.CreateSpanFromNullTerminated<char>(argumentsP);
if (argumentsSpan.Length > argumentsLen)
{
argumentsSpan = argumentsSpan[..argumentsLen];
}
startArguments = argumentsSpan.IsEmpty ? null : argumentsSpan.ToString();
}
(bool isSupported, Task<bool> task) = ThisExtensionExport
.LaunchGameFromGameManagerCoreAsync(context,
startArguments,
isRunBoosted,
processPriorityClass,
cts?.Token ?? CancellationToken.None);
taskResult = task.AsResult();
return isSupported;
}
catch (Exception ex)
{
// ignored
InstanceLogger.LogError(ex, "An error has occurred while trying to call LaunchGameFromGameManagerCoreAsync() from the plugin!");
return Marshal.GetHRForException(ex);
}
}
/// <summary>
/// This method is an ABI proxy function between the PInvoke Export and the actual plugin's method.<br/>
/// See the documentation for <see cref="SharedStaticV1Ext{T}.IsGameRunningCore(RunGameFromGameManagerContext, out bool, out DateTime)"/> method for more information.
/// </summary>
private static unsafe HResult IsGameRunning(nint gameManagerP, nint presetConfigP, out int isGameRunningInt, out DateTime gameStartTime)
{
isGameRunningInt = 0;
gameStartTime = default;
try
{
#if MANUALCOM
IGameManager? gameManager = ComWrappers.ComInterfaceDispatch.GetInstance<IGameManager>((ComWrappers.ComInterfaceDispatch*)gameManagerP);
IPluginPresetConfig? presetConfig = ComWrappers.ComInterfaceDispatch.GetInstance<IPluginPresetConfig>((ComWrappers.ComInterfaceDispatch*)presetConfigP);
#else
IGameManager? gameManager = ComInterfaceMarshaller<IGameManager>.ConvertToManaged((void*)gameManagerP);
IPluginPresetConfig? presetConfig = ComInterfaceMarshaller<IPluginPresetConfig>.ConvertToManaged((void*)presetConfigP);
#endif
if (gameManager == null)
{
throw new NullReferenceException("Cannot cast IGameManager from the pointer, hence it gives null!");
}
if (presetConfig == null)
{
throw new NullReferenceException("Cannot cast IPluginPresetConfig from the pointer, hence it gives null!");
}
RunGameFromGameManagerContext context = new()
{
GameManager = gameManager,
PresetConfig = presetConfig,
Plugin = null!,
PrintGameLogCallback = null!,
PluginHandle = nint.Zero
};
bool isSupported = ThisExtensionExport.IsGameRunningCore(context, out bool isGameRunning, out gameStartTime);
isGameRunningInt = isGameRunning ? 1 : 0;
return isSupported;
}
catch (Exception ex)
{
// ignored
InstanceLogger.LogError(ex, "An error has occurred while trying to call IsGameRunningCore() from the plugin!");
return Marshal.GetHRForException(ex);
}
}
/// <summary>
/// This method is an ABI proxy function between the PInvoke Export and the actual plugin's method.<br/>
/// See the documentation for <see cref="SharedStaticV1Ext{T}.WaitRunningGameCoreAsync(RunGameFromGameManagerContext, CancellationToken)"/> method for more information.
/// </summary>
private static unsafe HResult WaitRunningGameAsync(nint gameManagerP, nint pluginP, nint presetConfigP, ref Guid cancelToken, out nint taskResult)
{
taskResult = nint.Zero;
try
{
#if MANUALCOM
IPlugin? plugin = ComWrappers.ComInterfaceDispatch.GetInstance<IPlugin>((ComWrappers.ComInterfaceDispatch*)pluginP);
IGameManager? gameManager = ComWrappers.ComInterfaceDispatch.GetInstance<IGameManager>((ComWrappers.ComInterfaceDispatch*)gameManagerP);
IPluginPresetConfig? presetConfig = ComWrappers.ComInterfaceDispatch.GetInstance<IPluginPresetConfig>((ComWrappers.ComInterfaceDispatch*)presetConfigP);
#else
IPlugin? plugin = ComInterfaceMarshaller<IPlugin>.ConvertToManaged((void*)pluginP);
IGameManager? gameManager = ComInterfaceMarshaller<IGameManager>.ConvertToManaged((void*)gameManagerP);
IPluginPresetConfig? presetConfig = ComInterfaceMarshaller<IPluginPresetConfig>.ConvertToManaged((void*)presetConfigP);
#endif
if (ThisExtensionExport == null)
{
throw new NullReferenceException("The ThisPluginExport field is null!");
}
if (gameManager == null)
{
throw new NullReferenceException("Cannot cast IGameManager from the pointer, hence it gives null!");
}
if (plugin == null)
{
throw new NullReferenceException("Cannot cast IPlugin from the pointer, hence it gives null!");
}
if (presetConfig == null)
{
throw new NullReferenceException("Cannot cast IPluginPresetConfig from the pointer, hence it gives null!");
}
CancellationTokenSource? cts = null;
if (Unsafe.IsNullRef(ref cancelToken))
{
cts = ComCancellationTokenVault.RegisterToken(in cancelToken);
}
RunGameFromGameManagerContext context = new()
{
GameManager = gameManager,
PresetConfig = presetConfig,
Plugin = plugin,
PrintGameLogCallback = null!,
PluginHandle = nint.Zero
};
(bool isSupported, Task<bool> task) = ThisExtensionExport.WaitRunningGameCoreAsync(context, cts?.Token ?? CancellationToken.None);
taskResult = task.AsResult();
return isSupported;
}
catch (Exception ex)
{
// ignored
InstanceLogger.LogError(ex, "An error has occurred while trying to call WaitRunningGameCoreAsync() from the plugin!");
return Marshal.GetHRForException(ex);
}
}
/// <summary>
/// This method is an ABI proxy function between the PInvoke Export and the actual plugin's method.<br/>
/// See the documentation for <see cref="SharedStaticV1Ext{T}.KillRunningGameCore(RunGameFromGameManagerContext, out bool, out DateTime)"/> method for more information.
/// </summary>
private static unsafe HResult KillRunningGame(nint gameManagerP, nint presetConfigP, out int wasGameRunningInt, out DateTime gameStartTime)
{
wasGameRunningInt = 0;
gameStartTime = default;
try
{
#if MANUALCOM
IGameManager? gameManager = ComWrappers.ComInterfaceDispatch.GetInstance<IGameManager>((ComWrappers.ComInterfaceDispatch*)gameManagerP);
IPluginPresetConfig? presetConfig = ComWrappers.ComInterfaceDispatch.GetInstance<IPluginPresetConfig>((ComWrappers.ComInterfaceDispatch*)presetConfigP);
#else
IGameManager? gameManager = ComInterfaceMarshaller<IGameManager>.ConvertToManaged((void*)gameManagerP);
IPluginPresetConfig? presetConfig = ComInterfaceMarshaller<IPluginPresetConfig>.ConvertToManaged((void*)presetConfigP);
#endif
if (gameManager == null)
{
throw new NullReferenceException("Cannot cast IGameManager from the pointer, hence it gives null!");
}
if (presetConfig == null)
{
throw new NullReferenceException("Cannot cast IPluginPresetConfig from the pointer, hence it gives null!");
}
RunGameFromGameManagerContext context = new()
{
GameManager = gameManager,
PresetConfig = presetConfig,
Plugin = null!,
PrintGameLogCallback = null!,
PluginHandle = nint.Zero
};
bool isSupported = ThisExtensionExport.KillRunningGameCore(context, out bool wasGameRunning, out gameStartTime);
wasGameRunningInt = wasGameRunning ? 1 : 0;
return isSupported;
}
catch (Exception ex)
{
// ignored
InstanceLogger.LogError(ex, "An error has occurred while trying to call KillRunningGameCore() from the plugin!");
return Marshal.GetHRForException(ex);
}
}
#endregion
#region Core Methods
/// <summary>
/// Asynchronously launch the game using plugin's built-in game launch mechanism and wait until the game exit.
/// </summary>
/// <param name="context">The context to launch the game from <see cref="IGameManager"/>.</param>
/// <param name="startArgument">The additional argument to run the game executable.</param>
/// <param name="isRunBoosted">Based on <see cref="Process.PriorityBoostEnabled"/>, boost the process temporarily when the game window is focused (Default: false).</param>
/// <param name="processPriority">Based on <see cref="Process.PriorityClass"/>, run the game process with specific priority (Default: <see cref="ProcessPriorityClass.Normal"/>).</param>
/// <param name="token">
/// Cancellation token to pass into the plugin's game launch mechanism.<br/>
/// If cancellation is requested, it will cancel the awaiting but not killing the game process.
/// </param>
/// <returns>
/// Returns <c>IsSupported.false</c> if the plugin doesn't have game launch mechanism (or API Standard is equal or lower than v0.1.1) or if this method isn't overriden.<br/>
/// Otherwise, <c>IsSupported.true</c> if the plugin supports game launch mechanism.
/// </returns>
protected virtual (bool IsSupported, Task<bool> Task) LaunchGameFromGameManagerCoreAsync(
RunGameFromGameManagerContext context,
string? startArgument,
bool isRunBoosted,
ProcessPriorityClass processPriority,
CancellationToken token)
{
return (false, Task.FromResult(false));
}
/// <summary>
/// Check if the game from the current <see cref="IGameManager"/> is running or not.
/// </summary>
/// <param name="context">The context to launch the game from <see cref="IGameManager"/>.</param>
/// <param name="isGameRunning">Whether the game is currently running or not.</param>
/// <param name="gameStartTime">The date time stamp of when the process was started.</param>
/// <returns>
/// To find the actual return value, please use <paramref name="isGameRunning"/> out-argument.<br/><br/>
///
/// Returns <c>false</c> if the plugin doesn't have game launch mechanism (or API Standard is equal or lower than v0.1.1) or if this method isn't overriden.<br/>
/// Otherwise, <c>true</c> if the plugin supports game launch mechanism.
/// </returns>
protected virtual bool IsGameRunningCore(
RunGameFromGameManagerContext context,
out bool isGameRunning,
out DateTime gameStartTime)
{
isGameRunning = false;
gameStartTime = default;
return false;
}
/// <summary>
/// Asynchronously wait currently running game until it exit.
/// </summary>
/// <param name="context">The context to launch the game from <see cref="IGameManager"/>.</param>
/// <param name="token">
/// Cancellation token to pass into the plugin's game launch mechanism.<br/>
/// If cancellation is requested, it will cancel the awaiting but not killing the game process.
/// </param>
/// <returns>
/// Returns <c>IsSupported.false</c> if the plugin doesn't have game launch mechanism (or API Standard is equal or lower than v0.1.1) or if this method isn't overriden.<br/>
/// Otherwise, <c>IsSupported.true</c> if the plugin does support game launch mechanism and the game ran successfully.
/// </returns>
protected virtual (bool IsSupported, Task<bool> Task) WaitRunningGameCoreAsync(
RunGameFromGameManagerContext context,
CancellationToken token)
{
return (false, Task.FromResult(false));
}
/// <summary>
/// Kill the process of the currently running game.
/// </summary>
/// <param name="context">The context to launch the game from <see cref="IGameManager"/>.</param>
/// <param name="wasGameRunning">Whether to indicate that the game was running or not.</param>
/// <param name="gameStartTime">The date time stamp of when the process was started.</param>
/// <returns>
/// To find the actual return value, please use <paramref name="wasGameRunning"/> out-argument.<br/><br/>
///
/// Returns <c>false</c> if the plugin doesn't have game launch mechanism (or API Standard is equal or lower than v0.1.1) or if this method isn't overriden.<br/>
/// Otherwise, <c>true</c> if the plugin supports game launch mechanism.
/// </returns>
protected virtual bool KillRunningGameCore(
RunGameFromGameManagerContext context,
out bool wasGameRunning,
out DateTime gameStartTime)
{
wasGameRunning = false;
gameStartTime = default;
return false;
}
#endregion
}