-
Notifications
You must be signed in to change notification settings - Fork 1
/
dow_layout.py
304 lines (250 loc) · 10.2 KB
/
dow_layout.py
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
import abc
import configparser
import contextlib
import dataclasses
import enum
import pathlib
import typing
from .sga import SgaArchive, SgaPath
@enum.unique
class TextureLevel(str, enum.Enum):
HIGH = 'Full'
@enum.unique
class SoundLevel(str, enum.Enum):
HIGH = 'Full'
MEDIUM = 'Med'
LOW = 'Low'
@enum.unique
class ModelLevel(str, enum.Enum):
HIGH = 'High'
MEDIUM = 'Medium'
LOW = 'Low'
T = typing.TypeVar('T')
class AbstractSource(abc.ABC):
@abc.abstractmethod
def make_path(self, path: str | pathlib.PurePath) -> 'LayoutPath':
raise NotImplementedError
@abc.abstractmethod
def exists(self) -> bool:
raise NotImplementedError
@dataclasses.dataclass
class DirectoryPath:
full_path: pathlib.Path
root: pathlib.PurePosixPath
def __getattr__(self, key):
return getattr(self.full_path, key)
def __truediv__(self, other) -> 'DirectoryPath':
return DirectoryPath(self.full_path / other, self.root)
def __rtruediv__(self, other) -> 'DirectoryPath':
return DirectoryPath(other / self.full_path, self.root)
def iterdir(self) -> 'typing.Generator[DirectoryPath, None, None]':
for c in self.full_path.iterdir():
yield DirectoryPath(c, self.root)
def __str__(self) -> str:
return str(self.layout_path())
@property
def data_size(self):
return self.full_path.stat().st_size
def layout_path(self) -> pathlib.PurePosixPath:
return self.full_path.relative_to(self.root)
def __getstate__(self):
return vars(self)
def __setstate__(self, state):
vars(self).update(state)
LayoutPath = SgaPath | DirectoryPath
class DirectorySource(AbstractSource):
def __init__(self, root: str | pathlib.Path, name: str):
self.root = pathlib.Path(root)
self.name = name
def make_path(self, path: str | pathlib.PurePath) -> DirectoryPath:
path = pathlib.PurePath(path)
if path.is_absolute():
path = path.relative_to('/')
return DirectoryPath(self.root / path, self.root)
def exists(self) -> bool:
return self.root.exists()
@contextlib.contextmanager
def open(self):
yield self
def __repr__(self) -> str:
return f'DirectorySource({self.root})'
class SgaSource(AbstractSource):
def __init__(self, path: str | pathlib.Path, name: str):
self.path = path
self.name = name
self._archive = None
@property
def archive(self):
if self._archive is None and self.path.exists():
self._archive = SgaArchive.parse(self.path)
return self._archive
def make_path(self, path: str | pathlib.PurePath) -> SgaPath:
return self.archive.make_path(path)
def exists(self) -> bool:
return self.path.exists()
@contextlib.contextmanager
def open(self):
archive = self.archive
if archive is not None:
with archive.open():
yield self
return
yield self
def __repr__(self) -> str:
return f'SgaSource({self.path})'
def iter_path_candidates(part: str) -> typing.Generator[str, None, None]:
yield part
yield part.lower()
yield part.upper()
yield part.title()
def try_find_path(root: pathlib.Path, *parts: str) -> pathlib.Path:
curr = root
for part in parts:
for part_case in iter_path_candidates(part):
if (candidate := curr / part_case).exists():
curr = candidate
break
else:
if curr.is_dir():
for c in curr.iterdir():
if c.name.lower() == part.lower():
curr = c
break
else:
for p in parts:
root /= p
return root
return curr
@dataclasses.dataclass
class DowLayout:
default_lang: str = 'english'
default_texture_level: TextureLevel = TextureLevel.HIGH
default_sound_level: SoundLevel = SoundLevel.HIGH
default_model_level: ModelLevel = ModelLevel.HIGH
sources: list[AbstractSource] = dataclasses.field(default_factory=list)
@classmethod
def from_mod_folder(cls, path: str | pathlib.Path, include_movies: bool = True, include_locale: bool = True) -> 'DowLayout':
path = pathlib.Path(path)
dow_folder = path.parent
res = cls._initilize_defaults(dow_folder)
mod_configs = cls.load_mod_configs_options(dow_folder)
required_mods = [mod_configs.get(path.name.lower(), cls._make_default_mod_config(path.name))]
for required_mod_name in required_mods[0].get('requiredmods', ['dxp2', 'w40k']) + ['engine']:
required_mods.append(mod_configs.get(required_mod_name.lower(), cls._make_default_mod_config(required_mod_name)))
for mod in required_mods:
res.sources.append(DirectorySource(try_find_path(dow_folder, mod['modfolder'], 'Data'), name=mod['modfolder']))
for folder in mod.get('datafolders', []):
folder = res.interpolate_path(folder)
res.sources.append(SgaSource(try_find_path(dow_folder, mod['modfolder'], f'{folder}.sga'), name=mod['modfolder']))
for file in mod.get('archivefiles', []):
file = res.interpolate_path(file)
res.sources.append(SgaSource(try_find_path(dow_folder, mod['modfolder'], f'{file}.sga'), name=mod['modfolder']))
for mod in required_mods:
if include_movies:
res.sources.append(DirectorySource(try_find_path(dow_folder, mod['modfolder'], 'Movies'), name=mod['modfolder']))
if include_locale:
res.sources.append(DirectorySource(try_find_path(dow_folder, mod['modfolder'], res.interpolate_path('%LOCALE%')), name=mod['modfolder']))
return res
@classmethod
def _initilize_defaults(cls, root: pathlib.Path) -> 'DowLayout':
lang_config = cls.load_lang(root)
game_config = cls.load_game_options(root)
res = cls()
res.default_lang = lang_config.get('default', res.default_lang)
res.default_texture_level = game_config.get('texture_level', res.default_texture_level)
res.default_sound_level = game_config.get('texture_level', res.default_sound_level)
res.default_model_level = game_config.get('model_level', res.default_model_level)
return res
@classmethod
def _make_default_mod_config(cls, folder_name: str) -> dict:
return {
'modfolder': folder_name,
'datafolders': ['Data']
}
@classmethod
def load_lang(cls, path: pathlib.Path) -> dict:
conf_path = path / 'regions.ini'
if not conf_path.is_file():
return {}
try:
config = configparser.ConfigParser()
config.read(conf_path)
return {
**{k.lower(): v for k, v in config['mods'].items()},
'default': config['global']['lang'],
}
except Exception:
return {}
@classmethod
def load_game_options(cls, path: pathlib.Path) -> dict:
return {} # TODO
@classmethod
def load_mod_configs_options(cls, path: pathlib.Path) -> dict:
result = {}
for file in path.iterdir():
if file.suffix.lower() != '.module' or not file.is_file():
continue
config = configparser.ConfigParser(interpolation=None, comment_prefixes=('#', ';', '--'))
config.read(file)
config = config['global']
result[file.stem.lower()] = {
**{k: config[k] for k in ('uiname', 'description', 'modfolder')},
**{
f'{key}s': [
i for _, i in sorted([(k, v)
for k, v in config.items()
if k.startswith(f'{key}.')
], key=lambda x: int(x[0].rsplit('.')[1]))
]
for key in ('datafolder', 'archivefile', 'requiredmod')
},
}
if 'engine' not in result:
result['engine'] = {
'modfolder': 'engine',
'archivefiles': ['%LOCALE%\EnginLoc', 'Engine', 'Engine-New'],
}
return result
def interpolate_path(
self,
path: str,
lang: str = None,
texture_level: TextureLevel = None,
sound_level: SoundLevel = None,
model_level: ModelLevel = None,
) -> str:
path = path.replace('%LOCALE%', 'Locale/' + (lang or self.default_lang).title())
path = path.replace('%TEXTURE-LEVEL%', texture_level or self.default_texture_level)
path = path.replace('%SOUND-LEVEL%', sound_level or self.default_sound_level)
path = path.replace('%MODEL-LEVEL%', model_level or self.default_model_level)
return pathlib.PureWindowsPath(path).as_posix()
def iter_paths(self, path: str | pathlib.PurePath, return_missing: bool = False) -> typing.Generator[LayoutPath, None, None]:
path = pathlib.PurePath(path)
for source in self.sources:
if not source.exists():
continue
source_path = try_find_path(source.make_path('.'), *path.parts)
if return_missing or source_path.exists():
yield source_path
def find(self, path: str | pathlib.PurePath, default: T = None) -> LayoutPath | T:
for p in self.iter_paths(path):
return p
return default
def iterdir(self, path: str | pathlib.PurePath) -> typing.Generator[LayoutPath, None, None]:
seen_files = set()
for source in self.sources:
if not source.exists():
continue
source_path = source.make_path(path)
if source_path.exists():
for i in source_path.iterdir():
if i.name.lower() not in seen_files:
seen_files.add(i.name.lower())
yield i
@contextlib.contextmanager
def open(self):
with contextlib.ExitStack() as stack:
for source in self.sources:
if source.exists():
stack.enter_context(source.open())
yield self