forked from Odjit/KindredExtract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore.cs
More file actions
294 lines (239 loc) · 10.1 KB
/
Core.cs
File metadata and controls
294 lines (239 loc) · 10.1 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
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP.Utils.Collections;
using Engine.Console;
using Il2CppInterop.Runtime.Injection;
using KindredExtract.Services;
using ProjectM;
using ProjectM.Network;
using ProjectM.Physics;
using ProjectM.Scripting;
using ProjectM.UI;
using Stunlock.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Entities;
using UnityEngine;
using VampireCommandFramework;
using VampireCommandFramework.Breadstone;
using Object = UnityEngine.Object;
namespace KindredExtract;
internal static class Core
{
public static World TheWorld { get; } = GetWorld("Server") ?? (GetWorld("Client_0") ?? throw new System.Exception("There is no Server world (yet). Did you install a server mod on the client?"));
public static bool IsServer => TheWorld.Name == "Server";
public static EntityManager EntityManager { get; } = TheWorld.EntityManager;
public static ServerScriptMapper ServerScriptMapper { get; internal set; }
public static double ServerTime => ServerGameManager.ServerTime;
public static ServerGameManager ServerGameManager => ServerScriptMapper.GetServerGameManager();
public static ConsoleCommandSystem ConsoleCommandSystem => TheWorld.GetExistingSystemManaged<ConsoleCommandSystem>();
public static RefinementstationMenuMapper RefinementstationMenuMapper => TheWorld.GetExistingSystemManaged<RefinementstationMenuMapper>();
public static LocalizationService Localization { get; } = new();
public static ManualLogSource Log { get; } = Plugin.LogInstance;
public static PlayerService Players { get; internal set; }
public static PrefabService Prefabs { get; internal set; }
public static EcsSystemHierarchyService EcsSystemHierarchyService { get; } = new(Log);
public static EcsSystemDumpService EcsSystemDumpService { get; } = new(EcsSystemHierarchyService, Log);
static MonoBehaviour monoBehaviour;
public static void LogException(System.Exception e, [CallerMemberName] string caller = null)
{
Core.Log.LogError($"Failure in {caller}\nMessage: {e.Message} Inner:{e.InnerException?.Message}\n\nStack: {e.StackTrace}\nInner Stack: {e.InnerException?.StackTrace}");
}
internal static void InitializeAfterLoaded()
{
if (_hasInitialized) return;
ServerScriptMapper = TheWorld.GetExistingSystemManaged<ServerScriptMapper>();
Players = new();
Prefabs = new();
ComponentInitializer.InitializeComponents();
_hasInitialized = true;
Log.LogInfo($"{nameof(InitializeAfterLoaded)} completed");
}
private static bool _hasInitialized = false;
public static (PrefabGUID, int)[] CountPrefabs(int maxNum=10, string filter=null)
{
Dictionary<PrefabGUID, int> prefabCount = new();
foreach (var entity in EntityManager.GetAllEntities())
{
if (!EntityManager.HasComponent<PrefabGUID>(entity)) continue;
var prefab = EntityManager.GetComponentData<PrefabGUID>(entity);
if (filter != null && !prefab.LookupName().Contains(filter)) continue;
if (!prefabCount.ContainsKey(prefab)) prefabCount.Add(prefab, 0);
prefabCount[prefab]++;
}
return prefabCount.OrderByDescending(x => x.Value)
.Take(maxNum)
.Select(x => (x.Key, x.Value)).ToArray();
}
public static void SavePrefabCountToCSV()
{
Dictionary<string, int> nonPrefabCount = new();
Dictionary<PrefabGUID, int> prefabCount = new();
var total = 0;
var totalNonPrefab = 0;
foreach (var entity in EntityManager.GetAllEntities())
{
if (!EntityManager.HasComponent<PrefabGUID>(entity))
{
var componentString = entity.GetComponentString();
if (!nonPrefabCount.ContainsKey(componentString)) nonPrefabCount.Add(componentString, 0);
nonPrefabCount[componentString]++;
totalNonPrefab++;
if (componentString == "Simulate")
Core.EntityManager.DestroyEntity(entity);
continue;
}
var prefab = EntityManager.GetComponentData<PrefabGUID>(entity);
if (!prefabCount.ContainsKey(prefab)) prefabCount.Add(prefab, 0);
prefabCount[prefab]++;
total++;
}
Log.LogInfo($"Total Prefab Count: {total}");
Log.LogInfo($"Total Non Prefab Count: {totalNonPrefab}");
var sortedPrefabCount = prefabCount.ToList();
sortedPrefabCount.Sort((x, y) => x.Key.LookupName().CompareTo(y.Key.LookupName()));
using (var writer = new StreamWriter("prefab_count.csv"))
{
writer.WriteLine("PrefabGUID,Count");
foreach (var kvp in sortedPrefabCount)
{
writer.WriteLine($"{kvp.Key.LookupName()},{kvp.Value}");
}
}
var sortedNonPrefabCount = nonPrefabCount.ToList();
sortedNonPrefabCount.Sort((x, y) => x.Key.CompareTo(y.Key));
using (var writer = new StreamWriter("non_prefab_count.csv"))
{
writer.WriteLine("Components,Count");
foreach (var kvp in sortedNonPrefabCount)
{
writer.WriteLine($"{kvp.Key},{kvp.Value}");
}
}
}
class TestCommand : Il2CppSystem.Object
{
public TestCommand(IntPtr ptr) : base(ptr) { }
public TestCommand() { }
public void Test()
{
Core.Log.LogInfo("Test command executed!");
}
}
class ConsoleTest : ConsoleCommand
{
public ConsoleTest(string command) : base(command, 0)
{
Core.Log.LogInfo("Created!");
}
public override void ExecuteCommand(string command, string fullCommand)
{
Core.Log.LogInfo("ConsoleTest command executed!");
}
}
public static void RegisterCommandsForConsole()
{
Core.Log.LogInfo("Registering commands!!!");
var ccs = Core.TheWorld.GetExistingSystemManaged<ConsoleCommandSystem>();
var commandType = typeof(ConsoleTest);
if (!ClassInjector.IsTypeRegisteredInIl2Cpp(commandType))
{
ClassInjector.RegisterTypeInIl2Cpp(commandType);
}
ccs.AddCommand(new ConsoleTest("test"));
return;
var types = Assembly.GetAssembly(typeof(Core)).GetTypes();
foreach(var t in types)
{
foreach(var method in t.GetMethods())
{
var commandAttr = method.GetCustomAttribute<CommandAttribute>();
if (commandAttr != null)
{
Core.Log.LogInfo($"Registering command {commandAttr.Name}");
void ExecuteCommand()
{
try
{
var ctx = new ChatCommandContext(GetVChatEvent(commandAttr.Name));
// Prepare parameters
var parameters = method.GetParameters();
var args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType == typeof(ChatCommandContext))
{
args[i] = ctx;
}
else if (parameters[i].HasDefaultValue)
{
args[i] = parameters[i].DefaultValue;
}
else
{
throw new InvalidOperationException($"Cannot provide a value for parameter '{parameters[i].Name}' of method '{method.Name}'");
}
}
method.Invoke(null, args);
}
catch (System.Exception e)
{
Core.LogException(e);
}
}
var methodPtr = Marshal.GetFunctionPointerForDelegate(ExecuteCommand);
ccs.RegisterCommand(commandAttr.Name, commandAttr.Description, new (methodPtr));
}
}
}
}
static VChatEvent GetVChatEvent(string message)
{
var userEntity = Helper.GetEntitiesByComponentType<User>()[0];
var characterEntity = Helper.GetEntitiesByComponentType<PlayerCharacter>()[0];
var constructor = typeof(VChatEvent).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[] { typeof(Entity), typeof(Entity), typeof(string), typeof(ChatMessageType), typeof(User) },
null);
var type = ChatMessageType.Local; // Replace with actual chat message type
var user = userEntity.Read<User>(); // Adjust according to your actual method to get User
// Create an instance of VChatEvent using the constructor
var vChatEventInstance = constructor.Invoke(new object[] { userEntity, characterEntity, message, type, user });
return vChatEventInstance as VChatEvent;
}
private static World GetWorld(string name)
{
foreach (var world in World.s_AllWorlds)
{
if (world.Name == name)
{
return world;
}
}
return null;
}
public static Coroutine StartCoroutine(IEnumerator routine)
{
if (monoBehaviour == null)
{
var go = new GameObject("KindredExtract");
monoBehaviour = go.AddComponent<IgnorePhysicsDebugSystem>();
Object.DontDestroyOnLoad(go);
}
return monoBehaviour.StartCoroutine(routine.WrapToIl2Cpp());
}
public static void StopCoroutine(Coroutine coroutine)
{
if (monoBehaviour == null)
{
return;
}
monoBehaviour.StopCoroutine(coroutine);
}
}