aboutsummaryrefslogtreecommitdiff
path: root/libs/basic_games/games/game_blackandwhite2.py
blob: 5d9f60b3da7fbaba7fda8b44c8678385b349ca48 (plain)
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
import datetime
import os
import struct
import time
from collections.abc import Mapping
from pathlib import Path
from typing import BinaryIO

from PyQt6.QtCore import QDateTime, QDir, QFile, QFileInfo

import mobase

from ..basic_features import BasicLocalSavegames
from ..basic_features.basic_save_game_info import (
    BasicGameSaveGame,
    BasicGameSaveGameInfo,
    format_date,
)
from ..basic_game import BasicGame


class BlackAndWhite2ModDataChecker(mobase.ModDataChecker):
    _validFolderTree = {
        "<black & white 2>": ["audio", "data", "plugins", "scripts"],
        "audio": ["dialogue", "music", "sfx"],
        "music": [
            "buildingmusic",
            "chant",
            "cutscene",
            "dynamic music",
            "epicspell",
            "townalignment",
        ],
        "sfx": ["atmos", "creature", "game", "script", "spells", "video", "grass"],
        "data": [
            "art",
            "balance",
            "ctr",
            "effects",
            "encryptedshaders",
            "font",
            "handdemo",
            "interface",
            "landscape",
            "light particle effects",
            "lipsync",
            "physics",
            "sfx",
            "shaders",
            "symbols",
            "text",
            "textures",
            "tutorial avi",
            "visualeffects",
            "weathersystem",
            "zones",
        ],
        "art": [
            "binary_anim_libs",
            "binary_animations",
            "features",
            "models",
            "skins",
            "textures",
            "water",
        ],
        "ctr": [
            "badvisor_evil",
            "badvisor_good",
            "bape",
            "bgorilla",
            "bhand",
            "blion",
            "btiger",
            "bwolf",
            "damage",
            "siren",
        ],
        "font": ["asian"],
        "asian": ["korean", "traditional chinese"],
        "landscape": [
            "aztec",
            "bw2",
            "egyptian",
            "generic",
            "greek",
            "japanese",
            "norse",
            "skysettings",
        ],
        "tutorial avi": ["placeholder", "stills"],
        "visualeffects": ["textures"],
        "scripts": ["bw2"],
    }
    _validFileLocation = {
        "<black & white 2>": ["exe", "dll", "ico", "png", "jpeg", "jpg"]
    }
    _mapFile = ["chl", "bmp", "bwe", "ter", "pat", "xml", "wal", "txt"]
    _fileIgnore = ["readme", "read me", "meta.ini", "thumbs.db", "backup", ".png"]

    def fix(self, filetree: mobase.IFileTree):
        toMove: list[tuple[mobase.FileTreeEntry, str]] = []
        for entry in filetree:
            if any([sub in entry.name().casefold() for sub in self._fileIgnore]):
                continue
            elif entry.suffix() == "chl":
                toMove.append((entry, "/Scripts/BW2/"))
            elif entry.suffix() == "bmp":
                toMove.append((entry, "/Data/"))
            elif entry.suffix() == "txt":
                toMove.append((entry, "/Scripts/"))
            else:
                toMove.append((entry, "/Data/landscape/BW2/"))

        for entry, path in toMove:
            filetree.move(entry, path, policy=mobase.IFileTree.MERGE)

        return filetree

    def dataLooksValid(
        self, filetree: mobase.IFileTree
    ) -> mobase.ModDataChecker.CheckReturn:
        # qInfo("Data validation start")
        root = filetree
        unpackagedMap = False

        for entry in filetree:
            entryName = entry.name().casefold()
            canIgnore = any([sub in entryName for sub in self._fileIgnore])
            if not canIgnore:
                parent = entry.parent()
                if parent is not None:
                    if parent != root:
                        parentName = parent.name().casefold()
                    else:
                        # qInfo(str(entryName))
                        parentName = "<black & white 2>"

                    if not entry.isDir():
                        if parentName in self._validFileLocation.keys():
                            if (
                                entry.suffix()
                                not in self._validFileLocation[parentName]
                            ):
                                if (
                                    entry.suffix() in self._mapFile
                                    or entryName == "map.txt"
                                ):
                                    unpackagedMap = True
                                else:
                                    return mobase.ModDataChecker.INVALID
                    else:
                        unpackagedMap = False
                        if parentName in self._validFolderTree.keys():
                            if entryName not in self._validFolderTree[parentName]:
                                return mobase.ModDataChecker.INVALID

        # qInfo(str(unpackagedMap))
        if unpackagedMap:
            return mobase.ModDataChecker.FIXABLE
        else:
            return mobase.ModDataChecker.VALID


class BlackAndWhite2SaveGame(BasicGameSaveGame):
    _saveInfLayout = {
        "start": [0x00000000, 0x00000004],
        "name": [0x00000004, 0x0000002C],
        "empty": [0x0000002C, 0x00000104],
        "land": [0x00000104, 0x00000108],
        "date": [0x00000108, 0x00000110],
        "empty1": [0x00000110, 0x00000114],
        "elapsed": [0x00000114, 0x00000118],
        "empty2": [0x00000108, 0x0000011C],
    }

    def __init__(self, filepath: Path):
        super().__init__(filepath)
        self._filepath = Path(filepath)
        self.name: str = ""
        self.land: int = -1
        self.elapsed: int = 0
        self.lastsave: int = 0
        with open(self._filepath.joinpath("SaveGame.inf"), "rb") as info:
            # Name embedded in "SaveGame.inf" with UTF-16 encoding
            self.name = self.readInf(info, "name").decode("utf-16")
            # Land number embedded in "SaveGame.inf" as an int written in binary
            self.land = int.from_bytes(self.readInf(info, "land"), "little")
            # Getting elapsed time in second
            self.elapsed = int.from_bytes(self.readInf(info, "elapsed"), "little")
            # Getting date in 100th of nanosecond need to convert NT time
            # to UNIX time and offset localtime
            self.lastsave = int(
                (
                    struct.unpack("q", self.readInf(info, "date"))[0] / 10000
                    - 11644473600000
                )
                - (time.localtime().tm_gmtoff * 1000)
            )
            info.close()

    def readInf(self, inf: BinaryIO, key: str):
        inf.seek(self._saveInfLayout[key][0])
        return inf.read(self._saveInfLayout[key][1] - self._saveInfLayout[key][0])

    def allFiles(self) -> list[str]:
        files = [str(file) for file in self._filepath.glob("./*")]
        files.append(str(self._filepath))
        return files

    def getCreationTime(self) -> QDateTime:
        return QDateTime.fromMSecsSinceEpoch(self.lastsave)

    def getElapsed(self) -> str:
        return str(datetime.timedelta(seconds=self.elapsed))

    def getName(self) -> str:
        return self.name

    def getLand(self) -> str:
        return str(self.land)

    def getSaveGroupIdentifier(self):
        return self._filepath.parent.parent.name


def getMetadata(savepath: Path, save: mobase.ISaveGame) -> Mapping[str, str]:
    assert isinstance(save, BlackAndWhite2SaveGame)
    return {
        "Name": save.getName(),
        "Profile": save.getSaveGroupIdentifier(),
        "Land": save.getLand(),
        "Saved at": format_date(save.getCreationTime()),
        "Elapsed time": save.getElapsed(),
    }


PSTART_MENU = (
    str(os.getenv("ProgramData")) + "\\Microsoft\\Windows\\Start Menu\\Programs"
)


class BlackAndWhite2Game(BasicGame):
    Name = "Black & White 2 Support Plugin"
    Author = "Ilyu"
    Version = "1.0.1"

    GameName = "Black & White 2"
    GameShortName = "BW2"
    GameNexusName = "blackandwhite2"
    GameDataPath = "%GAME_PATH%"
    GameBinary = "white.exe"
    GameDocumentsDirectory = "%DOCUMENTS%/Black & White 2"
    GameSavesDirectory = "%GAME_DOCUMENTS%/Profiles"
    GameSupportURL = (
        r"https://github.com/ModOrganizer2/modorganizer-basic_games/wiki/"
        "Game:-Black-&-White-2"
    )

    _program_link = PSTART_MENU + "\\Black & White 2\\Black & White® 2.lnk"

    def init(self, organizer: mobase.IOrganizer) -> bool:
        BasicGame.init(self, organizer)

        self._register_feature(BlackAndWhite2ModDataChecker())
        self._register_feature(BasicLocalSavegames(self))
        self._register_feature(
            BasicGameSaveGameInfo(get_metadata=getMetadata, max_width=400)
        )
        return True

    def detectGame(self):
        super().detectGame()

        program_path = Path(self._program_link)
        if program_path.exists():
            installation_path = Path(QFileInfo(self._program_link).symLinkTarget())
            if installation_path.exists():
                self.setGamePath(installation_path.parent)

        return

    def executables(self) -> list[mobase.ExecutableInfo]:
        execs = super().executables()

        """
        A bat file to load modded executables from VFS.
        """
        workaroundPath = self._gamePath + "/" + self.GameBinary[:-4] + ".bat"

        try:
            workaround = open(workaroundPath, "rt")
        except FileNotFoundError:
            with open(workaroundPath, "wt") as workaround:
                workaround.write('start "" "' + self.GameBinary + '"')
        workaround.close()

        execs.append(
            mobase.ExecutableInfo(
                self.GameShortName + " Modded Exec", QFileInfo(workaroundPath)
            )
        )

        return execs

    def listSaves(self, folder: QDir) -> list[mobase.ISaveGame]:
        profiles: list[Path] = []
        for path in Path(folder.absolutePath()).glob("*/Saved Games/*"):
            if (
                path.name == "Autosave"
                or path.name == "Pictures"
                or "_invalid" in path.name
            ):
                continue
            if path.is_dir():
                saveFolder = QDir(str(path))
                if not saveFolder.exists("SaveGame.inf"):
                    savePath = saveFolder.absolutePath()
                    QFile.rename(savePath, savePath + "_invalid")
                    continue
            else:
                continue

            profiles.append(path)

        return [BlackAndWhite2SaveGame(path) for path in profiles]


class BOTGGame(BlackAndWhite2Game):
    Name = "Black & White 2 Battle of the Gods Support Plugin"

    GameName = "Black & White 2 Battle of the Gods"
    GameShortName = "BOTG"
    GameBinary = "BattleOfTheGods.exe"
    GameDocumentsDirectory = "%DOCUMENTS%/Black & White 2 - Battle of the Gods"
    GameSavesDirectory = "%GAME_DOCUMENTS%/Profiles"

    _program_link = (
        PSTART_MENU + "\\Black & White 2 Battle of the Gods"
        "\\Black & White® 2 Battle of the Gods.lnk"
    )