-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEUtils.cs
278 lines (261 loc) · 13.7 KB
/
EUtils.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
using ColossalFramework.PlatformServices;
using EManagersLib.Extra;
using EManagersLib.Patches;
using EManagersLib.Patches.ElectrifiedRoad;
using EManagersLib.Patches.OutsideConnection;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using UnityEngine;
namespace EManagersLib {
/// <summary>
/// This class provides public API to ensure that mods using this library functions correctly
/// </summary>
public static class EUtils {
private const string m_debugLogFile = "oEManagerDebug.log";
public delegate U RefGetter<U>();
/// <summary>Make sure to cache the return value of this property before using it in a loop</summary>
/// <returns>Returns the maximum prop limit set by Prop Anarchy. If Prop Anarchy is not installed, then returns default prop limit</returns>
public static int GetPropMaxLimit => EPropManager.MAX_PROP_LIMIT;
/// <summary>This library will call the queued action callback late in the initialization to ensure prop buffer points to the correct location</summary>
internal static void ProcessQueues() { }
/// <summary>
/// Helper API to create delegates to get private or protected field members that would usually be accessed
/// using slow reflection codes
/// </summary>
/// <typeparam name="S">Type of class where the field resides</typeparam>
/// <typeparam name="T">Name of the private or protected field</typeparam>
/// <param name="field"></param>
/// <returns>Returns the delegate for fast getter to private or protected fields</returns>
public static Func<S, T> CreateGetter<S, T>(FieldInfo field) {
string methodName = field.ReflectedType.FullName + ".get_" + field.Name;
DynamicMethod setterMethod = new DynamicMethod(methodName, typeof(T), new Type[1] { typeof(S) }, true);
ILGenerator gen = setterMethod.GetILGenerator();
if (field.IsStatic) {
gen.Emit(OpCodes.Ldsfld, field);
} else {
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldfld, field);
}
gen.Emit(OpCodes.Ret);
return (Func<S, T>)setterMethod.CreateDelegate(typeof(Func<S, T>));
}
public static RefGetter<U> CreatePrefabRefGetter<U>(string s_field) {
var prefab = typeof(PrefabCollection<PropInfo>);
var fi = prefab.GetField(s_field, BindingFlags.NonPublic | BindingFlags.Static);
if (fi == null) throw new MissingFieldException(prefab.Name, s_field);
var s_name = "__refget_" + prefab.Name + "_fi_" + fi.Name;
var dm = new DynamicMethod(s_name, typeof(U), new[] { prefab }, prefab, true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldsfld, fi);
il.Emit(OpCodes.Ret);
return (RefGetter<U>)dm.CreateDelegate(typeof(RefGetter<U>));
}
/// <summary>
/// Helper API to create delegates to set private or protected field members that would usually be accessed
/// using slow reflection codes
/// </summary>
/// <typeparam name="S"></typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <returns>Returns the delegate for fast setter of private or protected fields</returns>
public static Action<S, T> CreateSetter<S, T>(FieldInfo field) {
string methodName = field.ReflectedType.FullName + ".set_" + field.Name;
DynamicMethod setterMethod = new DynamicMethod(methodName, null, new Type[2] { typeof(S), typeof(T) }, true);
ILGenerator gen = setterMethod.GetILGenerator();
if (field.IsStatic) {
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Stsfld, field);
} else {
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Stfld, field);
}
gen.Emit(OpCodes.Ret);
return (Action<S, T>)setterMethod.CreateDelegate(typeof(Action<S, T>));
}
internal static IEnumerable<CodeInstruction> DebugPatchOutput(IEnumerable<CodeInstruction> instructions, MethodBase method) {
ELog("---- " + method.Name + " ----");
foreach (var code in instructions) {
ELog(code.ToString());
yield return code;
}
ELog("------------------------------------------");
}
private static readonly Stopwatch profiler = new Stopwatch();
private static readonly object fileLock = new object();
internal static void CreateDebugFile() {
profiler.Start();
/* Create Debug Log File */
string path = Path.Combine(Application.dataPath, m_debugLogFile);
using (FileStream debugFile = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
using (StreamWriter sw = new StreamWriter(debugFile)) {
sw.WriteLine($"--- {EModule.m_modName} {EModule.m_modVersion} Debug File ---");
sw.WriteLine(Environment.OSVersion);
sw.WriteLine($"C# CLR Version {Environment.Version}");
sw.WriteLine($"Unity Version {Application.unityVersion}");
sw.WriteLine("-------------------------------------");
}
}
internal static void ELog(string msg) {
var ticks = profiler.ElapsedTicks;
Monitor.Enter(fileLock);
try {
using (FileStream debugFile = new FileStream(Path.Combine(Application.dataPath, m_debugLogFile), FileMode.Append))
using (StreamWriter sw = new StreamWriter(debugFile)) {
sw.WriteLine($"{(ticks / Stopwatch.Frequency):n0}:{(ticks % Stopwatch.Frequency):D7}-{new StackFrame(1, true).GetMethod().Name} ==> {msg}");
}
} finally {
Monitor.Exit(fileLock);
}
}
public readonly struct ModInfo {
public readonly ulong fileID;
public readonly string name;
public readonly string specialMsg;
public readonly bool inclusive;
public ModInfo(ulong modID, string modName, bool isInclusive) {
fileID = modID;
name = modName;
specialMsg = null;
inclusive = isInclusive;
}
public ModInfo(ulong modID, string modName, bool isInclusive, string extraMsg) {
fileID = modID;
name = modName;
specialMsg = extraMsg;
inclusive = isInclusive;
}
}
private static readonly ModInfo[] IncompatibleMods = new ModInfo[] {
new ModInfo(593588108, @"Prop & Tree Anarchy", false, @"Prop Anarchy and Tree Anarchy together replaces Prop & Tree Anarchy"),
new ModInfo(791221322, @"Prop Precision", false, @"Use Prop Anarchy instead"),
new ModInfo(787611845, @"Prop Snapping", false, @"Use Prop Anarchy instead"),
new ModInfo(767233815, @"Decal Prop Fix", false, @"Use Prop Anarchy instead"),
new ModInfo(694512541, @"Prop Line Tool", false, @"Use Prop Anarchy instead"),
new ModInfo(911295408, @"Prop Scaler", false, @"Use Prop Anarchy instead"),
new ModInfo(1869561285, @"Prop Painter", false, @"Use Prop Anarchy instead"),
new ModInfo(2685506044, @"Prop Painter: Revisited", false, @"Use Prop Anarchy instead"),
new ModInfo(922939393, @"Transparency LOD Fix", false, @"Use Prop Anarchy instead"),
new ModInfo(1410003347, @"Additive Shader by Ronyx69", false, @"Use Prop Anarchy instead"),
new ModInfo(2119477759, @"[TEST]Additive Shader by aubergine18", false, @"Use Prop Anarchy instead"),
new ModInfo(878991312, @"Prop It Up", false, @"Use BOB instead"),
new ModInfo(2153618633, @"Prop Switcher", false, @"Use BOB instead"),
new ModInfo(518456166, @"Prop Remover", false, @"Use BOB instead"),
new ModInfo(2140866327, @"Asset Color Expander 2", false),
new ModInfo(531738447, @"CSL Show More Limits", true)
};
internal static bool CheckIncompatibleMods() {
string errorMsg = "";
foreach (var mod in PlatformService.workshop.GetSubscribedItems()) {
for (int i = 0; i < IncompatibleMods.Length; i++) {
if (mod.AsUInt64 == IncompatibleMods[i].fileID) {
errorMsg += '[' + IncompatibleMods[i].name + ']' + @" detected. " +
(IncompatibleMods[i].inclusive ? "EML already includes the same functionality. " : "This mod is incompatible with EML. ") +
(IncompatibleMods[i].specialMsg is null ? "\n" : IncompatibleMods[i].specialMsg + "\n\n");
ELog(@"Incompatible mod: [" + IncompatibleMods[i].name + @"] detected");
}
}
}
if (errorMsg.Length > 0) {
EDialog.MessageBox("EML detected incompatible mods", errorMsg);
ELog("EML detected incompatible mods, please remove the following mentioned mods\n" + errorMsg);
return false;
}
return true;
}
internal static void EnablePatches() {
Harmony harmony = new Harmony(EModule.HARMONYID);
new EPropManagerPatch().Enable(harmony);
new EDefaultToolPatch().Enable(harmony);
new EBuildingDecorationPatch().Enable(harmony);
new EBulldozePatch().Enable(harmony);
new EDistrictManagerPatch().Enable(harmony);
new EDisasterHelpersPatch().Enable(harmony);
new EInstanceManagerPatch().Enable(harmony);
new EPropToolPatch().Enable(harmony);
new EBuildingAIPatch().Enable(harmony);
new ETreeToolPatch().Enable(harmony);
new EBuildingToolPatch().Enable(harmony);
#if ENABLEEIGHTYONE
new EAreaWrapperPatch().Enable(harmony);
new EGameAreaManagerPatch().Enable(harmony);
new EGameAreaToolPatch().Enable(harmony);
new EGameAreaInfoPanel().Enable(harmony);
new ENaturalResourceManagerPatch().Enable(harmony);
new ENetManagerPatch().Enable(harmony);
new ETerrainManagerPatch().Enable(harmony);
new EZoneManagerPatch().Enable(harmony);
new EZoneBlockPatch().Enable(harmony);
new EZoneToolPatch().Enable(harmony);
new EBuildingPatch().Enable(harmony);
new EDistrictToolPatch().Enable(harmony);
new EElectricityManagerPatch().Enable(harmony);
new EImmaterialResourceManagerPatch().Enable(harmony);
new EWaterManagerPatch().Enable(harmony);
#endif
new ENetworkAIPatches().Enable(harmony);
}
internal static void LateEnablePatches() {
Harmony harmony = new Harmony(EModule.HARMONYID);
if (ESettings.m_electrifiedRoad) {
new ERoadBaseAIPatch().Enable(harmony);
}
}
internal static void DisablePatches() {
Harmony harmony = new Harmony(EModule.HARMONYID);
new EPropManagerPatch().Disable(harmony);
new EBulldozePatch().Disable(harmony);
new EDefaultToolPatch().Disable(harmony);
new EBuildingDecorationPatch().Disable(harmony);
new EDistrictManagerPatch().Disable(harmony);
new EDisasterHelpersPatch().Disable(harmony);
new EInstanceManagerPatch().Disable(harmony);
new EPropToolPatch().Disable(harmony);
new EBuildingAIPatch().Disable(harmony);
new ETreeToolPatch().Disable(harmony);
new EBuildingToolPatch().Disable(harmony);
#if ENABLEEIGHTYONE
new EAreaWrapperPatch().Disable(harmony);
new EGameAreaManagerPatch().Disable(harmony);
new EGameAreaToolPatch().Disable(harmony);
new EGameAreaInfoPanel().Disable(harmony);
new ENaturalResourceManagerPatch().Disable(harmony);
new ENetManagerPatch().Disable(harmony);
new ETerrainManagerPatch().Disable(harmony);
new EZoneManagerPatch().Disable(harmony);
new EZoneBlockPatch().Disable(harmony);
new EZoneToolPatch().Disable(harmony);
new EBuildingPatch().Disable(harmony);
new EDistrictToolPatch().Disable(harmony);
new EElectricityManagerPatch().Disable(harmony);
new EImmaterialResourceManagerPatch().Disable(harmony);
new EWaterManagerPatch().Disable(harmony);
#else
new E81TilesCompatPatch().Disable(harmony);
#endif
new ENetworkAIPatches().Disable(harmony);
}
internal static void LateDisablePatches() {
Harmony harmony = new Harmony(EModule.HARMONYID);
if (ESettings.m_electrifiedRoad) {
new ERoadBaseAIPatch().Disable(harmony);
}
}
/// <summary>
/// Enables Harmony patches for other mods. Do NOT call before OnCreated() - especially DO NOT USE DoOnHarmonyReady.
/// Mod load and instantiation order is undefined at OnEnabled, and CitiesHarmony DoOnHarmonyReady may - and often does - trigger this BEFORE target mod is lodaed.
/// </summary>
internal static void EnableModPatches() {
#if !ENABLEEIGHTYONE
Harmony harmony = new Harmony(EModule.HARMONYID);
new E81TilesCompatPatch().Enable(harmony);
#endif
}
}
}