/
Parser.cs
336 lines (296 loc) · 13.3 KB
/
Parser.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using HOI4MI.Manager;
using HOI4MI.Entity;
using HOI4MI.Util;
namespace HOI4MI
{
public static class Parser {
public static string Status { get; private set; }
private static NumberStyles valueFormat = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite;
private static string currentFile;
public static bool ParseProvinceDef(string path) {
string[] lines = File.ReadAllLines(path);
string[] data;
foreach (string l in lines) {
data = l.Split(';');
int id = -1;
int[] rgb = new int[3];
if (!int.TryParse(data[0], out id)) {
Status = $"malformed province ID in line {l}";
return false;
}
if (!int.TryParse(data[1], out rgb[0])) {
Status = $"malformed R for province {id}";
return false;
}
if (!int.TryParse(data[2], out rgb[1])) {
Status = $"malformed G for province {id}";
return false;
}
if (!int.TryParse(data[3], out rgb[2])) {
Status = $"malformed B for province {id}";
return false;
}
if (Province.Create(id, rgb)) {
Province p = Province.Get(id);
p.Type = data[4] switch {
"sea" => ProvinceType.Sea,
"lake" => ProvinceType.Lake,
_ => ProvinceType.Land,
};
p.Coastal = data[5] == "true";
p.Terrain = data[6] switch {
"ocean" => Terrain.Ocean,
"lake" => Terrain.Lake,
"forest" => Terrain.Forest,
"hills" => Terrain.Hills,
"mountain" => Terrain.Mountain,
"plains" => Terrain.Plains,
"urban" => Terrain.Urban,
"jungle" => Terrain.Jungle,
"marsh" => Terrain.Marsh,
"desert" => Terrain.Desert,
"water_fjords" => Terrain.Water_Fjords,
"water_shallow_sea" => Terrain.Water_Shallow_Sea,
"water_deep_ocean" => Terrain.Water_Deep_Ocean,
_ => Terrain.Unknown,
};
if (!int.TryParse(data[7], out int continent)) {
Status = $"malformed continent for province {id}";
return false;
}
p.Continent = (Continent)continent;
p.SetUnmodified();
}
else {
Status = $"Error creating province {id}.\n{Province.Status}";
return false;
}
}
return true;
}
public static bool ParseState(string path) {
string f = File.ReadAllText(path);
currentFile = RemoveWhiteSpace(f);
//check the provinces list is a list of numbers
string provinceString = FindKey("provinces");
if (!Regex.IsMatch(provinceString, @"{((\s+)(\d+))+\s*}")) {
Status = $"Malformed provinces in {path}.";
return false;
}
//get all the numbers in string form
var provStrings = Regex.Matches(provinceString, @"\d+");
HashSet<Province> provs = new HashSet<Province>();
foreach (Match m in provStrings) {
string s = m.Value;
//one of the provinces wasn't a number
if (!int.TryParse(s, out int provId)) {
Status = $"Province {s} isn't an int in {path}.";
return false;
}
Province p = Province.Get(provId);
if (p == null) {
Status = $"Province {provId} doesn't exist";
return false;
}
//check if there are any province-level buildings
string temp = FindKey(s);
if (!string.IsNullOrEmpty(temp)) {
p.LandForts = FindKeyInt("[^_]bunker", temp);
p.CoastalForts = FindKeyInt("coastal_bunker", temp);
p.NavalBase = FindKeyInt("naval_base", temp);
}
provs.Add(p);
p.SetUnmodified();
}
//check if there's any vps specified in the file
//doesnt have to be for provinces from this state
List<string> vpLists = FindMultipleKey("victory_points");
foreach (string s in vpLists) {
Match m = Regex.Match(s, $@"(\d+)\s+(\d+)");
if (m.Success) {
int pid = int.Parse(m.Groups[1].Value);
Province p = Province.Get(pid);
if (p == null) {
Status = $"Victory points specified for invalid province {pid}";
return false;
}
p.VictoryPoints = int.Parse(m.Groups[2].Value);
p.SetUnmodified();
}
}
ResourceSet res = new ResourceSet {
Aluminium = FindKeyDouble("aluminium"),
Steel = FindKeyDouble("steel"),
Tungsten = FindKeyDouble("tungsten"),
Chromium = FindKeyDouble("chromium"),
Oil = FindKeyDouble("oil"),
Rubber = FindKeyDouble("rubber")
};
StateCategory? c = FindKey("category").ConvertStateCategory();
if (c == null) {
//state didn't have a valid category listed
Status = $"Error parsing state category in {path}.";
return false;
}
int stateId = FindKeyInt("id");
string stateName = FindKey("name");
int buildingFactor = FindKeyInt("buildings_max_level_factor");
if (State.Create(stateId)) {
State s = State.Get(stateId);
s.Name = stateName;
s.FileName = path.Split('\\').Last();
s.Manpower = FindKeyInt("manpower");
s.BuildFactor = buildingFactor == 0 ? 1 : buildingFactor;
s.Category = (StateCategory)c;
s.Resources = res;
s.Owner = FindKey("owner");
s.Cores = FindMultipleKey("add_core_of").ToHashSet();
s.Infrastructure = FindKeyInt("infrastructure");
s.CivillianFactories = FindKeyInt("industrial_complex");
s.MilitaryFactories = FindKeyInt("arms_factory");
s.Dockyards = FindKeyInt("dockyard");
s.Refineries = FindKeyInt("synthetic_refinery");
s.Antiair = FindKeyInt("antiair");
s.Silos = FindKeyInt("fuel_silo");
s.Radar = FindKeyInt("radar_station");
s.Rockets = FindKeyInt("rocket_site");
s.Reactors = FindKeyInt("nuclear_reactor");
s.Airbases = FindKeyInt("air_base");
s.Impassable = FindKey("impassable") == "yes";
s.Provinces = provs;
s.SetUnmodified();
}
//something went wrong when creating the state
else {
Status = $"Error creating state {stateId} for {path}.";
return false;
}
return true;
}
public static bool ParseCountry(string path) {
string f = File.ReadAllText(path);
currentFile = RemoveWhiteSpace(f);
string tag = Regex.Match(path.Split(@"\").Last(), @"([A-Z]+) - .+").Groups[1].Value.ToUpper();
//string tag = path.Split(@"\").Last().Substring(1, 3).ToUpper();
if (!Regex.IsMatch(tag, @"[A-Z]+")) {
Status = $"Country tag {tag} is not valid for {path}.";
return false;
}
string pol = FindKey("set_politics");
string pop = FindKey("set_popularities");
Politics p = new Politics();
if (pop != string.Empty) {
p.neutrality = FindKeyInt("neutrality", pop);
p.democracy = FindKeyInt("democratic", pop);
p.fascism = FindKeyInt("fascism", pop);
p.communism = FindKeyInt("communism", pop);
};
if (pol != string.Empty) {
p.rulingParty = (Ideology)Enum.Parse(typeof(Ideology), FindKey("ruling_party", pol), true);
p.lastElection = DateTime.Parse(FindKey("last_election", pol));
p.electionFrequency = FindKeyInt("election_frequency", pol);
p.electionsAllowed = FindKey("election_allowed", pol) == "yes";
}
if (Country.Create(tag)) {
Country c = Country.Get(tag);
c.Name = Localisation.Get($"{tag}_{p.rulingParty.ToString().ToLower()}");
c.Oob = FindKey("oob");
c.ResearchSlots = FindKeyInt("set_research_slots");
c.Convoys = FindKeyInt("set_convoys");
c.Stability = FindKeyDouble("set_stability");
c.WarSupport = FindKeyDouble("set_war_support");
c.Politics = p;
c.FactionName = FindKey("create_faction");
c.FactionMembers = FindMultipleKey("add_to_faction");
c.Capital = FindKeyInt("capital");
c.SetUnmodified();
}
else {
Status = $"Error creating country {tag} for {path}.";
return false;
}
return true;
}
public static string FindKey(string k) {
return FindKey(k, currentFile);
}
public static string FindKey(string k, string s) {
int depth = 0;
string result = string.Empty;
Match m = Regex.Match(s, $"{k}=");
if (m.Success) {
string temp = s.Substring(m.Index + m.Length);
foreach (char c in temp) {
if (c == '{') depth++;
if (c == '}') {
if (depth == 0) break;
depth--;
}
if (c == '\n' && depth == 0) break;
result += c;
}
}
return result.Trim('"');
}
private static List<string> FindMultipleKey(string k) {
return FindMultipleKey(k, currentFile);
}
private static List<string> FindMultipleKey(string k, string s) {
int depth = 0;
List<string> result = new List<string>();
MatchCollection m = Regex.Matches(s, $"{k}=");
foreach (Match n in m) {
string temp2 = string.Empty;
if (n.Success) {
string temp = s.Substring(n.Index + n.Length);
foreach (char c in temp) {
if (c == '{') depth++;
if (c == '}') {
if (depth == 0) break;
depth--;
}
if (c == '\n' && depth == 0) break;
temp2 += c;
}
result.Add(temp2.Trim('"'));
}
}
return result;
}
private static int FindKeyInt(string k) {
return FindKeyInt(k, currentFile);
}
private static int FindKeyInt(string k, string s) {
string value = FindKey(k, s);
if (value == string.Empty) return 0;
if (!int.TryParse(value, valueFormat, CultureInfo.CurrentCulture.NumberFormat, out int result)) throw new ArithmeticException();
return result;
}
private static double FindKeyDouble(string k) {
return FindKeyDouble(k, currentFile);
}
private static double FindKeyDouble(string k, string s) {
string value = FindKey(k, s);
if (value == string.Empty) return 0;
if (!double.TryParse(value, valueFormat, CultureInfo.CurrentCulture.NumberFormat, out double result)) throw new ArithmeticException();
return result;
}
private static string RemoveWhiteSpace(string lines) {
lines = Regex.Replace(lines, @"^(.*)#.*$", "$1", RegexOptions.Multiline); //remove comments
lines = Regex.Replace(lines, @"\r([^\n])", "\r\n", RegexOptions.Multiline);
lines = Regex.Replace(lines, @"^\s*$\n|\r|\t", string.Empty, RegexOptions.Multiline); //remove empty lines
lines = Regex.Replace(lines, @"(.)\s*=\s*(.)", "$1=$2", RegexOptions.Multiline); //remove spaces around =
lines = Regex.Replace(lines, @"^\s*(\S.*?)\s*$", "$1", RegexOptions.Multiline); //remove leading and trailing spaces
return lines;
}
}
}