Repository navigation
Expand file tree
/
Copy pathMod.cs
More file actions
238 lines (212 loc) · 12.2 KB
/
Copy pathMod.cs
File metadata and controls
238 lines (212 loc) · 12.2 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
using Colossal.IO.AssetDatabase;
using Colossal.Logging;
using Colossal.UI;
using Game;
using Game.Modding;
using Game.SceneFlow;
using Game.Simulation;
using Game.UI.InGame;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Unity.Entities;
namespace ChangeCompany
{
/// <summary>
/// The main entry point for this mod.
/// </summary>
public class Mod : IMod
{
// Harmony ID.
public const string HarmonyID = "rcav8tr." + ModAssemblyInfo.Name;
// Create a new log just for this mod.
// This mod will have its own log file in the game's Logs folder.
public static readonly ILog log = LogManager.GetLogger(ModAssemblyInfo.Name)
.SetShowsErrorsInUI(true) // Show message in UI for severity level Error and above.
.SetShowsStackTraceAboveLevels(Level.Error); // Include stack trace for severity level Error and above.
// The global settings for this mod.
public static ModSettings ModSettings { get; private set; }
/// <summary>
/// One-time mod loading.
/// </summary>
public void OnLoad(UpdateSystem updateSystem)
{
log.Info($"{nameof(Mod)}.{nameof(OnLoad)} Version {ModAssemblyInfo.Version}");
try
{
// Register and load mod settings.
ModSettings = new ModSettings(this);
ModSettings.RegisterInOptionsUI();
ModSettings.RegisterKeyBindings();
AssetDatabase.global.LoadSettings(ModAssemblyInfo.Name, ModSettings, new ModSettings(this));
ModSettings.Loaded();
// Initialize translations.
Translation.Initialize();
// Initialize production and surplus.
ProductionSurplus.Initialize();
// Add mod UI images directory to UI resource handler.
// When the URI is used to access an image, the game forces the URI portion to lower case.
// So make the URI lower case here to be compatible.
if (!GameManager.instance.modManager.TryGetExecutableAsset(this, out ExecutableAsset modExecutableAsset))
{
log.Error("Unable to get mod executable asset.");
return;
}
string assemblyPath = Path.GetDirectoryName(modExecutableAsset.path);
string imagesPath = Path.Combine(assemblyPath, "Images");
UIManager.defaultUISystem.AddHostLocation(ModAssemblyInfo.Name.ToLower(), imagesPath);
// Create this mod's sections for the game's building info display in the UI.
// These are not systems that update directly in a system update phase.
// Instead, updates are handled by SelectedInfoUISystem which runs in UIUpdate phase.
// The sections just need to be created.
World defaultWorld = World.DefaultGameObjectInjectionWorld;
ChangeCompanySection changeCompanySection = defaultWorld.GetOrCreateSystemManaged<ChangeCompanySection>();
LockCompanySection lockCompanySection = defaultWorld.GetOrCreateSystemManaged<LockCompanySection>();
CompanyWorkplacesSection companyWorkplacesSection = defaultWorld.GetOrCreateSystemManaged<CompanyWorkplacesSection>();
// Use reflection to get the list of middle sections from SelectedInfoUISystem.
FieldInfo fieldInfoMiddleSections = typeof(SelectedInfoUISystem).GetField("m_MiddleSections", BindingFlags.Instance | BindingFlags.NonPublic);
if (fieldInfoMiddleSections == null)
{
log.Error($"{nameof(Mod)}.{nameof(OnLoad)} Unable to find middle sections in SelectedInfoUISystem.");
return;
}
SelectedInfoUISystem selectedInfoUISystem = defaultWorld.GetOrCreateSystemManaged<SelectedInfoUISystem>();
List<ISectionSource> middleSections = (List<ISectionSource>)fieldInfoMiddleSections.GetValue(selectedInfoUISystem);
if (middleSections == null)
{
log.Error($"{nameof(Mod)}.{nameof(OnLoad)} Unable to get middle sections from SelectedInfoUISystem.");
return;
}
// Get the index of the game's CompanySection.
int companySectionIndex = -1;
for (int i = 0; i < middleSections.Count; i++)
{
if (middleSections[i] is CompanySection)
{
companySectionIndex = i;
break;
}
}
// Check if game's CompanySection was found.
if (companySectionIndex == -1)
{
// Log an error and add this mod's ChangeCompanySection and LockCompanySection to the end.
log.Error($"[{ModAssemblyInfo.Title}] Unable to find CompanySection in middle sections from SelectedInfoUISystem.");
middleSections.Add(changeCompanySection);
middleSections.Add(lockCompanySection);
}
else
{
// Insert ChangeCompanySection and LockCompanySection right after the game's CompanySection.
// This is the order they will be displayed by the game.
middleSections.Insert(companySectionIndex + 1, changeCompanySection);
middleSections.Insert(companySectionIndex + 2, lockCompanySection);
}
// Get the index of the game's EmployeesSection.
int employeesSectionIndex = -1;
for (int i = 0; i < middleSections.Count; i++)
{
if (middleSections[i] is EmployeesSection)
{
employeesSectionIndex = i;
break;
}
}
// Check if game's EmployeesSection was found.
if (employeesSectionIndex == -1)
{
// Log an error and add this mod's CompanyWorkplacesSection to the end.
log.Error($"[{ModAssemblyInfo.Title}] Unable to find EmployeesSection in middle sections from SelectedInfoUISystem.");
middleSections.Add(companyWorkplacesSection);
}
else
{
// Insert CompanyWorkplacesSection right after the game EmployeesSection.
// This is the order they will be displayed by the game.
middleSections.Insert(employeesSectionIndex + 1, companyWorkplacesSection);
}
// Create and activate this mod's ChangeCompanySystem which contains the logic to change or remove the company on a property.
// In the game, this logic is normally executed in the GameSimulation phase.
// Of course, the GameSimulation phase runs only when the simulation is running.
// It is highly desired to allow the player to change companies while the game is paused.
// Therefore, ChangeCompanySystem updates in the PostSimulation phase, which runs even when the game is paused.
updateSystem.UpdateAt<ChangeCompanySystem>(SystemUpdatePhase.PostSimulation);
// Create and activate this mod's production balance systems.
// Run after the TimeSystem which updates the game date/time.
updateSystem.UpdateAfter<ProductionBalanceSystem, TimeSystem>(SystemUpdatePhase.GameSimulation);
updateSystem.UpdateAt<ProductionBalanceUISystem>(SystemUpdatePhase.UIUpdate);
// Create this mod's company workplaces systems.
// These systems do not run in a system update phase and do nothing in their OnUpdate.
// Instead, they use a Harmony postfix to run after another system OnUpdate runs.
// Therefore, these systems just need to be created.
defaultWorld.GetOrCreateSystemManaged<CommercialWorkplacesSystem>();
defaultWorld.GetOrCreateSystemManaged<ExtractorWorkplacesSystem >();
defaultWorld.GetOrCreateSystemManaged<IndustrialWorkplacesSystem>();
defaultWorld.GetOrCreateSystemManaged<RWHCompanyWorkplacesSystem>();
// Create and activate this mod's system to remove the workplaces override for companies with no PropertyRenter.
// Do in PreSimulation so the overrides are removed before any
// game systems in Simulation phase can assign the company to a property.
updateSystem.UpdateAt<RemoveWorkplacesOverrideSystem>(SystemUpdatePhase.PreSimulation);
// Create and activate this mod's systems to override company storage and vehicles.
// Run these at the end of the phase so that they overwrite any changes made by other mods in the same phase.
updateSystem.UpdateAfter<OverrideStorageSystem >(SystemUpdatePhase.PrefabUpdate);
updateSystem.UpdateAfter<OverrideVehiclesSystem>(SystemUpdatePhase.PrefabUpdate);
#if DEBUG
// Get localized text from the game where the value is or contains specific text.
//Colossal.Localization.LocalizationManager localizationManager = GameManager.instance.localizationManager;
//foreach (KeyValuePair<string, string> keyValue in localizationManager.activeDictionary.entries)
//{
// // Exclude assets.
// if (!keyValue.Key.StartsWith("Assets."))
// {
// //if (keyValue.Value.ToLower().Contains("no data"))
// if (keyValue.Value.ToLower() == "vehicles")
// //if (keyValue.Key.ToLower().Contains("value_ton"))
// {
// log.Info(keyValue.Key + "\t" + keyValue.Value);
// }
// }
//}
// For a specific localization key, get the localized text for each base game locale ID.
//string[] localeIDs = new string[] { "en-US", "de-DE", "es-ES", "fr-FR", "it-IT", "ja-JP", "ko-KR", "pl-PL", "pt-BR", "ru-RU", "zh-HANS", "zh-HANT" };
//foreach (string localeID in localeIDs)
//{
// localizationManager.SetActiveLocale(localeID);
// foreach (KeyValuePair<string, string> keyValue in localizationManager.activeDictionary.entries)
// {
// if (keyValue.Key == "Common.VALUE_TON")
// {
// log.Info(keyValue.Key + "\t" + localeID + "\t" + keyValue.Value);
// //break;
// }
// }
//}
//localizationManager.SetActiveLocale("en-US");
#endif
}
catch (Exception ex)
{
log.Error(ex);
}
log.Info($"{nameof(Mod)}.{nameof(OnLoad)} complete.");
}
/// <summary>
/// One-time mod disposing.
/// </summary>
public void OnDispose()
{
log.Info($"{nameof(Mod)}.{nameof(OnDispose)}");
// Stop listening for language change events to prevent null reference exception when accessing ModSettings.
// This can happen if this mod is disposed first and then another mod's OnDispose causes a language change.
// This mod could still be listening for the event, but ModSettings would be null when accessed.
World.DefaultGameObjectInjectionWorld.GetExistingSystemManaged<ProductionBalanceUISystem>()?.StopLanguageChangeListener();
// Unregister mod settings.
ModSettings?.UnregisterInOptionsUI();
ModSettings = null;
// Remove all Harmony patches for this mod.
new Harmony(HarmonyID).UnpatchAll();
}
}
}