Repository navigation
Expand file tree
/
Copy pathRepositoryCreator.py
More file actions
652 lines (559 loc) · 24.6 KB
/
Copy pathRepositoryCreator.py
File metadata and controls
652 lines (559 loc) · 24.6 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import logging
import os
from typing import Callable
import pandas as pd
from tqdm import tqdm
from gameObjects.gameObjectRepository import GameObjectRepository
from gameObjects.planet import CORE_ART_MODEL_NAME, Planet
from gameObjects.traderoute import TradeRoute
from gameObjects.campaign import Campaign
from gameObjects.faction import Faction
from gameObjects.startingForce import StartingForce
from xmlTools.xmlreader import XMLReader
from xmlTools.xmlstructure import XMLStructure
logger = logging.getLogger(__name__)
STARTING_FORCES_SHEETS = {
"TR": ("ICW_Eras", 1, 11),
"FotR": ("FOTR_Eras", 0, 6),
"Rev": ("RR_Eras", 0, 6),
}
COMMON_FACTION_NAMES = {
"Neutral": "Neutral",
"Local Forces": "Independent_Forces",
"Hutts": "Hutt_Cartels",
"Hapes": "Hapes_Consortium",
"Chiss": "Chiss",
"Ssi-Ruuk": "SsiRuuvi_Imperium",
"Vong": "Underworld",
"Killiks": "Killik_Hives",
"Mandalorians": "Mandalorians",
"CSA": "Corporate_Sector",
}
FACTION_NAMES_BY_MOD = {
"TR": {
**COMMON_FACTION_NAMES,
"IR": "Empire",
"NR": "Rebel",
"PA": "Pentastar",
"EOTH": "EmpireoftheHand",
"WZ": "Zsinj_Empire",
"EA": "Eriadu_Authority",
"GM": "Greater_Maldrood",
"Warlord": "Warlords",
"Corellian": "Corellia",
"Yevetha": "Yevetha",
},
"FotR": {
**COMMON_FACTION_NAMES,
"REP": "Empire",
"CIS": "Rebel",
"REP_SF": "Sector_Forces",
"CIS_TF": "Trade_Federation",
"CIS_TU": "Techno_Union",
"CIS_BC": "Banking_Clan",
"CIS_CG": "Commerce_Guild",
"CIS_CA": "Corporate_Alliance",
},
"Rev": {
**COMMON_FACTION_NAMES,
"Republic": "Empire",
"Sith": "Rebel",
"Sector Forces": "Sector_Forces",
"Sith Warlords": "Sith_Warlords",
"Mandalorians": "Underworld",
"Hutt Cartels": "Hutt_Cartels",
"Mon Cal Kingdom": "Mon_Cal_Kingdom",
"Rakatan": "Rakata_Empire",
"Eternal Empire": "Eternal_Empire",
"Tion": "Tion_Hegemony",
"Killik": "Killik_Hives",
"Krath": "Krath",
"Alsakani": "Alsakan_Republic",
"Hapan": "Hapes_Consortium",
"Droids": "Droid_Revolt",
"Argazda": "Argazdan_Redoubt",
"Paecia": "Paecian_Empire",
},
}
SKIPPED_SHEET_OWNERS = {"", "Neutral", "Unused", "Locked"}
class RepositoryCreator:
"""Creates a Repository of GameObjects from input XMLs"""
def __init__(self):
self.repository: GameObjectRepository = GameObjectRepository()
self.__folder: str = ""
self.__xml: XMLReader = XMLReader()
self.__progressCallback: Callable[[str, int, int], None] | None = None
def setProgressCallback(self, callback: Callable[[str, int, int], None]) -> None:
"""Set a callback that receives tqdm-style progress updates."""
self.__progressCallback = callback
def __progress(self, iterable, description: str, total: int | None = None):
progressCallback = self.__progressCallback
if progressCallback is None:
return tqdm(iterable, desc=description, total=total)
if total is None:
try:
total = len(iterable)
except TypeError:
total = 0
progressCallback(description, 0, total)
def report_progress():
for current, item in enumerate(iterable, start=1):
yield item
progressCallback(description, current, total)
return report_progress()
def getNamesRootsFromXML(self, rootsList, tag: str) -> list:
"""Takes a list of XML roots and a tag to search for
and returns the Names and Roots of GameObjects in the list"""
names = []
roots = []
for root in rootsList:
names.extend(self.__xml.getNamesFromXML(root))
roots.extend(root.iter(tag))
return names, roots
def addPlanetsFromXML(self, planetRoots, mapVisible: bool = True) -> None:
"""Takes a list of Planet GameObject XML roots and adds
them to the repository with x and y positions"""
shipyard_list = {
"TEXT_PLANET_LIGHT": "Light Frigate",
"TEXT_PLANET_HEAVY": "Heavy Frigate",
"TEXT_PLANET_CAPITAL": "Capital",
"TEXT_PLANET_DREAD": "Dreadnaught",
}
for planetRoot in planetRoots:
for record in self.__progress(
self.__xml.getPlanetInfo(planetRoot), "Loading planets"
):
name = record["name"]
coordinates = record["coordinates"]
if coordinates is None:
logger.warning(
"Planet %s not added to repository, missing coordinates", name
)
continue
newplanet = Planet(name)
newplanet.mapVisible = mapVisible and name != CORE_ART_MODEL_NAME
newplanet.variantOf = record["variant_of"]
newplanet.emptyXmlTags = record["empty_xml_tags"]
newplanet.x, newplanet.y = coordinates
# TODO better way than this hack to convert to int
newplanet.starbaseLevel = int(float(record["starbase_level"]))
newplanet.shipyardLevel = shipyard_list.get(
record["shipyard"], "No Shipyard Defined"
)
structure = record["structure"]
if structure and structure.startswith("TEXT_RESOURCE_SUPPORTS_"):
newplanet.SupportsStructure = structure.replace(
"TEXT_RESOURCE_SUPPORTS_", ""
)
else:
newplanet.SupportsStructure = "None"
newplanet.spaceStructureSlots = int(float(record["space_slots"]))
newplanet.groundStructureSlots = int(float(record["ground_slots"]))
income_value = record["income"]
if income_value:
newplanet.income = int(float(income_value))
self.repository.addPlanet(newplanet)
def addGroundForceTypesFromXML(self, gameObjectRoots) -> None:
"""Adds ground unit names, including variants of ground units, to the repository."""
variants = {}
for root in gameObjectRoots:
variants.update(self.__xml.getGroundForceTypes(root))
unresolved = dict(variants)
while unresolved:
resolved = set()
for name, parent in unresolved.items():
if parent is None or parent in self.repository.groundForceTypes:
self.repository.addGroundForceType(name)
resolved.add(name)
if not resolved:
break
for name in resolved:
unresolved.pop(name)
def addTradeRoutesFromXML(self, tradeRouteRoots) -> None:
"""Takes a list of Trade Route GameObject XML roots and adds
them to the repository with start and end planets"""
for tradeRouteRoot in tradeRouteRoots:
tradeRouteNames = self.__xml.getNamesFromXML(tradeRouteRoot)
for name in self.__progress(tradeRouteNames, "Loading trade routes"):
newroute = TradeRoute(name)
try:
newroute.start, newroute.end = self.__xml.getStartEnd(
name, self.repository.planets, tradeRouteRoot
)
except ValueError as err:
logger.warning("Skipping malformed trade route '%s': %s", name, err)
continue
self.repository.addTradeRoute(newroute)
def addFactionsFromXML(self, factionRoots) -> None:
"""Takes a list of Faction GameObject XML roots and adds
them to the repository"""
for factionRoot in factionRoots:
factionInfo = self.__xml.getFactionInfo(factionRoot)
for name, basic_ai, color, playable in factionInfo:
newFaction = Faction(name)
newFaction.color = color
newFaction.aiplayer = basic_ai
newFaction.playable = playable
self.repository.addFaction(newFaction)
def addCampaignsFromXML(self, campaignEntries) -> None:
"""Takes a list of (filePath, campaignName, campaignRoot) tuples and adds
campaigns to the repository, after finding their planets and trade routes"""
current_campaign_set = ""
# Build lookup dicts once instead of re-scanning/copying the full
# planet/trade route sets for every single name in every campaign.
planetsByLowerName = {p.name.lower(): p for p in self.repository.planets}
tradeRoutesByLowerName = {
t.name.lower(): t for t in self.repository.tradeRoutes
}
for filePath, campaign, campaignRoot in self.__progress(
campaignEntries, "Loading Galactic Conquests"
):
setName = self.__xml.getValueFromXMLRoot(campaignRoot, ".//Campaign_Set")
startingActivePlayer = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Starting_Active_Player"
).strip()
differentLayoutTag = campaignRoot.find(".//Different_Layout_Per_Faction")
differentLayoutPerFaction = (
differentLayoutTag is not None
and self.__xml.stringToBool(differentLayoutTag.text or "")
)
logger.info("Loading campaign %s from set %s", campaign, setName)
if self.__tryAddAlternateSet(campaign, setName, startingActivePlayer, campaignRoot):
continue
if setName != current_campaign_set or differentLayoutPerFaction:
current_campaign_set = setName
newCampaign = Campaign(campaign)
newCampaign.fileName = filePath
newCampaign.loadAlternateSets()
else:
# MP campaigns don't have a starting active player
if startingActivePlayer:
self.repository.getCampaignBySetName(setName).playableFactions.add(
self.repository.getFactionByName(startingActivePlayer)
)
continue
newCampaign.setName = setName
if startingActivePlayer:
newCampaign.playableFactions.add(
self.repository.getFactionByName(startingActivePlayer)
)
newCampaignPlanets = set()
newCampaignTradeRoutes = set()
newCampaignStartingForces = list()
campaignPlanetNames = self.__xml.getListFromXMLRoot(
campaignRoot, ".//Locations"
)
newCampaign.sortOrder = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Sort_Order"
)
newCampaign.textID = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Text_ID"
)
newCampaign.descriptionText = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Description_Text"
)
newCampaign.eraStart = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Era_Start"
)
useDefaultForcesText = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Use_Default_Forces"
)
newCampaign.useDefaultForces = self.__xml.stringToBool(useDefaultForcesText)
newCampaign.rebelStoryName = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Rebel_Story_Name"
)
newCampaign.empireStoryName = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Empire_Story_Name"
)
newCampaign.underworldStoryName = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Underworld_Story_Name"
)
newCampaign.storyName = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Story_Name"
)
newCampaign.isListed = self.__xml.getValueFromXMLRoot(
campaignRoot, ".//Is_Listed"
)
newCampaign.differentLayoutPerFaction = differentLayoutPerFaction
campaignTradeRouteNames = self.__xml.getListFromXMLRoot(
campaignRoot, ".//Trade_Routes"
)
campaignStartingForces = self.__xml.getMultiTag(
campaignRoot, ".//Starting_Forces"
)
for p in campaignPlanetNames:
newPlanet = planetsByLowerName.get(p.lower())
if newPlanet is None:
logger.warning("Object %s not found!", p)
newCampaignPlanets.add(newPlanet)
for t in campaignTradeRouteNames:
newRoute = tradeRoutesByLowerName.get(t.lower())
if newRoute is None:
logger.warning("Object %s not found!", t)
newCampaignTradeRoutes.add(newRoute)
for s in campaignStartingForces:
startingForcesEntry = self.getStartingForces(s)
newCampaignStartingForces.append(startingForcesEntry)
newCampaign.planets = newCampaignPlanets
newCampaign.tradeRoutes = newCampaignTradeRoutes
# TODO sum up identical entries into the Amount column
newCampaign.startingForces = pd.DataFrame(
newCampaignStartingForces,
columns=["Planet", "Era", "Owner", "ObjectType", "Amount"],
)
logger.info(
"Found %d planets and %d trade routes",
len(newCampaignPlanets),
len(newCampaignTradeRoutes),
)
self.repository.addCampaign(newCampaign)
def __tryAddAlternateSet(
self, campaignName: str, setName: str, faction: str, campaignRoot
) -> bool:
"""Fold embedded regime campaigns into their base campaign when possible."""
if not faction:
return False
for baseCampaign in self.repository.campaigns:
prefix = baseCampaign.setName + "_"
if not setName.startswith(prefix):
continue
suffix = setName[len(prefix) :]
if campaignName != baseCampaign.setName + "_" + faction + "_" + suffix:
continue
alternateForces = [
self.getStartingForces(entry)
for entry in self.__xml.getMultiTag(campaignRoot, ".//Starting_Forces")
]
baseOwners = self.__planetOwners(baseCampaign.startingForces.values)
alternateOwners = self.__planetOwners(alternateForces)
dummyName = suffix + "_Dummy"
alternateSets = baseCampaign.alternateSets
if not any(
entry["suffix"] == suffix and entry["faction"] == faction
for entry in alternateSets
):
alternateSets.append(
{
"enabled": True,
"suffix": suffix,
"faction": faction,
"dummy_planet": self.__dummyPlanet(alternateForces, dummyName),
"planet_affiliations": {
planet: owner
for planet, owner in alternateOwners.items()
if baseOwners.get(planet) != owner
},
}
)
baseCampaign.alternateSets = alternateSets
return True
return False
def __planetOwners(self, startingForces) -> dict:
owners = {}
for planet, era, owner, objectType, amount in startingForces:
objectType = str(objectType)
if objectType.endswith("_Dummy") or objectType.endswith("_Capital"):
continue
owners.setdefault(str(planet), str(owner))
return owners
def __dummyPlanet(self, startingForces, dummyName: str) -> str:
for planet, era, owner, objectType, amount in startingForces:
if str(objectType) == dummyName:
return str(planet)
return ""
def runPlanetVariantOfCheck(self) -> None:
for planet in self.__progress(
self.repository.planets, "Checking planet variants"
):
if (planet.x is None) or (planet.y is None):
logger.warning("%s needs parent coordinates", planet.name)
if planet.variantOf != "":
parent = self.getPlanetParentWithCoordinates(planet)
planet.x = parent.x
planet.y = parent.y
logger.info(
"%s now uses %s coordinates!%s, %s",
planet.name,
parent.name,
parent.x,
parent.y,
)
else:
logger.error("%s has no parent!", planet.name)
def getPlanetParentWithCoordinates(self, planet) -> Planet:
p = self.repository.getPlanetByName(planet.variantOf)
if p is not None:
if (p.x is None) & (p.y is None):
if p.variantOf == "":
return None
else:
return self.getPlanetParentWithCoordinates(p)
else:
return p
else:
return None
def getStartingForces(self, entry: str) -> StartingForce:
"""Produces a starting forces object from an XML entry"""
entry = entry.replace(",", " ")
entry = entry.split()
if len(entry) == 3:
factionName = entry[0]
planetName = entry[1]
unitName = entry[2]
return [planetName, 0, factionName, unitName, 1]
else:
logger.warning("Malformed starting forces entry %s", entry)
return ["Empty", 0, "Neutral", "Empty", 1]
def getStartingForcesLibrary(self, dataFolders, startingForcesLibraryURL: str):
if isinstance(dataFolders, (str, os.PathLike)):
dataFolders = [os.fspath(dataFolders)]
modName = next(
(
candidate
for folder in reversed(dataFolders)
if (
candidate := os.path.basename(
os.path.dirname(os.fspath(folder).rstrip("/\\"))
)
) in STARTING_FORCES_SHEETS
),
None,
)
if modName is None:
logger.warning(
"No TR, FotR, or Rev data folder found; continuing without "
"a starting forces library"
)
return None
startingForcesLibraryURL = startingForcesLibraryURL.strip()
if not startingForcesLibraryURL:
logger.warning("Starting forces spreadsheet URL is not configured")
return None
sheetName, firstEra, eraCount = STARTING_FORCES_SHEETS[modName]
spreadsheetURL = startingForcesLibraryURL.split("/edit", 1)[0].rstrip("/")
sheetURL = f"{spreadsheetURL}/gviz/tq?tqx=out:csv&sheet={sheetName}"
logger.info("Loading starting forces from %s", sheetName)
try:
sheet = pd.read_csv(sheetURL, dtype=str, keep_default_na=False)
except (
OSError,
pd.errors.EmptyDataError,
pd.errors.ParserError,
UnicodeDecodeError,
) as err:
logger.error("Failed to load starting forces sheet '%s': %s", sheetName, err)
return None
if sheet.empty or sheet.columns[0] != "Planet" or len(sheet.columns) < eraCount + 1:
logger.error(
"Starting forces sheet '%s' is malformed; expected Planet followed "
"by %d era columns",
sheetName,
eraCount,
)
return None
factionNames = FACTION_NAMES_BY_MOD[modName]
seenPlanets = set()
unknownOwners = set()
records = []
for row in self.__progress(
sheet.itertuples(index=False, name=None),
"Loading starting forces",
total=len(sheet),
):
planet = str(row[0]).strip()
if not planet:
continue
planetKey = planet.casefold()
if planetKey in seenPlanets:
logger.warning(
"Duplicate planet '%s' in %s; keeping the earlier row",
planet,
sheetName,
)
continue
seenPlanets.add(planetKey)
for era, ownerValue in enumerate(
row[1 : eraCount + 1], start=firstEra
):
owner = str(ownerValue).strip()
if owner in SKIPPED_SHEET_OWNERS:
continue
factionName = factionNames.get(owner)
if factionName is None:
unknownOwners.add(owner)
continue
records.append([planet, era, factionName, "Generate_Force", 1])
if unknownOwners:
logger.warning(
"Unknown faction shorthand(s) in %s skipped: %s",
sheetName,
", ".join(sorted(unknownOwners)),
)
startingForcesLibrary = pd.DataFrame(
records, columns=["Planet", "Era", "Owner", "ObjectType", "Amount"]
)
startingForcesLibrary.sort_values(by=["Planet", "Era"], inplace=True)
startingForcesLibrary.reset_index(drop=True, inplace=True)
return startingForcesLibrary
def constructRepository(
self, dataFolders, startingForcesLibraryURL: str
) -> GameObjectRepository:
"""Reads one or more mod Data folders and searches the XML metafiles within.
dataFolders is an ordered list [base, submod1, submod2, ...] where later entries
have higher priority and override earlier ones.
Creates a repository with planets, trade routes and campaigns"""
if isinstance(dataFolders, str):
dataFolders = [dataFolders]
self.__folder = dataFolders[0]
XMLStructure.dataFolder = dataFolders[0]
XMLStructure.dataFolders = dataFolders
# Derive submod names from folders beyond the base: ModPath/SubmodName/Data
XMLStructure.submods = [
os.path.basename(os.path.dirname(f)) for f in dataFolders[1:]
]
gameObjectFile = dataFolders[0] + "/XML/GameObjectFiles.XML"
campaignFile = dataFolders[0] + "/XML/CampaignFiles.XML"
tradeRouteFile = dataFolders[0] + "/XML/TradeRouteFiles.XML"
factionFile = dataFolders[0] + "/XML/FactionFiles.XML"
def metaFileExists(name):
return any(
os.path.exists(os.path.join(f, "XML", name)) for f in dataFolders
)
if metaFileExists("GameObjectFiles.XML"):
print("\nLoading Planets")
gameObjectRoots = self.__xml.findMetaFileRefs(gameObjectFile, dataFolders)
self.addGroundForceTypesFromXML(gameObjectRoots)
planetRoots = self.__xml.findPlanetsFiles(gameObjectFile, dataFolders, excludedFiles={"Planets_Dummy.xml"})
self.addPlanetsFromXML(planetRoots)
dummyPlanetRoots = self.__xml.findPlanetFileByName(
"Planets_Dummy.xml", dataFolders
)
self.addPlanetsFromXML(dummyPlanetRoots, mapVisible=False)
if metaFileExists("TradeRouteFiles.XML"):
logger.info("Loading Trade Routes")
tradeRouteRoots = self.__xml.findMetaFileRefs(tradeRouteFile, dataFolders)
self.addTradeRoutesFromXML(tradeRouteRoots)
if metaFileExists("FactionFiles.XML"):
logger.info("Loading Factions")
factionRoots = self.__xml.findMetaFileRefs(factionFile, dataFolders)
self.addFactionsFromXML(factionRoots)
if metaFileExists("CampaignFiles.XML"):
logger.info("Loading Campigns")
campaignPathRootList = self.__xml.findMetaFileRefsWithPaths(
campaignFile, dataFolders
)
campaignEntries = [
(filePath, name, root)
for filePath, fileRoot in campaignPathRootList
for name, root in zip(
self.__xml.getNamesFromXML(fileRoot), fileRoot.iter("Campaign")
)
]
self.addCampaignsFromXML(campaignEntries)
logger.info("Checking for planet variants")
self.runPlanetVariantOfCheck()
logger.info("Loading starting forces")
self.repository.startingForcesLibrary = self.getStartingForcesLibrary(
dataFolders, startingForcesLibraryURL
)
return self.repository