Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathbuild_libtcod.py
More file actions
Latest commit
executable file
·408 lines (335 loc) · 13.4 KB
/
Copy pathbuild_libtcod.py
File metadata and controls
executable file
·408 lines (335 loc) · 13.4 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
#!/usr/bin/env python3
"""Parse and compile libtcod and SDL sources for CFFI."""
from __future__ importannotations
importcontextlib
importglob
importos
importplatform
importre
importsys
frompathlibimportPath
fromtypingimportAny, Iterable, Iterator
fromcffiimportFFI
sys.path.append(str(Path(__file__).parent)) # Allow importing local modules.
importbuild_sdl# noqa: E402
Py_LIMITED_API=0x03060000
HEADER_PARSE_PATHS= ("tcod/", "libtcod/src/libtcod/")
HEADER_PARSE_EXCLUDES= ("gl2_ext_.h", "renderer_gl_internal.h", "event.h")
BIT_SIZE, LINKAGE=platform.architecture()
# Regular expressions to parse the headers for cffi.
RE_COMMENT=re.compile(r"\s*/\*.*?\*/|\s*//*?$", re.DOTALL|re.MULTILINE)
RE_CPLUSPLUS=re.compile(r"#ifdef __cplusplus.*?#endif.*?$", re.DOTALL|re.MULTILINE)
RE_PREPROCESSOR=re.compile(r"(?!#define\s+\w+\s+\d+$)#.*?(?<!\\)$", re.DOTALL|re.MULTILINE)
RE_INCLUDE=re.compile(r'#include "([^"]*)"')
RE_TAGS=re.compile(
r"TCODLIB_C?API|TCOD_PUBLIC|TCOD_NODISCARD|TCOD_DEPRECATED_NOMESSAGE|TCOD_DEPRECATED_ENUM"
r"|(TCOD_DEPRECATED\(\".*?\"\))"
r"|(TCOD_DEPRECATED|TCODLIB_FORMAT)\([^)]*\)|__restrict"
)
RE_VAFUNC=re.compile(r"^[^;]*\([^;]*va_list.*\);", re.MULTILINE)
RE_INLINE=re.compile(r"(^.*?inline.*?\(.*?\))\s*\{.*?\}$", re.DOTALL|re.MULTILINE)
classParsedHeader:
"""Header manager class for parsing headers.
Holds parsed sources and keeps information needed to resolve header order.
"""
# Class dictionary of all parsed headers.
all_headers: dict[Path, ParsedHeader] = {}
def__init__(self, path: Path) ->None:
"""Initialize and organize a header file."""
self.path=path=path.resolve(True)
directory=path.parent
depends=set()
header=self.path.read_text(encoding="utf-8")
header=RE_COMMENT.sub("", header)
header=RE_CPLUSPLUS.sub("", header)
fordependencyinRE_INCLUDE.findall(header):
depends.add((directory/str(dependency)).resolve(True))
header=RE_PREPROCESSOR.sub("", header)
header=RE_TAGS.sub("", header)
header=RE_VAFUNC.sub("", header)
header=RE_INLINE.sub(r"\1;", header)
self.header=header.strip()
self.depends=frozenset(depends)
self.all_headers[self.path] =self
defparsed_depends(self) ->Iterator[ParsedHeader]:
"""Return dependencies excluding ones that were not loaded."""
fordepinself.depends:
withcontextlib.suppress(KeyError):
yieldself.all_headers[dep]
def__str__(self) ->str:
"""Return useful info on this object."""
return"Parsed harder at '{}'\n Depends on: {}".format(
self.path,
"\n\t".join(str(d) fordinself.depends),
)
def__repr__(self) ->str:
"""Return the representation of this object."""
returnf"ParsedHeader({self.path!r})"
defwalk_includes(directory: str) ->Iterator[ParsedHeader]:
"""Parse all the include files in a directory and subdirectories."""
forpath, _dirs, filesinos.walk(directory):
forfileinfiles:
iffileinHEADER_PARSE_EXCLUDES:
continue
iffile.endswith(".h"):
yieldParsedHeader(Path(path, file).resolve(True))
defresolve_dependencies(
includes: Iterable[ParsedHeader],
) ->list[ParsedHeader]:
"""Sort headers by their correct include order."""
unresolved=set(includes)
resolved: set[ParsedHeader] =set()
result= []
whileunresolved:
foriteminunresolved:
iffrozenset(item.parsed_depends()).issubset(resolved):
resolved.add(item)
result.append(item)
ifnotunresolved&resolved:
msg= (
"Could not resolve header load order."
"\nPossible cyclic dependency with the unresolved headers:"
f"\n{unresolved}"
)
raiseRuntimeError(msg)
unresolved-=resolved
returnresult
defparse_includes() ->list[ParsedHeader]:
"""Collect all parsed header files and return them.
Reads HEADER_PARSE_PATHS and HEADER_PARSE_EXCLUDES.
"""
includes: list[ParsedHeader] = []
fordirpathinHEADER_PARSE_PATHS:
includes.extend(walk_includes(dirpath))
returnresolve_dependencies(includes)
defwalk_sources(directory: str) ->Iterator[str]:
"""Iterate over the C sources of a directory recursively."""
forpath, _dirs, filesinos.walk(directory):
forsourceinfiles:
ifsource.endswith(".c"):
yieldstr(Path(path, source))
includes=parse_includes()
module_name="tcod._libtcod"
include_dirs: list[str] = [
".",
"libtcod/src/vendor/",
"libtcod/src/vendor/utf8proc",
"libtcod/src/vendor/zlib/",
*build_sdl.include_dirs,
]
extra_compile_args: list[str] = [*build_sdl.extra_compile_args]
extra_link_args: list[str] = [*build_sdl.extra_link_args]
sources: list[str] = []
libraries: list[str] = [*build_sdl.libraries]
library_dirs: list[str] = [*build_sdl.library_dirs]
define_macros: list[tuple[str, Any]] = [("Py_LIMITED_API", Py_LIMITED_API)]
sources+=walk_sources("tcod/")
sources+=walk_sources("libtcod/src/libtcod/")
sources+= ["libtcod/src/vendor/stb.c"]
sources+= ["libtcod/src/vendor/lodepng.c"]
sources+= ["libtcod/src/vendor/utf8proc/utf8proc.c"]
sources+=glob.glob("libtcod/src/vendor/zlib/*.c")
ifsys.platform=="win32":
libraries+= ["User32"]
define_macros.append(("TCODLIB_API", ""))
define_macros.append(("_CRT_SECURE_NO_WARNINGS", None))
ifsys.platformin ["win32", "darwin"]:
include_dirs.append("libtcod/src/zlib/")
ifsys.platform=="darwin":
# Fix "implicit declaration of function 'close'" in zlib.
define_macros.append(("HAVE_UNISTD_H", 1))
tdl_build=os.environ.get("TDL_BUILD", "RELEASE").upper()
MSVC_CFLAGS= {"DEBUG": ["/Od"], "RELEASE": ["/GL", "/O2", "/GS-", "/wd4996"]}
MSVC_LDFLAGS: dict[str, list[str]] = {"DEBUG": [], "RELEASE": ["/LTCG"]}
GCC_CFLAGS= {
"DEBUG": ["-std=c99", "-Og", "-g", "-fPIC"],
"RELEASE": [
"-std=c99",
"-flto",
"-O3",
"-g",
"-fPIC",
"-Wno-deprecated-declarations",
"-Wno-discarded-qualifiers", # Ignore discarded restrict qualifiers.
],
}
ifsys.platform=="win32"and"--compiler=mingw32"notinsys.argv:
extra_compile_args.extend(MSVC_CFLAGS[tdl_build])
extra_link_args.extend(MSVC_LDFLAGS[tdl_build])
else:
extra_compile_args.extend(GCC_CFLAGS[tdl_build])
extra_link_args.extend(GCC_CFLAGS[tdl_build])
ffi=FFI()
ffi.cdef(build_sdl.get_cdef())
forincludeinincludes:
try:
ffi.cdef(include.header)
exceptException:
# Print the source, for debugging.
print(f"Error with: {include.path}")
fori, lineinenumerate(include.header.split("\n"), 1):
print("%03i %s"% (i, line))
raise
ffi.cdef(
"""
#define TCOD_COMPILEDVERSION ...
"""
)
ffi.set_source(
module_name,
"#include <tcod/cffi.h>\n#include <SDL.h>",
include_dirs=include_dirs,
library_dirs=library_dirs,
sources=sources,
libraries=libraries,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
define_macros=define_macros,
py_limited_api=True,
)
CONSTANT_MODULE_HEADER='''"""Constants from the libtcod C API.
This module is auto-generated by `build_libtcod.py`.
"""
from tcod.color import Color
'''
EVENT_CONSTANT_MODULE_HEADER='''"""Event constants from SDL's C API.
This module is auto-generated by `build_libtcod.py`.
"""
'''
deffind_sdl_attrs(prefix: str) ->Iterator[tuple[str, int|str|Any]]:
"""Return names and values from `tcod.lib`.
`prefix` is used to filter out which names to copy.
"""
fromtcod._libtcodimportlib# type: ignore
ifprefix.startswith("SDL_"):
name_starts_at=4
elifprefix.startswith("SDL"):
name_starts_at=3
else:
name_starts_at=0
forattrindir(lib):
ifattr.startswith(prefix):
yieldattr[name_starts_at:], getattr(lib, attr)
defparse_sdl_attrs(prefix: str, all_names: list[str] |None) ->tuple[str, str]:
"""Return the name/value pairs, and the final dictionary string for the library attributes with `prefix`.
Append matching names to the `all_names` list.
"""
names= []
lookup= []
forname, valueinsorted(find_sdl_attrs(prefix), key=lambdaitem: item[1]):
ifname=="KMOD_RESERVED":
continue
ifall_namesisnotNone:
all_names.append(name)
names.append(f"{name} = {value}")
lookup.append(f'{value}: "{name}"')
return"\n".join(names), "{{\n {},\n}}".format(",\n ".join(lookup))
EXCLUDE_CONSTANTS= [
"TCOD_MAJOR_VERSION",
"TCOD_MINOR_VERSION",
"TCOD_PATCHLEVEL",
"TCOD_COMPILEDVERSION",
"TCOD_PATHFINDER_MAX_DIMENSIONS",
"TCOD_KEY_TEXT_SIZE",
"TCOD_NOISE_MAX_DIMENSIONS",
"TCOD_NOISE_MAX_OCTAVES",
"TCOD_FALLBACK_FONT_SIZE",
]
EXCLUDE_CONSTANT_PREFIXES= [
"TCOD_E_",
"TCOD_HEAP_",
"TCOD_LEX_",
"TCOD_CHARMAP_",
"TCOD_LOG_",
]
defupdate_module_all(filename: Path, new_all: str) ->None:
"""Update the __all__ of a file with the constants from new_all."""
RE_CONSTANTS_ALL=re.compile(
r"(.*# --- From constants.py ---).*(# --- End constants.py ---.*)",
re.DOTALL,
)
match=RE_CONSTANTS_ALL.match(filename.read_text(encoding="utf-8"))
assertmatch, f"Can't determine __all__ subsection in {filename}!"
header, footer=match.groups()
filename.write_text(f"{header}\n{new_all},\n{footer}", encoding="utf-8")
defgenerate_enums(prefix: str) ->Iterator[str]:
"""Generate attribute assignments suitable for a Python enum."""
forsymbol, valueinsorted(find_sdl_attrs(prefix), key=lambdaitem: item[1]):
_, name=symbol.split("_", 1)
ifname.isdigit():
name=f"N{name}"
ifnamein"IOl": # Ignore ambiguous variable name warnings.
yieldf"{name} = {value} # noqa: E741"
else:
yieldf"{name} = {value}"
defwrite_library_constants() ->None:
"""Write libtcod constants into the tcod.constants module."""
importtcod.color
fromtcod._libtcodimportffi, lib
withPath("tcod/constants.py").open("w", encoding="utf-8") asf:
all_names= []
f.write(CONSTANT_MODULE_HEADER)
fornameindir(lib):
# To exclude specific names use either EXCLUDE_CONSTANTS or
# EXCLUDE_CONSTANT_PREFIXES before editing this.
ifname.endswith("_"):
continue
ifnameinEXCLUDE_CONSTANTS:
continue
ifany(name.startswith(prefix) forprefixinEXCLUDE_CONSTANT_PREFIXES):
continue
value=getattr(lib, name)
ifname[:5] =="TCOD_":
ifname.isupper(): # const names
f.write(f"{name[5:]} = {value!r}\n")
all_names.append(name[5:])
elifname.startswith("FOV"): # fov const names
f.write(f"{name} = {value!r}\n")
all_names.append(name)
elifname[:6] =="TCODK_": # key name
f.write(f"KEY_{name[6:]} = {value!r}\n")
all_names.append(f"KEY_{name[6:]}")
f.write("\n# --- colors ---\n")
fornameindir(lib):
ifname[:5] !="TCOD_":
continue
value=getattr(lib, name)
ifnotisinstance(value, ffi.CData):
continue
ifffi.typeof(value) !=ffi.typeof("TCOD_color_t"):
continue
color=tcod.color.Color._new_from_cdata(value)
f.write(f"{name[5:]} = {color!r}\n")
all_names_merged=",\n ".join(f'"{name}"'fornameinall_names)
f.write(f"\n__all__ = [\n{all_names_merged},\n]\n")
update_module_all(Path("tcod/__init__.py"), all_names_merged)
update_module_all(Path("tcod/libtcodpy.py"), all_names_merged)
withPath("tcod/event_constants.py").open("w", encoding="utf-8") asf:
all_names= []
f.write(EVENT_CONSTANT_MODULE_HEADER)
f.write("\n# --- SDL scancodes ---\n")
f.write(f"""{parse_sdl_attrs("SDL_SCANCODE", None)[0]}\n""")
f.write("\n# --- SDL keyboard symbols ---\n")
f.write(f"""{parse_sdl_attrs("SDLK", None)[0]}\n""")
f.write("\n# --- SDL keyboard modifiers ---\n")
f.write("{}\n_REVERSE_MOD_TABLE = {}\n".format(*parse_sdl_attrs("KMOD", all_names)))
f.write("\n# --- SDL wheel ---\n")
f.write("{}\n_REVERSE_WHEEL_TABLE = {}\n".format(*parse_sdl_attrs("SDL_MOUSEWHEEL", all_names)))
all_names_merged=",\n ".join(f'"{name}"'fornameinall_names)
f.write(f"\n__all__ = [\n{all_names_merged},\n]\n")
event_py=Path("tcod/event.py").read_text(encoding="utf-8")
event_py=re.sub(
r"(?<=# --- SDL scancodes ---\n ).*?(?=\n # --- end ---\n)",
"\n ".join(generate_enums("SDL_SCANCODE")),
event_py,
flags=re.DOTALL,
)
event_py=re.sub(
r"(?<=# --- SDL keyboard symbols ---\n ).*?(?=\n # --- end ---\n)",
"\n ".join(generate_enums("SDLK")),
event_py,
flags=re.DOTALL,
)
Path("tcod/event.py").write_text(event_py, encoding="utf-8")
if__name__=="__main__":
write_library_constants()