0.2.0-dev Download ZIP
1703 lines ·65.2 KB Raw
| 1 | import atexit |
| 2 | import contextlib |
| 3 | import glob |
| 4 | import math |
| 5 | import os |
| 6 | import re |
| 7 | import subprocess |
| 8 | import sys |
| 9 | import zlib |
| 10 | from collections import OrderedDict |
| 11 | from collections.abc import Generator |
| 12 | from io import StringIO |
| 13 | from pathlib import Path |
| 14 | from typing import TextIO, cast |
| 15 | |
| 16 | from misc.utility.color import print_error, print_info, print_warning |
| 17 | from platform_methods import detect_arch |
| 18 | |
| 19 | # Get the "Godot" folder name ahead of time |
| 20 | base_folder = Path(__file__).resolve().parent |
| 21 | |
| 22 | compiler_version_cache = None |
| 23 | |
| 24 | # Listing all the folders we have converted |
| 25 | # for SCU in scu_builders.py |
| 26 | _scu_folders = set[str]() |
| 27 | |
| 28 | |
| 29 | def set_scu_folders(scu_folders): |
| 30 | global _scu_folders |
| 31 | _scu_folders = scu_folders |
| 32 | |
| 33 | |
| 34 | def add_source_files_orig(self, sources, files, allow_gen=False): |
| 35 | # Convert string to list of absolute paths (including expanding wildcard) |
| 36 | if isinstance(files, str): |
| 37 | # Exclude .gen.cpp files from globbing, to avoid including obsolete ones. |
| 38 | # They should instead be added manually. |
| 39 | skip_gen_cpp = "*" in files |
| 40 | files = self.Glob(files) |
| 41 | if skip_gen_cpp and not allow_gen: |
| 42 | files = [f for f in files if not str(f).endswith(".gen.cpp")] |
| 43 | |
| 44 | # Add each path as compiled Object following environment (self) configuration |
| 45 | for file in files: |
| 46 | obj = self.Object(file) |
| 47 | if obj in sources: |
| 48 | print_warning(f'Object "{obj}" already included in environment sources.') |
| 49 | continue |
| 50 | sources.append(obj) |
| 51 | |
| 52 | |
| 53 | def add_source_files_scu(self, sources, files, allow_gen=False): |
| 54 | if self["scu_build"] and isinstance(files, str): |
| 55 | if "*." not in files: |
| 56 | return False |
| 57 | |
| 58 | # If the files are in a subdirectory, we want to create the scu gen |
| 59 | # files inside this subdirectory. |
| 60 | subdir = os.path.dirname(files) |
| 61 | subdir = subdir if subdir == "" else subdir + "/" |
| 62 | section_name = self.Dir(subdir).tpath |
| 63 | section_name = section_name.replace("\\", "/") # win32 |
| 64 | # if the section name is in the hash table? |
| 65 | # i.e. is it part of the SCU build? |
| 66 | global _scu_folders |
| 67 | if section_name not in (_scu_folders): |
| 68 | return False |
| 69 | |
| 70 | # Add all the gen.cpp files in the SCU directory |
| 71 | add_source_files_orig(self, sources, subdir + ".scu/scu_*.gen.cpp", True) |
| 72 | return True |
| 73 | return False |
| 74 | |
| 75 | |
| 76 | # Either builds the folder using the SCU system, |
| 77 | # or reverts to regular build. |
| 78 | def add_source_files(self, sources, files, allow_gen=False): |
| 79 | if not add_source_files_scu(self, sources, files, allow_gen): |
| 80 | # Wraps the original function when scu build is not active. |
| 81 | add_source_files_orig(self, sources, files, allow_gen) |
| 82 | return False |
| 83 | return True |
| 84 | |
| 85 | |
| 86 | def redirect_emitter(target, source, env): |
| 87 | """ |
| 88 | Emitter to automatically redirect object/library build files to the `bin/obj` directory, |
| 89 | retaining subfolder structure. External build files will attempt to retain subfolder |
| 90 | structure relative to their environment's parent directory, sorted under `bin/obj/external`. |
| 91 | If `redirect_build_objects` is `False`, an external build file isn't relative to the passed |
| 92 | environment, or a file is being written directly into `bin`, this emitter does nothing. |
| 93 | """ |
| 94 | if not env["redirect_build_objects"]: |
| 95 | return target, source |
| 96 | |
| 97 | redirected_targets = [] |
| 98 | for item in target: |
| 99 | path = Path(item.get_abspath()).resolve() |
| 100 | |
| 101 | if path.parent == base_folder / "bin": |
| 102 | pass |
| 103 | elif base_folder in path.parents: |
| 104 | item = env.File(f"#bin/obj/{path.relative_to(base_folder)}") |
| 105 | elif (alt_base := Path(env.Dir(".").get_abspath()).resolve().parent) in path.parents: |
| 106 | item = env.File(f"#bin/obj/external/{path.relative_to(alt_base)}") |
| 107 | else: |
| 108 | print_warning(f'Failed to redirect "{path}"') |
| 109 | redirected_targets.append(item) |
| 110 | return redirected_targets, source |
| 111 | |
| 112 | |
| 113 | def disable_warnings(self): |
| 114 | # 'self' is the environment |
| 115 | if self.msvc and not using_clang(self): |
| 116 | self["WARNLEVEL"] = "/w" |
| 117 | else: |
| 118 | self["WARNLEVEL"] = "-w" |
| 119 | |
| 120 | |
| 121 | def force_optimization_on_debug(self): |
| 122 | # 'self' is the environment |
| 123 | if self["target"] == "template_release": |
| 124 | return |
| 125 | elif self.msvc: |
| 126 | self["OPTIMIZELEVEL"] = "/O2" |
| 127 | else: |
| 128 | self["OPTIMIZELEVEL"] = "-O3" |
| 129 | |
| 130 | |
| 131 | def add_module_version_string(self, s): |
| 132 | self.module_version_string += "." + s |
| 133 | |
| 134 | |
| 135 | def get_version_info(module_version_string="", silent=False): |
| 136 | build_name = "custom_build" |
| 137 | if os.getenv("BUILD_NAME") is not None: |
| 138 | build_name = str(os.getenv("BUILD_NAME")) |
| 139 | if not silent: |
| 140 | print_info(f"Using custom build name: '{build_name}'.") |
| 141 | |
| 142 | import version |
| 143 | |
| 144 | version_info = { |
| 145 | "short_name": str(version.short_name), |
| 146 | "name": str(version.name), |
| 147 | "major": int(version.major), |
| 148 | "minor": int(version.minor), |
| 149 | "patch": int(version.patch), |
| 150 | "status": str(version.status), |
| 151 | "build": str(build_name), |
| 152 | "module_config": str(version.module_config) + module_version_string, |
| 153 | "website": str(version.website), |
| 154 | "docs_branch": str(version.docs), |
| 155 | } |
| 156 | |
| 157 | # For dev snapshots (alpha, beta, RC, etc.) we do not commit status change to Git, |
| 158 | # so this define provides a way to override it without having to modify the source. |
| 159 | if os.getenv("GODOT_VERSION_STATUS") is not None: |
| 160 | version_info["status"] = str(os.getenv("GODOT_VERSION_STATUS")) |
| 161 | if not silent: |
| 162 | print_info(f"Using version status '{version_info['status']}', overriding the original '{version.status}'.") |
| 163 | |
| 164 | return version_info |
| 165 | |
| 166 | |
| 167 | def get_git_info(): |
| 168 | os.chdir(base_folder) |
| 169 | |
| 170 | # Parse Git hash if we're in a Git repo. |
| 171 | git_hash = "" |
| 172 | git_folder = ".git" |
| 173 | |
| 174 | if os.path.isfile(".git"): |
| 175 | with open(".git", "r", encoding="utf-8") as file: |
| 176 | module_folder = file.readline().strip() |
| 177 | if module_folder.startswith("gitdir: "): |
| 178 | git_folder = module_folder[8:] |
| 179 | |
| 180 | if os.path.isfile(os.path.join(git_folder, "HEAD")): |
| 181 | with open(os.path.join(git_folder, "HEAD"), "r", encoding="utf8") as file: |
| 182 | head = file.readline().strip() |
| 183 | if head.startswith("ref: "): |
| 184 | ref = head[5:] |
| 185 | # If this directory is a Git worktree instead of a root clone. |
| 186 | parts = git_folder.split("/") |
| 187 | if len(parts) > 2 and parts[-2] == "worktrees": |
| 188 | git_folder = "/".join(parts[0:-2]) |
| 189 | head = os.path.join(git_folder, ref) |
| 190 | packedrefs = os.path.join(git_folder, "packed-refs") |
| 191 | if os.path.isfile(head): |
| 192 | with open(head, "r", encoding="utf-8") as file: |
| 193 | git_hash = file.readline().strip() |
| 194 | elif os.path.isfile(packedrefs): |
| 195 | # Git may pack refs into a single file. This code searches .git/packed-refs file for the current ref's hash. |
| 196 | # https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-pack-refs.html |
| 197 | for line in open(packedrefs, "r", encoding="utf-8").read().splitlines(): |
| 198 | if line.startswith("#"): |
| 199 | continue |
| 200 | (line_hash, line_ref) = line.split(" ") |
| 201 | if ref == line_ref: |
| 202 | git_hash = line_hash |
| 203 | break |
| 204 | else: |
| 205 | git_hash = head |
| 206 | |
| 207 | # Get the UNIX timestamp of the build commit. |
| 208 | git_timestamp = 0 |
| 209 | if os.path.exists(".git"): |
| 210 | try: |
| 211 | git_timestamp = subprocess.check_output( |
| 212 | ["git", "log", "-1", "--pretty=format:%ct", "--no-show-signature", git_hash], encoding="utf-8" |
| 213 | ) |
| 214 | except (subprocess.CalledProcessError, OSError): |
| 215 | # `git` not found in PATH. |
| 216 | pass |
| 217 | |
| 218 | return { |
| 219 | "git_hash": git_hash, |
| 220 | "git_timestamp": git_timestamp, |
| 221 | } |
| 222 | |
| 223 | |
| 224 | def get_cmdline_bool(option, default): |
| 225 | """We use `ARGUMENTS.get()` to check if options were manually overridden on the command line, |
| 226 | and SCons' _text2bool helper to convert them to booleans, otherwise they're handled as strings. |
| 227 | """ |
| 228 | from SCons.Script import ARGUMENTS |
| 229 | from SCons.Variables.BoolVariable import _text2bool |
| 230 | |
| 231 | cmdline_val = ARGUMENTS.get(option) |
| 232 | if cmdline_val is not None: |
| 233 | return _text2bool(cmdline_val) |
| 234 | else: |
| 235 | return default |
| 236 | |
| 237 | |
| 238 | def detect_modules(search_path, recursive=False): |
| 239 | """Detects and collects a list of C++ modules at specified path |
| 240 | |
| 241 | `search_path` - a directory path containing modules. The path may point to |
| 242 | a single module, which may have other nested modules. A module must have |
| 243 | "register_types.h", "SCsub", "config.py" files created to be detected. |
| 244 | |
| 245 | `recursive` - if `True`, then all subdirectories are searched for modules as |
| 246 | specified by the `search_path`, otherwise collects all modules under the |
| 247 | `search_path` directory. If the `search_path` is a module, it is collected |
| 248 | in all cases. |
| 249 | |
| 250 | Returns an `OrderedDict` with module names as keys, and directory paths as |
| 251 | values. If a path is relative, then it is a built-in module. If a path is |
| 252 | absolute, then it is a custom module collected outside of the engine source. |
| 253 | """ |
| 254 | modules = OrderedDict() |
| 255 | |
| 256 | def add_module(path): |
| 257 | module_name = os.path.basename(path) |
| 258 | module_path = path.replace("\\", "/") # win32 |
| 259 | modules[module_name] = module_path |
| 260 | |
| 261 | def is_engine(path): |
| 262 | # Prevent recursively detecting modules in self and other |
| 263 | # Godot sources when using `custom_modules` build option. |
| 264 | version_path = os.path.join(path, "version.py") |
| 265 | if os.path.exists(version_path): |
| 266 | with open(version_path, "r", encoding="utf-8") as f: |
| 267 | if 'short_name = "godot"' in f.read(): |
| 268 | return True |
| 269 | return False |
| 270 | |
| 271 | def get_files(path): |
| 272 | files = glob.glob(os.path.join(path, "*")) |
| 273 | # Sort so that `register_module_types` does not change that often, |
| 274 | # and plugins are registered in alphabetic order as well. |
| 275 | files.sort() |
| 276 | return files |
| 277 | |
| 278 | if not recursive: |
| 279 | if is_module(search_path): |
| 280 | add_module(search_path) |
| 281 | for path in get_files(search_path): |
| 282 | if is_engine(path): |
| 283 | continue |
| 284 | if is_module(path): |
| 285 | add_module(path) |
| 286 | else: |
| 287 | to_search = [search_path] |
| 288 | while to_search: |
| 289 | path = to_search.pop() |
| 290 | if is_module(path): |
| 291 | add_module(path) |
| 292 | for child in get_files(path): |
| 293 | if not os.path.isdir(child): |
| 294 | continue |
| 295 | if is_engine(child): |
| 296 | continue |
| 297 | to_search.insert(0, child) |
| 298 | return modules |
| 299 | |
| 300 | |
| 301 | def is_module(path): |
| 302 | if not os.path.isdir(path): |
| 303 | return False |
| 304 | must_exist = ["register_types.h", "SCsub", "config.py"] |
| 305 | for f in must_exist: |
| 306 | if not os.path.exists(os.path.join(path, f)): |
| 307 | return False |
| 308 | return True |
| 309 | |
| 310 | |
| 311 | def convert_custom_modules_path(path): |
| 312 | if not path: |
| 313 | return path |
| 314 | path = os.path.realpath(os.path.expanduser(os.path.expandvars(path))) |
| 315 | err_msg = "Build option 'custom_modules' must %s" |
| 316 | if not os.path.isdir(path): |
| 317 | raise ValueError(err_msg % "point to an existing directory.") |
| 318 | if path == os.path.realpath("modules"): |
| 319 | raise ValueError(err_msg % "be a directory other than built-in `modules` directory.") |
| 320 | return path |
| 321 | |
| 322 | |
| 323 | def module_add_dependencies(self, module, dependencies, optional=False): |
| 324 | """ |
| 325 | Adds dependencies for a given module. |
| 326 | Meant to be used in module `can_build` methods. |
| 327 | """ |
| 328 | if module not in self.module_dependencies: |
| 329 | self.module_dependencies[module] = [[], []] |
| 330 | if optional: |
| 331 | self.module_dependencies[module][1].extend(dependencies) |
| 332 | else: |
| 333 | self.module_dependencies[module][0].extend(dependencies) |
| 334 | |
| 335 | |
| 336 | def module_check_dependencies(self, module): |
| 337 | """ |
| 338 | Checks if module dependencies are enabled for a given module, |
| 339 | and prints a warning if they aren't. |
| 340 | Meant to be used in module `can_build` methods. |
| 341 | Returns a boolean (True if dependencies are satisfied). |
| 342 | """ |
| 343 | missing_deps = set() |
| 344 | required_deps = self.module_dependencies[module][0] if module in self.module_dependencies else [] |
| 345 | for dep in required_deps: |
| 346 | opt = f"module_{dep}_enabled" |
| 347 | if opt not in self or not self[opt] or not module_check_dependencies(self, dep): |
| 348 | missing_deps.add(dep) |
| 349 | |
| 350 | if missing_deps: |
| 351 | if module not in self.disabled_modules: |
| 352 | print_warning( |
| 353 | "Disabling '{}' module as the following dependencies are not satisfied: {}".format( |
| 354 | module, ", ".join(missing_deps) |
| 355 | ) |
| 356 | ) |
| 357 | self.disabled_modules.add(module) |
| 358 | return False |
| 359 | else: |
| 360 | return True |
| 361 | |
| 362 | |
| 363 | def sort_module_list(env): |
| 364 | deps = {k: v[0] + list(filter(lambda x: x in env.module_list, v[1])) for k, v in env.module_dependencies.items()} |
| 365 | |
| 366 | frontier = list(env.module_list.keys()) |
| 367 | explored = [] |
| 368 | while len(frontier): |
| 369 | cur = frontier.pop() |
| 370 | deps_list = deps[cur] if cur in deps else [] |
| 371 | if len(deps_list) and any([d not in explored for d in deps_list]): |
| 372 | # Will explore later, after its dependencies |
| 373 | frontier.insert(0, cur) |
| 374 | continue |
| 375 | explored.append(cur) |
| 376 | for k in explored: |
| 377 | env.module_list.move_to_end(k) |
| 378 | |
| 379 | |
| 380 | def use_windows_spawn_fix(self, platform=None): |
| 381 | if os.name != "nt": |
| 382 | return # not needed, only for windows |
| 383 | |
| 384 | def mySubProcess(cmdline, env): |
| 385 | startupinfo = subprocess.STARTUPINFO() |
| 386 | startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW |
| 387 | popen_args = { |
| 388 | "stdin": subprocess.PIPE, |
| 389 | "stdout": subprocess.PIPE, |
| 390 | "stderr": subprocess.PIPE, |
| 391 | "startupinfo": startupinfo, |
| 392 | "shell": False, |
| 393 | "env": env, |
| 394 | } |
| 395 | popen_args["text"] = True |
| 396 | proc = subprocess.Popen(cmdline, **popen_args) |
| 397 | _, err = proc.communicate() |
| 398 | rv = proc.wait() |
| 399 | if rv: |
| 400 | print_error(err) |
| 401 | elif len(err) > 0 and not err.isspace(): |
| 402 | print(err) |
| 403 | return rv |
| 404 | |
| 405 | def mySpawn(sh, escape, cmd, args, env): |
| 406 | # Used by TEMPFILE. |
| 407 | if cmd == "del": |
| 408 | os.remove(args[1]) |
| 409 | return 0 |
| 410 | |
| 411 | newargs = " ".join(args[1:]) |
| 412 | cmdline = cmd + " " + newargs |
| 413 | |
| 414 | rv = 0 |
| 415 | env = {str(key): str(value) for key, value in iter(env.items())} |
| 416 | rv = mySubProcess(cmdline, env) |
| 417 | |
| 418 | return rv |
| 419 | |
| 420 | self["SPAWN"] = mySpawn |
| 421 | |
| 422 | |
| 423 | def no_verbose(env): |
| 424 | from misc.utility.color import Ansi, is_stdout_color |
| 425 | |
| 426 | colors = [Ansi.BLUE, Ansi.BOLD, Ansi.REGULAR, Ansi.RESET] if is_stdout_color() else ["", "", "", ""] |
| 427 | |
| 428 | # There is a space before "..." to ensure that source file names can be |
| 429 | # Ctrl + clicked in the VS Code terminal. |
| 430 | compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors) |
| 431 | java_compile_source_message = "{}Compiling {}$SOURCE{} ...{}".format(*colors) |
| 432 | compile_shared_source_message = "{}Compiling shared {}$SOURCE{} ...{}".format(*colors) |
| 433 | link_program_message = "{}Linking Program {}$TARGET{} ...{}".format(*colors) |
| 434 | link_library_message = "{}Linking Static Library {}$TARGET{} ...{}".format(*colors) |
| 435 | ranlib_library_message = "{}Ranlib Library {}$TARGET{} ...{}".format(*colors) |
| 436 | link_shared_library_message = "{}Linking Shared Library {}$TARGET{} ...{}".format(*colors) |
| 437 | java_library_message = "{}Creating Java Archive {}$TARGET{} ...{}".format(*colors) |
| 438 | compiled_resource_message = "{}Creating Compiled Resource {}$TARGET{} ...{}".format(*colors) |
| 439 | zip_archive_message = "{}Archiving {}$TARGET{} ...{}".format(*colors) |
| 440 | generated_file_message = "{}Generating {}$TARGET{} ...{}".format(*colors) |
| 441 | |
| 442 | env["CXXCOMSTR"] = compile_source_message |
| 443 | env["CCCOMSTR"] = compile_source_message |
| 444 | env["SWIFTCOMSTR"] = compile_source_message |
| 445 | env["SHCCCOMSTR"] = compile_shared_source_message |
| 446 | env["SHCXXCOMSTR"] = compile_shared_source_message |
| 447 | env["ARCOMSTR"] = link_library_message |
| 448 | env["RANLIBCOMSTR"] = ranlib_library_message |
| 449 | env["SHLINKCOMSTR"] = link_shared_library_message |
| 450 | env["LINKCOMSTR"] = link_program_message |
| 451 | env["JARCOMSTR"] = java_library_message |
| 452 | env["JAVACCOMSTR"] = java_compile_source_message |
| 453 | env["RCCOMSTR"] = compiled_resource_message |
| 454 | env["ZIPCOMSTR"] = zip_archive_message |
| 455 | env["GENCOMSTR"] = generated_file_message |
| 456 | |
| 457 | |
| 458 | def detect_visual_c_compiler_version(tools_env): |
| 459 | # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks... |
| 460 | # (see the SCons documentation for more information on what it does)... |
| 461 | # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV'] |
| 462 | # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect |
| 463 | # the proper vc version that will be called |
| 464 | |
| 465 | # There is no flag to give to visual c compilers to set the architecture, i.e. scons arch argument (x86_32, x86_64, arm64, etc.). |
| 466 | # There are many different cl.exe files that are run, and each one compiles & links to a different architecture |
| 467 | # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program() |
| 468 | # is to check the PATH variable and figure out which one will be called first. Code below does that and returns: |
| 469 | # the following string values: |
| 470 | |
| 471 | # "" Compiler not detected |
| 472 | # "amd64" Native 64 bit compiler |
| 473 | # "amd64_x86" 64 bit Cross Compiler for 32 bit |
| 474 | # "x86" Native 32 bit compiler |
| 475 | # "x86_amd64" 32 bit Cross Compiler for 64 bit |
| 476 | |
| 477 | # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm |
| 478 | # and similar architectures/compilers |
| 479 | |
| 480 | # Set chosen compiler to "not detected" |
| 481 | vc_chosen_compiler_index = -1 |
| 482 | vc_chosen_compiler_str = "" |
| 483 | |
| 484 | # VS 2017 and newer should set VCTOOLSINSTALLDIR |
| 485 | if "VCTOOLSINSTALLDIR" in tools_env: |
| 486 | # Newer versions have a different path available |
| 487 | vc_amd64_compiler_detection_index = ( |
| 488 | tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X64;") |
| 489 | ) |
| 490 | if vc_amd64_compiler_detection_index > -1: |
| 491 | vc_chosen_compiler_index = vc_amd64_compiler_detection_index |
| 492 | vc_chosen_compiler_str = "amd64" |
| 493 | |
| 494 | vc_amd64_x86_compiler_detection_index = ( |
| 495 | tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX64\\X86;") |
| 496 | ) |
| 497 | if vc_amd64_x86_compiler_detection_index > -1 and ( |
| 498 | vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index |
| 499 | ): |
| 500 | vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index |
| 501 | vc_chosen_compiler_str = "amd64_x86" |
| 502 | |
| 503 | vc_x86_compiler_detection_index = ( |
| 504 | tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X86;") |
| 505 | ) |
| 506 | if vc_x86_compiler_detection_index > -1 and ( |
| 507 | vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_compiler_detection_index |
| 508 | ): |
| 509 | vc_chosen_compiler_index = vc_x86_compiler_detection_index |
| 510 | vc_chosen_compiler_str = "x86" |
| 511 | |
| 512 | vc_x86_amd64_compiler_detection_index = ( |
| 513 | tools_env["PATH"].upper().find(tools_env["VCTOOLSINSTALLDIR"].upper() + "BIN\\HOSTX86\\X64;") |
| 514 | ) |
| 515 | if vc_x86_amd64_compiler_detection_index > -1 and ( |
| 516 | vc_chosen_compiler_index == -1 or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index |
| 517 | ): |
| 518 | vc_chosen_compiler_str = "x86_amd64" |
| 519 | |
| 520 | return vc_chosen_compiler_str |
| 521 | |
| 522 | |
| 523 | def find_visual_c_batch_file(env): |
| 524 | # TODO: We should investigate if we can avoid relying on SCons internals here. |
| 525 | from SCons.Tool.MSCommon.vc import find_batch_file, find_vc_pdir, get_default_version, get_host_target |
| 526 | |
| 527 | msvc_version = get_default_version(env) |
| 528 | host_platform, target_platform, _ = get_host_target(env, msvc_version) |
| 529 | |
| 530 | if env.scons_version < (4, 6, 0): |
| 531 | return find_batch_file(env, msvc_version, host_platform, target_platform)[0] |
| 532 | |
| 533 | # SCons 4.6.0+ removed passing env, so we need to get the product_dir ourselves first, |
| 534 | # then pass that as the last param instead of env as the first param as before. |
| 535 | # Param names need to be explicit, as they were shuffled around in SCons 4.8.0. |
| 536 | product_dir = find_vc_pdir(msvc_version=msvc_version, env=env) |
| 537 | |
| 538 | return find_batch_file(msvc_version, host_platform, target_platform, product_dir)[0] |
| 539 | |
| 540 | |
| 541 | def generate_cpp_hint_file(filename): |
| 542 | if os.path.isfile(filename): |
| 543 | # Don't overwrite an existing hint file since the user may have customized it. |
| 544 | pass |
| 545 | else: |
| 546 | try: |
| 547 | with open(filename, "w", encoding="utf-8", newline="\n") as fd: |
| 548 | fd.write("#define GDCLASS(m_class, m_inherits)\n") |
| 549 | for name in ["GDVIRTUAL", "EXBIND", "MODBIND"]: |
| 550 | for count in range(13): |
| 551 | for suffix in ["", "R", "C", "RC"]: |
| 552 | fd.write(f"#define {name}{count}{suffix}(") |
| 553 | if "R" in suffix: |
| 554 | fd.write("m_ret, ") |
| 555 | fd.write("m_name") |
| 556 | for idx in range(1, count + 1): |
| 557 | fd.write(f", type{idx}") |
| 558 | fd.write(")\n") |
| 559 | |
| 560 | except OSError: |
| 561 | print_warning("Could not write cpp.hint file.") |
| 562 | |
| 563 | |
| 564 | def glob_recursive(pattern, node="."): |
| 565 | from SCons import Node |
| 566 | from SCons.Script import Glob |
| 567 | |
| 568 | results = [] |
| 569 | for f in Glob(str(node) + "/*", source=True): |
| 570 | if type(f) is Node.FS.Dir: |
| 571 | results += glob_recursive(pattern, f) |
| 572 | results += Glob(str(node) + "/" + pattern, source=True) |
| 573 | return results |
| 574 | |
| 575 | |
| 576 | def precious_program(env, program, sources, **args): |
| 577 | program = env.Program(program, sources, **args) |
| 578 | env.Precious(program) |
| 579 | return program |
| 580 | |
| 581 | |
| 582 | def add_shared_library(env, name, sources, **args): |
| 583 | library = env.SharedLibrary(name, sources, **args) |
| 584 | env.NoCache(library) |
| 585 | return library |
| 586 | |
| 587 | |
| 588 | def add_library(env, name, sources, **args): |
| 589 | library = env.Library(name, sources, **args) |
| 590 | env.NoCache(library) |
| 591 | return library |
| 592 | |
| 593 | |
| 594 | def add_program(env, name, sources, **args): |
| 595 | program = env.Program(name, sources, **args) |
| 596 | env.NoCache(program) |
| 597 | return program |
| 598 | |
| 599 | |
| 600 | def CommandNoCache(env, target, sources, command, **args): |
| 601 | result = env.Command(target, sources, command, **args) |
| 602 | env.NoCache(result) |
| 603 | return result |
| 604 | |
| 605 | |
| 606 | def Run(env, function, comstr="$GENCOMSTR"): |
| 607 | from SCons.Script import Action |
| 608 | |
| 609 | return Action(function, comstr) |
| 610 | |
| 611 | |
| 612 | def detect_darwin_toolchain_path(env): |
| 613 | var_name = "APPLE_TOOLCHAIN_PATH" |
| 614 | if not env[var_name]: |
| 615 | try: |
| 616 | xcode_path = subprocess.check_output(["xcode-select", "-p"]).strip().decode("utf-8") |
| 617 | if xcode_path: |
| 618 | env[var_name] = xcode_path + "/Toolchains/XcodeDefault.xctoolchain" |
| 619 | except (subprocess.CalledProcessError, OSError): |
| 620 | print_error("Failed to find SDK path while running 'xcode-select -p'.") |
| 621 | raise |
| 622 | |
| 623 | |
| 624 | def detect_darwin_sdk_path(platform, env): |
| 625 | sdk_name = "" |
| 626 | |
| 627 | if platform == "macos": |
| 628 | sdk_name = "macosx" |
| 629 | var_name = "MACOS_SDK_PATH" |
| 630 | |
| 631 | elif platform == "ios": |
| 632 | sdk_name = "iphoneos" |
| 633 | var_name = "APPLE_SDK_PATH" |
| 634 | |
| 635 | elif platform == "iossimulator": |
| 636 | sdk_name = "iphonesimulator" |
| 637 | var_name = "APPLE_SDK_PATH" |
| 638 | |
| 639 | elif platform == "visionos": |
| 640 | sdk_name = "xros" |
| 641 | var_name = "APPLE_SDK_PATH" |
| 642 | |
| 643 | elif platform == "visionossimulator": |
| 644 | sdk_name = "xrsimulator" |
| 645 | var_name = "APPLE_SDK_PATH" |
| 646 | |
| 647 | else: |
| 648 | raise Exception("Invalid platform argument passed to detect_darwin_sdk_path") |
| 649 | |
| 650 | if not env[var_name]: |
| 651 | try: |
| 652 | sdk_path = subprocess.check_output(["xcrun", "--sdk", sdk_name, "--show-sdk-path"]).strip().decode("utf-8") |
| 653 | if sdk_path: |
| 654 | env[var_name] = sdk_path |
| 655 | except (subprocess.CalledProcessError, OSError): |
| 656 | print_error(f"Failed to find SDK path while running 'xcrun --sdk {sdk_name} --show-sdk-path'.") |
| 657 | raise |
| 658 | |
| 659 | |
| 660 | def is_apple_clang(env): |
| 661 | import shlex |
| 662 | |
| 663 | if env["platform"] not in ["macos", "ios"]: |
| 664 | return False |
| 665 | if not using_clang(env): |
| 666 | return False |
| 667 | try: |
| 668 | version = ( |
| 669 | subprocess |
| 670 | .check_output(shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"]) |
| 671 | .strip() |
| 672 | .decode("utf-8") |
| 673 | ) |
| 674 | except (subprocess.CalledProcessError, OSError): |
| 675 | print_warning("Couldn't parse CXX environment variable to infer compiler version.") |
| 676 | return False |
| 677 | return version.startswith("Apple") |
| 678 | |
| 679 | |
| 680 | def get_compiler_version(env): |
| 681 | """ |
| 682 | Returns a dictionary with various version information: |
| 683 | |
| 684 | - major, minor, patch: Version following semantic versioning system |
| 685 | - metadata1, metadata2: Extra information |
| 686 | - date: Date of the build |
| 687 | """ |
| 688 | |
| 689 | global compiler_version_cache |
| 690 | if compiler_version_cache is not None: |
| 691 | return compiler_version_cache |
| 692 | |
| 693 | import shlex |
| 694 | |
| 695 | ret = { |
| 696 | "major": -1, |
| 697 | "minor": -1, |
| 698 | "patch": -1, |
| 699 | "metadata1": "", |
| 700 | "metadata2": "", |
| 701 | "date": "", |
| 702 | "apple_major": -1, |
| 703 | "apple_minor": -1, |
| 704 | "apple_patch1": -1, |
| 705 | "apple_patch2": -1, |
| 706 | "apple_patch3": -1, |
| 707 | } |
| 708 | |
| 709 | if env.msvc and not using_clang(env): |
| 710 | try: |
| 711 | # FIXME: `-latest` works for most cases, but there are edge-cases where this would |
| 712 | # benefit from a more nuanced search. |
| 713 | # https://github.com/godotengine/godot/pull/91069#issuecomment-2358956731 |
| 714 | # https://github.com/godotengine/godot/pull/91069#issuecomment-2380836341 |
| 715 | args = [ |
| 716 | env["VSWHERE"], |
| 717 | "-latest", |
| 718 | "-prerelease", |
| 719 | "-products", |
| 720 | "*", |
| 721 | "-utf8", |
| 722 | ] |
| 723 | version = subprocess.check_output(args, encoding="utf-8").strip() |
| 724 | for line in version.splitlines(): |
| 725 | split = line.split(":", 1) |
| 726 | if split[0] == "catalog_productSemanticVersion": |
| 727 | match = re.match(r" ([0-9]*).([0-9]*).([0-9]*)-?([a-z0-9.+]*)", split[1]) |
| 728 | if match is not None: |
| 729 | ret["major"] = int(match.group(1)) |
| 730 | ret["minor"] = int(match.group(2)) |
| 731 | ret["patch"] = int(match.group(3)) |
| 732 | # Semantic suffix (i.e. insiders+11116.177) |
| 733 | ret["metadata2"] = match.group(4) |
| 734 | # Could potentially add section for determining preview version, but |
| 735 | # that can wait until metadata is actually used for something. |
| 736 | if split[0] == "catalog_buildVersion": |
| 737 | ret["metadata1"] = split[1] |
| 738 | except (subprocess.CalledProcessError, OSError): |
| 739 | print_warning("Couldn't find vswhere to determine compiler version.") |
| 740 | return update_compiler_version_cache(ret) |
| 741 | |
| 742 | # Not using -dumpversion as some GCC distros only return major, and |
| 743 | # Clang used to return hardcoded 4.2.1: # https://reviews.llvm.org/D56803 |
| 744 | try: |
| 745 | version = subprocess.check_output( |
| 746 | shlex.split(env.subst(env["CXX"]), posix=False) + ["--version"], shell=(os.name == "nt"), encoding="utf-8" |
| 747 | ).strip() |
| 748 | except (subprocess.CalledProcessError, OSError): |
| 749 | print_warning("Couldn't parse CXX environment variable to infer compiler version.") |
| 750 | return update_compiler_version_cache(ret) |
| 751 | |
| 752 | match = re.search( |
| 753 | r"(?:(?<=version )|(?<=\) )|(?<=^))" |
| 754 | r"(?P<major>\d+)" |
| 755 | r"(?:\.(?P<minor>\d*))?" |
| 756 | r"(?:\.(?P<patch>\d*))?" |
| 757 | r"(?:-(?P<metadata1>[0-9a-zA-Z-]*))?" |
| 758 | r"(?:\+(?P<metadata2>[0-9a-zA-Z-]*))?" |
| 759 | r"(?: (?P<date>[0-9]{8}|[0-9]{6})(?![0-9a-zA-Z]))?", |
| 760 | version, |
| 761 | ) |
| 762 | if match is not None: |
| 763 | for key, value in match.groupdict().items(): |
| 764 | if value is not None: |
| 765 | ret[key] = value |
| 766 | |
| 767 | match_apple = re.search( |
| 768 | r"(?:(?<=clang-)|(?<=\) )|(?<=^))" |
| 769 | r"(?P<apple_major>\d+)" |
| 770 | r"(?:\.(?P<apple_minor>\d*))?" |
| 771 | r"(?:\.(?P<apple_patch1>\d*))?" |
| 772 | r"(?:\.(?P<apple_patch2>\d*))?" |
| 773 | r"(?:\.(?P<apple_patch3>\d*))?", |
| 774 | version, |
| 775 | ) |
| 776 | if match_apple is not None: |
| 777 | for key, value in match_apple.groupdict().items(): |
| 778 | if value is not None: |
| 779 | ret[key] = value |
| 780 | |
| 781 | # Transform semantic versioning to integers |
| 782 | for key in [ |
| 783 | "major", |
| 784 | "minor", |
| 785 | "patch", |
| 786 | "apple_major", |
| 787 | "apple_minor", |
| 788 | "apple_patch1", |
| 789 | "apple_patch2", |
| 790 | "apple_patch3", |
| 791 | ]: |
| 792 | ret[key] = int(ret[key] or -1) |
| 793 | return update_compiler_version_cache(ret) |
| 794 | |
| 795 | |
| 796 | def update_compiler_version_cache(value): |
| 797 | global compiler_version_cache |
| 798 | compiler_version_cache = value |
| 799 | return value |
| 800 | |
| 801 | |
| 802 | def using_gcc(env): |
| 803 | return "gcc" in os.path.basename(env["CC"]) |
| 804 | |
| 805 | |
| 806 | def using_clang(env): |
| 807 | return "clang" in os.path.basename(env["CC"]) |
| 808 | |
| 809 | |
| 810 | def using_emcc(env): |
| 811 | return "emcc" in os.path.basename(env["CC"]) |
| 812 | |
| 813 | |
| 814 | def show_progress(env): |
| 815 | # Ninja has its own progress/tracking tool that clashes with ours. |
| 816 | if env["ninja"]: |
| 817 | return |
| 818 | |
| 819 | NODE_COUNT_FILENAME = base_folder / ".scons_node_count" |
| 820 | |
| 821 | class ShowProgress: |
| 822 | def __init__(self): |
| 823 | self.count = 0 |
| 824 | self.max = 0 |
| 825 | try: |
| 826 | with open(NODE_COUNT_FILENAME, "r", encoding="utf-8") as f: |
| 827 | self.max = int(f.readline()) |
| 828 | except OSError: |
| 829 | pass |
| 830 | |
| 831 | # Progress reporting is not available in non-TTY environments since it |
| 832 | # messes with the output (for example, when writing to a file). |
| 833 | self.display = cast(bool, env["progress"] and sys.stdout.isatty()) |
| 834 | if self.display and not self.max: |
| 835 | print_info("Performing initial build, progress percentage unavailable!") |
| 836 | self.display = False |
| 837 | |
| 838 | def __call__(self, node, *args, **kw): |
| 839 | self.count += 1 |
| 840 | if self.display: |
| 841 | percent = int(min(self.count * 100 / self.max, 100)) |
| 842 | sys.stdout.write(f"\r[{percent:3d}%] ") |
| 843 | sys.stdout.flush() |
| 844 | |
| 845 | from SCons.Script import Progress |
| 846 | from SCons.Script.Main import GetBuildFailures |
| 847 | |
| 848 | progressor = ShowProgress() |
| 849 | Progress(progressor) |
| 850 | |
| 851 | def progress_finish(): |
| 852 | if GetBuildFailures() or not progressor.count: |
| 853 | return |
| 854 | try: |
| 855 | with open(NODE_COUNT_FILENAME, "w", encoding="utf-8", newline="\n") as f: |
| 856 | f.write(f"{progressor.count}\n") |
| 857 | except OSError: |
| 858 | pass |
| 859 | |
| 860 | atexit.register(progress_finish) |
| 861 | |
| 862 | |
| 863 | def convert_size(size_bytes: int) -> str: |
| 864 | if size_bytes == 0: |
| 865 | return "0 bytes" |
| 866 | SIZE_NAMES = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"] |
| 867 | index = math.floor(math.log(size_bytes, 1024)) |
| 868 | power = math.pow(1024, index) |
| 869 | size = round(size_bytes / power, 2) |
| 870 | return f"{size} {SIZE_NAMES[index]}" |
| 871 | |
| 872 | |
| 873 | def get_size(start_path: str = ".") -> int: |
| 874 | total_size = 0 |
| 875 | for dirpath, _, filenames in os.walk(start_path): |
| 876 | for file in filenames: |
| 877 | path = os.path.join(dirpath, file) |
| 878 | total_size += os.path.getsize(path) |
| 879 | return total_size |
| 880 | |
| 881 | |
| 882 | def clean_cache(cache_path: str, cache_limit: int, verbose: bool) -> None: |
| 883 | if not cache_limit: |
| 884 | return |
| 885 | |
| 886 | files = glob.glob(os.path.join(cache_path, "*", "*")) |
| 887 | if not files: |
| 888 | return |
| 889 | |
| 890 | # Store files in list of (filename, size, atime). |
| 891 | stats = [] |
| 892 | for file in files: |
| 893 | try: |
| 894 | stats.append((file, *os.stat(file)[6:8])) |
| 895 | except OSError: |
| 896 | print_error(f'Failed to access cache file "{file}"; skipping.') |
| 897 | |
| 898 | # Sort by most recent access (most sensible to keep) first. Search for the first entry where |
| 899 | # the cache limit is reached. |
| 900 | stats.sort(key=lambda x: x[2], reverse=True) |
| 901 | sum = 0 |
| 902 | for index, stat in enumerate(stats): |
| 903 | sum += stat[1] |
| 904 | if sum > cache_limit: |
| 905 | purge = [x[0] for x in stats[index:]] |
| 906 | count = len(purge) |
| 907 | for file in purge: |
| 908 | try: |
| 909 | os.remove(file) |
| 910 | except OSError: |
| 911 | print_error(f'Failed to remove cache file "{file}"; skipping.') |
| 912 | count -= 1 |
| 913 | if verbose and count: |
| 914 | print_info(f"Purged {count} file{'s' if count else ''} from cache.") |
| 915 | break |
| 916 | |
| 917 | |
| 918 | def prepare_cache(env) -> None: |
| 919 | cache_path = "" |
| 920 | if env["cache_path"]: |
| 921 | cache_path = cast(str, env["cache_path"]) |
| 922 | elif os.environ.get("SCONS_CACHE"): |
| 923 | print_warning("Environment variable `SCONS_CACHE` is deprecated; use `cache_path` argument instead.") |
| 924 | cache_path = cast(str, os.environ.get("SCONS_CACHE")) |
| 925 | |
| 926 | if not cache_path: |
| 927 | return |
| 928 | |
| 929 | env.CacheDir(cache_path) |
| 930 | print(f'SCons cache enabled... (path: "{cache_path}")') |
| 931 | |
| 932 | if env["cache_limit"]: |
| 933 | cache_limit = float(env["cache_limit"]) |
| 934 | elif os.environ.get("SCONS_CACHE_LIMIT"): |
| 935 | print_warning("Environment variable `SCONS_CACHE_LIMIT` is deprecated; use `cache_limit` argument instead.") |
| 936 | cache_limit = float(os.getenv("SCONS_CACHE_LIMIT", "0")) / 1024 # Old method used MiB, convert to GiB |
| 937 | |
| 938 | # Convert GiB to bytes; treat negative numbers as 0 (unlimited). |
| 939 | cache_limit = max(0, int(cache_limit * 1024 * 1024 * 1024)) |
| 940 | if env["verbose"]: |
| 941 | print_info( |
| 942 | f"Current cache size is {convert_size(get_size(cache_path))}" |
| 943 | + (f" (limit: {convert_size(cache_limit)})" if cache_limit else "") |
| 944 | ) |
| 945 | |
| 946 | atexit.register(clean_cache, cache_path, cache_limit, env["verbose"]) |
| 947 | |
| 948 | |
| 949 | def prepare_purge(env): |
| 950 | from SCons.Script.Main import GetBuildFailures |
| 951 | |
| 952 | def purge_flaky_files(): |
| 953 | paths_to_keep = [env["ninja_file"]] |
| 954 | for build_failure in GetBuildFailures(): |
| 955 | path = build_failure.node.path |
| 956 | if os.path.isfile(path) and path not in paths_to_keep: |
| 957 | os.remove(path) |
| 958 | |
| 959 | atexit.register(purge_flaky_files) |
| 960 | |
| 961 | |
| 962 | def prepare_timer(): |
| 963 | import time |
| 964 | |
| 965 | def print_elapsed_time(time_at_start: float): |
| 966 | time_elapsed = time.time() - time_at_start |
| 967 | time_formatted = time.strftime("%H:%M:%S", time.gmtime(time_elapsed)) |
| 968 | time_centiseconds = (time_elapsed % 1) * 100 |
| 969 | print_info(f"Time elapsed: {time_formatted}.{time_centiseconds:02.0f}") |
| 970 | |
| 971 | atexit.register(print_elapsed_time, time.time()) |
| 972 | |
| 973 | |
| 974 | def dump(env): |
| 975 | """ |
| 976 | Dumps latest build information for debugging purposes and external tools. |
| 977 | """ |
| 978 | |
| 979 | with open(".scons_env.json", "w", encoding="utf-8", newline="\n") as file: |
| 980 | file.write(env.Dump(format="json")) |
| 981 | |
| 982 | |
| 983 | # Custom Visual Studio project generation logic that supports any platform that has a msvs.py |
| 984 | # script, so Visual Studio can be used to run scons for any platform, with the right defines per target. |
| 985 | # Invoked with scons vsproj=yes |
| 986 | # |
| 987 | # Only platforms that opt in to vs proj generation by having a msvs.py file in the platform folder are included. |
| 988 | # Platforms with a msvs.py file will be added to the solution, but only the current active platform+target+arch |
| 989 | # will have a build configuration generated, because we only know what the right defines/includes/flags/etc are |
| 990 | # on the active build target. |
| 991 | # |
| 992 | # Platforms that don't support an editor target will have a dummy editor target that won't do anything on build, |
| 993 | # but will have the files and configuration for the windows editor target. |
| 994 | # |
| 995 | # To generate build configuration files for all platforms+targets+arch combinations, users can call |
| 996 | # scons vsproj=yes |
| 997 | # for each combination of platform+target+arch. This will generate the relevant vs project files but |
| 998 | # skip the build process. This lets project files be quickly generated even if there are build errors. |
| 999 | # |
| 1000 | # To generate AND build from the command line: |
| 1001 | # scons vsproj=yes vsproj_gen_only=no |
| 1002 | def generate_vs_project(env, original_args, project_name="godot"): |
| 1003 | # Augmented glob_recursive that also fills the dirs argument with traversed directories that have content. |
| 1004 | def glob_recursive_2(pattern, dirs, node="."): |
| 1005 | from SCons import Node |
| 1006 | from SCons.Script import Glob |
| 1007 | |
| 1008 | results = [] |
| 1009 | for f in Glob(str(node) + "/*", source=True): |
| 1010 | if type(f) is Node.FS.Dir: |
| 1011 | results += glob_recursive_2(pattern, dirs, f) |
| 1012 | r = Glob(str(node) + "/" + pattern, source=True) |
| 1013 | if len(r) > 0 and str(node) not in dirs: |
| 1014 | d = "" |
| 1015 | for part in str(node).split("\\"): |
| 1016 | d += part |
| 1017 | if d not in dirs: |
| 1018 | dirs.append(d) |
| 1019 | d += "\\" |
| 1020 | results += r |
| 1021 | return results |
| 1022 | |
| 1023 | def get_bool(args, option, default): |
| 1024 | from SCons.Variables.BoolVariable import _text2bool |
| 1025 | |
| 1026 | val = args.get(option, default) |
| 1027 | if val is not None: |
| 1028 | try: |
| 1029 | return _text2bool(val) |
| 1030 | except (ValueError, AttributeError): |
| 1031 | return default |
| 1032 | else: |
| 1033 | return default |
| 1034 | |
| 1035 | def format_key_value(v): |
| 1036 | if type(v) in [tuple, list]: |
| 1037 | return v[0] if len(v) == 1 else f"{v[0]}={v[1]}" |
| 1038 | return v |
| 1039 | |
| 1040 | def get_dependencies(file, env, exts, headers, sources, others): |
| 1041 | for child in file.children(): |
| 1042 | if isinstance(child, str): |
| 1043 | child = env.File(x) |
| 1044 | fname = "" |
| 1045 | try: |
| 1046 | fname = child.path |
| 1047 | except AttributeError: |
| 1048 | # It's not a file. |
| 1049 | pass |
| 1050 | |
| 1051 | if fname: |
| 1052 | parts = os.path.splitext(fname) |
| 1053 | if len(parts) > 1: |
| 1054 | ext = parts[1].lower() |
| 1055 | if ext in exts["sources"]: |
| 1056 | sources += [fname] |
| 1057 | elif ext in exts["headers"]: |
| 1058 | headers += [fname] |
| 1059 | elif ext in exts["others"]: |
| 1060 | others += [fname] |
| 1061 | |
| 1062 | get_dependencies(child, env, exts, headers, sources, others) |
| 1063 | |
| 1064 | filtered_args = original_args.copy() |
| 1065 | |
| 1066 | # Ignore the "vsproj" option to not regenerate the VS project on every build |
| 1067 | filtered_args.pop("vsproj", None) |
| 1068 | |
| 1069 | # This flag allows users to regenerate the proj files but skip the building process. |
| 1070 | # This lets projects be regenerated even if there are build errors. |
| 1071 | filtered_args.pop("vsproj_gen_only", None) |
| 1072 | |
| 1073 | # This flag allows users to regenerate only the props file without touching the sln or vcxproj files. |
| 1074 | # This preserves any customizations users have done to the solution, while still updating the file list |
| 1075 | # and build commands. |
| 1076 | filtered_args.pop("vsproj_props_only", None) |
| 1077 | |
| 1078 | # The "progress" option is ignored as the current compilation progress indication doesn't work in VS |
| 1079 | filtered_args.pop("progress", None) |
| 1080 | |
| 1081 | # We add these three manually because they might not be explicitly passed in, and it's important to always set them. |
| 1082 | filtered_args.pop("platform", None) |
| 1083 | filtered_args.pop("target", None) |
| 1084 | filtered_args.pop("arch", None) |
| 1085 | |
| 1086 | platform = env["platform"] |
| 1087 | target = env["target"] |
| 1088 | arch = env["arch"] |
| 1089 | host_arch = detect_arch() |
| 1090 | |
| 1091 | host_platform = "windows" |
| 1092 | if ( |
| 1093 | sys.platform.startswith("linux") |
| 1094 | or sys.platform.startswith("dragonfly") |
| 1095 | or sys.platform.startswith("freebsd") |
| 1096 | or sys.platform.startswith("netbsd") |
| 1097 | or sys.platform.startswith("openbsd") |
| 1098 | ): |
| 1099 | host_platform = "linuxbsd" |
| 1100 | elif sys.platform == "darwin": |
| 1101 | host_platform = "macos" |
| 1102 | |
| 1103 | vs_configuration = {} |
| 1104 | host_vs_configuration = {} |
| 1105 | common_build_prefix = [] |
| 1106 | confs = [] |
| 1107 | for x in sorted(glob.glob("platform/*")): |
| 1108 | # Only platforms that opt in to vs proj generation are included. |
| 1109 | if not os.path.isdir(x) or not os.path.exists(x + "/msvs.py"): |
| 1110 | continue |
| 1111 | tmppath = "./" + x |
| 1112 | sys.path.insert(0, tmppath) |
| 1113 | import msvs |
| 1114 | |
| 1115 | vs_plats = [] |
| 1116 | vs_confs = [] |
| 1117 | try: |
| 1118 | platform_name = x[9:] |
| 1119 | vs_plats = msvs.get_platforms() |
| 1120 | vs_confs = msvs.get_configurations() |
| 1121 | val = [] |
| 1122 | for plat in vs_plats: |
| 1123 | val += [{"platform": plat[0], "architecture": plat[1]}] |
| 1124 | |
| 1125 | vsconf = {"platform": platform_name, "targets": vs_confs, "arches": val} |
| 1126 | confs += [vsconf] |
| 1127 | |
| 1128 | # Save additional information about the configuration for the actively selected platform, |
| 1129 | # so we can generate the platform-specific props file with all the build commands/defines/etc |
| 1130 | if platform == platform_name: |
| 1131 | common_build_prefix = msvs.get_build_prefix(env) |
| 1132 | vs_configuration = vsconf |
| 1133 | if platform_name == host_platform: |
| 1134 | host_vs_configuration = vsconf |
| 1135 | for a in vsconf["arches"]: |
| 1136 | if host_arch == a["architecture"]: |
| 1137 | host_arch = a["platform"] |
| 1138 | break |
| 1139 | except Exception: |
| 1140 | pass |
| 1141 | |
| 1142 | sys.path.remove(tmppath) |
| 1143 | sys.modules.pop("msvs") |
| 1144 | |
| 1145 | extensions = {} |
| 1146 | extensions["headers"] = [".h", ".hh", ".hpp", ".hxx", ".inc", ".inl"] |
| 1147 | extensions["sources"] = [".c", ".cc", ".cpp", ".cxx", ".m", ".mm", ".java"] |
| 1148 | extensions["others"] = [".natvis", ".glsl", ".rc"] |
| 1149 | |
| 1150 | headers = [] |
| 1151 | headers_dirs = [] |
| 1152 | for ext in extensions["headers"]: |
| 1153 | for file in glob_recursive_2("*" + ext, headers_dirs): |
| 1154 | headers.append(str(file).replace("/", "\\")) |
| 1155 | |
| 1156 | sources = [] |
| 1157 | sources_dirs = [] |
| 1158 | for ext in extensions["sources"]: |
| 1159 | for file in glob_recursive_2("*" + ext, sources_dirs): |
| 1160 | sources.append(str(file).replace("/", "\\")) |
| 1161 | |
| 1162 | others = [] |
| 1163 | others_dirs = [] |
| 1164 | for ext in extensions["others"]: |
| 1165 | for file in glob_recursive_2("*" + ext, others_dirs): |
| 1166 | others.append(str(file).replace("/", "\\")) |
| 1167 | |
| 1168 | skip_filters = False |
| 1169 | import hashlib |
| 1170 | import json |
| 1171 | |
| 1172 | md5 = hashlib.md5( |
| 1173 | json.dumps(sorted(headers + headers_dirs + sources + sources_dirs + others + others_dirs)).encode("utf-8") |
| 1174 | ).hexdigest() |
| 1175 | |
| 1176 | if os.path.exists(f"{project_name}.vcxproj.filters"): |
| 1177 | with open(f"{project_name}.vcxproj.filters", "r", encoding="utf-8") as file: |
| 1178 | existing_filters = file.read() |
| 1179 | match = re.search(r"(?ms)^<!-- CHECKSUM$.([0-9a-f]{32})", existing_filters) |
| 1180 | if match is not None and md5 == match.group(1): |
| 1181 | skip_filters = True |
| 1182 | |
| 1183 | import uuid |
| 1184 | |
| 1185 | # Don't regenerate the filters file if nothing has changed, so we keep the existing UUIDs. |
| 1186 | if not skip_filters: |
| 1187 | print(f"Regenerating {project_name}.vcxproj.filters") |
| 1188 | |
| 1189 | with open("misc/msvs/vcxproj.filters.template", "r", encoding="utf-8") as file: |
| 1190 | filters_template = file.read() |
| 1191 | for i in range(1, 10): |
| 1192 | filters_template = filters_template.replace(f"%%UUID{i}%%", str(uuid.uuid4())) |
| 1193 | |
| 1194 | filters = "" |
| 1195 | |
| 1196 | for d in headers_dirs: |
| 1197 | filters += f'<Filter Include="Header Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1198 | for d in sources_dirs: |
| 1199 | filters += f'<Filter Include="Source Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1200 | for d in others_dirs: |
| 1201 | filters += f'<Filter Include="Other Files\\{d}"><UniqueIdentifier>{{{str(uuid.uuid4())}}}</UniqueIdentifier></Filter>\n' |
| 1202 | |
| 1203 | filters_template = filters_template.replace("%%FILTERS%%", filters) |
| 1204 | |
| 1205 | filters = "" |
| 1206 | for file in headers: |
| 1207 | filters += ( |
| 1208 | f'<ClInclude Include="{file}"><Filter>Header Files\\{os.path.dirname(file)}</Filter></ClInclude>\n' |
| 1209 | ) |
| 1210 | filters_template = filters_template.replace("%%INCLUDES%%", filters) |
| 1211 | |
| 1212 | filters = "" |
| 1213 | for file in sources: |
| 1214 | filters += ( |
| 1215 | f'<ClCompile Include="{file}"><Filter>Source Files\\{os.path.dirname(file)}</Filter></ClCompile>\n' |
| 1216 | ) |
| 1217 | |
| 1218 | filters_template = filters_template.replace("%%COMPILES%%", filters) |
| 1219 | |
| 1220 | filters = "" |
| 1221 | for file in others: |
| 1222 | filters += f'<None Include="{file}"><Filter>Other Files\\{os.path.dirname(file)}</Filter></None>\n' |
| 1223 | filters_template = filters_template.replace("%%OTHERS%%", filters) |
| 1224 | |
| 1225 | filters_template = filters_template.replace("%%HASH%%", md5) |
| 1226 | |
| 1227 | with open(f"{project_name}.vcxproj.filters", "w", encoding="utf-8", newline="\r\n") as f: |
| 1228 | f.write(filters_template) |
| 1229 | |
| 1230 | headers_active = [] |
| 1231 | sources_active = [] |
| 1232 | others_active = [] |
| 1233 | |
| 1234 | get_dependencies( |
| 1235 | env.File(f"#bin/godot{env['PROGSUFFIX']}"), env, extensions, headers_active, sources_active, others_active |
| 1236 | ) |
| 1237 | |
| 1238 | all_items = [] |
| 1239 | properties = [] |
| 1240 | activeItems = [] |
| 1241 | extraItems = [] |
| 1242 | |
| 1243 | set_headers = set(headers_active) |
| 1244 | set_sources = set(sources_active) |
| 1245 | set_others = set(others_active) |
| 1246 | for file in headers: |
| 1247 | base_path = os.path.dirname(file).replace("\\", "_") |
| 1248 | all_items.append(f'<ClInclude Include="{file}">') |
| 1249 | all_items.append( |
| 1250 | f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1251 | ) |
| 1252 | all_items.append("</ClInclude>") |
| 1253 | if file in set_headers: |
| 1254 | activeItems.append(file) |
| 1255 | |
| 1256 | for file in sources: |
| 1257 | base_path = os.path.dirname(file).replace("\\", "_") |
| 1258 | all_items.append(f'<ClCompile Include="{file}">') |
| 1259 | all_items.append( |
| 1260 | f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1261 | ) |
| 1262 | all_items.append("</ClCompile>") |
| 1263 | if file in set_sources: |
| 1264 | activeItems.append(file) |
| 1265 | |
| 1266 | for file in others: |
| 1267 | base_path = os.path.dirname(file).replace("\\", "_") |
| 1268 | all_items.append(f'<None Include="{file}">') |
| 1269 | all_items.append( |
| 1270 | f" <ExcludedFromBuild Condition=\"!$(ActiveProjectItemList_{base_path}.Contains(';{file};'))\">true</ExcludedFromBuild>" |
| 1271 | ) |
| 1272 | all_items.append("</None>") |
| 1273 | if file in set_others: |
| 1274 | activeItems.append(file) |
| 1275 | |
| 1276 | if vs_configuration: |
| 1277 | vsconf = "" |
| 1278 | for a in vs_configuration["arches"]: |
| 1279 | if arch == a["architecture"]: |
| 1280 | vsconf = f"{target}|{a['platform']}" |
| 1281 | break |
| 1282 | |
| 1283 | condition = "'$(GodotConfiguration)|$(GodotPlatform)'=='" + vsconf + "'" |
| 1284 | itemlist = {} |
| 1285 | for item in activeItems: |
| 1286 | key = os.path.dirname(item).replace("\\", "_") |
| 1287 | if key not in itemlist: |
| 1288 | itemlist[key] = [item] |
| 1289 | else: |
| 1290 | itemlist[key] += [item] |
| 1291 | |
| 1292 | for x in itemlist.keys(): |
| 1293 | properties.append(f"<ActiveProjectItemList_{x}>;{';'.join(itemlist[x])};</ActiveProjectItemList_{x}>") |
| 1294 | output = os.path.join("bin", f"godot{env['PROGSUFFIX']}") |
| 1295 | |
| 1296 | # The modules_enabled.gen.h header containing the defines is only generated on build, and only for the most recently built |
| 1297 | # platform, which means VS can't properly render code that's inside module-specific ifdefs. This adds those defines to the |
| 1298 | # platform-specific VS props file, so that VS knows which defines are enabled for the selected platform. |
| 1299 | env.Append(VSHINT_DEFINES=[f"MODULE_{module.upper()}_ENABLED" for module in env.module_list]) |
| 1300 | |
| 1301 | with open("misc/msvs/props.template", "r", encoding="utf-8") as file: |
| 1302 | props_template = file.read() |
| 1303 | |
| 1304 | props_template = props_template.replace("%%CONDITION%%", condition) |
| 1305 | props_template = props_template.replace("%%PROPERTIES%%", "\n ".join(properties)) |
| 1306 | props_template = props_template.replace("%%EXTRA_ITEMS%%", "\n ".join(extraItems)) |
| 1307 | |
| 1308 | props_template = props_template.replace("%%OUTPUT%%", output) |
| 1309 | |
| 1310 | proplist = [format_key_value(j) for j in list(env["CPPDEFINES"])] |
| 1311 | proplist += [format_key_value(j) for j in env.get("VSHINT_DEFINES", [])] |
| 1312 | props_template = props_template.replace("%%DEFINES%%", ";".join(proplist)) |
| 1313 | |
| 1314 | proplist = [str(j) for j in env["CPPPATH"]] |
| 1315 | proplist += [str(j) for j in env.get("VSHINT_INCLUDES", [])] |
| 1316 | proplist += [str(j) for j in get_default_include_paths(env)] |
| 1317 | props_template = props_template.replace("%%INCLUDES%%", ";".join(proplist)) |
| 1318 | |
| 1319 | proplist = [env.subst("$CCFLAGS")] |
| 1320 | proplist += [env.subst("$CXXFLAGS")] |
| 1321 | proplist += [env.subst("$VSHINT_OPTIONS")] |
| 1322 | props_template = props_template.replace("%%OPTIONS%%", " ".join(proplist)) |
| 1323 | |
| 1324 | # Windows allows us to have spaces in paths, so we need |
| 1325 | # to double quote off the directory. However, the path ends |
| 1326 | # in a backslash, so we need to remove this, lest it escape the |
| 1327 | # last double quote off, confusing MSBuild |
| 1328 | common_build_postfix = [ |
| 1329 | "--directory="$(ProjectDir.TrimEnd('\\'))"", |
| 1330 | "progress=no", |
| 1331 | f"platform={platform}", |
| 1332 | f"target={target}", |
| 1333 | f"arch={arch}", |
| 1334 | ] |
| 1335 | |
| 1336 | for arg, value in filtered_args.items(): |
| 1337 | common_build_postfix.append(f"{arg}={value}") |
| 1338 | |
| 1339 | cmd_rebuild = [ |
| 1340 | "vsproj=yes", |
| 1341 | "vsproj_props_only=yes", |
| 1342 | "vsproj_gen_only=no", |
| 1343 | f"vsproj_name={project_name}", |
| 1344 | ] + common_build_postfix |
| 1345 | |
| 1346 | cmd_clean = [ |
| 1347 | "--clean", |
| 1348 | ] + common_build_postfix |
| 1349 | |
| 1350 | commands = "scons" |
| 1351 | if len(common_build_prefix) == 0: |
| 1352 | commands = "echo Starting SCons & " + commands |
| 1353 | else: |
| 1354 | common_build_prefix[0] = "echo Starting SCons & " + common_build_prefix[0] |
| 1355 | |
| 1356 | cmd = " ".join(common_build_prefix + [" ".join([commands] + common_build_postfix)]) |
| 1357 | props_template = props_template.replace("%%BUILD%%", cmd) |
| 1358 | |
| 1359 | cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_rebuild)]) |
| 1360 | props_template = props_template.replace("%%REBUILD%%", cmd) |
| 1361 | |
| 1362 | cmd = " ".join(common_build_prefix + [" ".join([commands] + cmd_clean)]) |
| 1363 | props_template = props_template.replace("%%CLEAN%%", cmd) |
| 1364 | |
| 1365 | with open( |
| 1366 | f"{project_name}.{platform}.{target}.{arch}.generated.props", "w", encoding="utf-8", newline="\r\n" |
| 1367 | ) as f: |
| 1368 | f.write(props_template) |
| 1369 | |
| 1370 | proj_uuid = str(uuid.uuid4()) |
| 1371 | sln_uuid = str(uuid.uuid4()) |
| 1372 | |
| 1373 | if os.path.exists(f"{project_name}.sln"): |
| 1374 | for line in open(f"{project_name}.sln", "r", encoding="utf-8").read().splitlines(): |
| 1375 | if line.startswith('Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}")'): |
| 1376 | proj_uuid = re.search( |
| 1377 | r"\"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}\"$", |
| 1378 | line, |
| 1379 | ).group(1) |
| 1380 | elif line.strip().startswith("SolutionGuid ="): |
| 1381 | sln_uuid = re.search( |
| 1382 | r"{(\b[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-\b[0-9a-fA-F]{12}\b)}", line |
| 1383 | ).group(1) |
| 1384 | break |
| 1385 | |
| 1386 | configurations = [] |
| 1387 | imports = [] |
| 1388 | properties = [] |
| 1389 | section1 = [] |
| 1390 | section2 = [] |
| 1391 | for conf in confs: |
| 1392 | godot_platform = conf["platform"] |
| 1393 | has_editor = "editor" in conf["targets"] |
| 1394 | |
| 1395 | # Skip any platforms that can build the editor and don't match the host platform. |
| 1396 | # |
| 1397 | # When both Windows and Mac define an editor target, it's defined as platform+target+arch (windows+editor+x64 for example). |
| 1398 | # VS only supports two attributes, a "Configuration" and a "Platform", and we currently map our target to the Configuration |
| 1399 | # (i.e. editor/template_debug/template_release), and our architecture to the "Platform" (i.e. x64, arm64, etc). |
| 1400 | # Those two are not enough to disambiguate multiple godot targets for different godot platforms with the same architecture, |
| 1401 | # i.e. editor|x64 would currently match both windows editor intel 64 and linux editor intel 64. |
| 1402 | # |
| 1403 | # TODO: More work is needed in order to support generating VS projects that unambiguously support all platform+target+arch variations. |
| 1404 | # The VS "Platform" has to be a known architecture that VS recognizes, so we can only play around with the "Configuration" part of the combo. |
| 1405 | if has_editor and godot_platform != host_vs_configuration["platform"]: |
| 1406 | continue |
| 1407 | |
| 1408 | for p in conf["arches"]: |
| 1409 | sln_plat = p["platform"] |
| 1410 | proj_plat = sln_plat |
| 1411 | godot_arch = p["architecture"] |
| 1412 | |
| 1413 | # Redirect editor configurations for platforms that don't support the editor target to the default editor target on the |
| 1414 | # active host platform, so the solution has all the permutations and VS doesn't complain about missing project configurations. |
| 1415 | # These configurations are disabled, so they show up but won't build. |
| 1416 | if not has_editor: |
| 1417 | section1 += [f"editor|{sln_plat} = editor|{proj_plat}"] |
| 1418 | section2 += [f"{{{proj_uuid}}}.editor|{proj_plat}.ActiveCfg = editor|{host_arch}"] |
| 1419 | |
| 1420 | configurations += [ |
| 1421 | f'<ProjectConfiguration Include="editor|{proj_plat}">', |
| 1422 | " <Configuration>editor</Configuration>", |
| 1423 | f" <Platform>{proj_plat}</Platform>", |
| 1424 | "</ProjectConfiguration>", |
| 1425 | ] |
| 1426 | |
| 1427 | properties += [ |
| 1428 | f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='editor|{proj_plat}'\">", |
| 1429 | " <GodotConfiguration>editor</GodotConfiguration>", |
| 1430 | f" <GodotPlatform>{proj_plat}</GodotPlatform>", |
| 1431 | "</PropertyGroup>", |
| 1432 | ] |
| 1433 | |
| 1434 | for t in conf["targets"]: |
| 1435 | godot_target = t |
| 1436 | |
| 1437 | # Windows x86 is a special little flower that requires a project platform == Win32 but a solution platform == x86. |
| 1438 | if godot_platform == "windows" and godot_target == "editor" and godot_arch == "x86_32": |
| 1439 | sln_plat = "x86" |
| 1440 | |
| 1441 | configurations += [ |
| 1442 | f'<ProjectConfiguration Include="{godot_target}|{proj_plat}">', |
| 1443 | f" <Configuration>{godot_target}</Configuration>", |
| 1444 | f" <Platform>{proj_plat}</Platform>", |
| 1445 | "</ProjectConfiguration>", |
| 1446 | ] |
| 1447 | |
| 1448 | properties += [ |
| 1449 | f"<PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='{godot_target}|{proj_plat}'\">", |
| 1450 | f" <GodotConfiguration>{godot_target}</GodotConfiguration>", |
| 1451 | f" <GodotPlatform>{proj_plat}</GodotPlatform>", |
| 1452 | "</PropertyGroup>", |
| 1453 | ] |
| 1454 | |
| 1455 | p = f"{project_name}.{godot_platform}.{godot_target}.{godot_arch}.generated.props" |
| 1456 | imports += [ |
| 1457 | f'<Import Project="$(MSBuildProjectDirectory)\\{p}" Condition="Exists(\'$(MSBuildProjectDirectory)\\{p}\')"/>' |
| 1458 | ] |
| 1459 | |
| 1460 | section1 += [f"{godot_target}|{sln_plat} = {godot_target}|{sln_plat}"] |
| 1461 | |
| 1462 | section2 += [ |
| 1463 | f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.ActiveCfg = {godot_target}|{proj_plat}", |
| 1464 | f"{{{proj_uuid}}}.{godot_target}|{sln_plat}.Build.0 = {godot_target}|{proj_plat}", |
| 1465 | ] |
| 1466 | |
| 1467 | # Add an extra import for a local user props file at the end, so users can add more overrides. |
| 1468 | imports += [ |
| 1469 | f'<Import Project="$(MSBuildProjectDirectory)\\{project_name}.vs.user.props" Condition="Exists(\'$(MSBuildProjectDirectory)\\{project_name}.vs.user.props\')"/>' |
| 1470 | ] |
| 1471 | section1 = sorted(section1) |
| 1472 | section2 = sorted(section2) |
| 1473 | |
| 1474 | if not get_bool(original_args, "vsproj_props_only", False): |
| 1475 | with open("misc/msvs/vcxproj.template", "r", encoding="utf-8") as file: |
| 1476 | proj_template = file.read() |
| 1477 | proj_template = proj_template.replace("%%UUID%%", proj_uuid) |
| 1478 | proj_template = proj_template.replace("%%CONFS%%", "\n ".join(configurations)) |
| 1479 | proj_template = proj_template.replace("%%IMPORTS%%", "\n ".join(imports)) |
| 1480 | proj_template = proj_template.replace("%%DEFAULT_ITEMS%%", "\n ".join(all_items)) |
| 1481 | proj_template = proj_template.replace("%%PROPERTIES%%", "\n ".join(properties)) |
| 1482 | |
| 1483 | with open(f"{project_name}.vcxproj", "w", encoding="utf-8", newline="\r\n") as f: |
| 1484 | f.write(proj_template) |
| 1485 | |
| 1486 | if not get_bool(original_args, "vsproj_props_only", False): |
| 1487 | with open("misc/msvs/sln.template", "r", encoding="utf-8") as file: |
| 1488 | sln_template = file.read() |
| 1489 | sln_template = sln_template.replace("%%NAME%%", project_name) |
| 1490 | sln_template = sln_template.replace("%%UUID%%", proj_uuid) |
| 1491 | sln_template = sln_template.replace("%%SLNUUID%%", sln_uuid) |
| 1492 | sln_template = sln_template.replace("%%SECTION1%%", "\n\t\t".join(section1)) |
| 1493 | sln_template = sln_template.replace("%%SECTION2%%", "\n\t\t".join(section2)) |
| 1494 | |
| 1495 | with open(f"{project_name}.sln", "w", encoding="utf-8", newline="\r\n") as f: |
| 1496 | f.write(sln_template) |
| 1497 | |
| 1498 | if get_bool(original_args, "vsproj_gen_only", True): |
| 1499 | sys.exit() |
| 1500 | |
| 1501 | |
| 1502 | ############################################################ |
| 1503 | # FILE GENERATION & FORMATTING |
| 1504 | ############################################################ |
| 1505 | |
| 1506 | |
| 1507 | def generate_copyright_header(filename: str) -> str: |
| 1508 | MARGIN = 70 |
| 1509 | TEMPLATE = """\ |
| 1510 | /**************************************************************************/ |
| 1511 | /* %s*/ |
| 1512 | /**************************************************************************/ |
| 1513 | /* This file is part of: */ |
| 1514 | /* GODOT ENGINE */ |
| 1515 | /* https://godotengine.org */ |
| 1516 | /**************************************************************************/ |
| 1517 | /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ |
| 1518 | /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ |
| 1519 | /* */ |
| 1520 | /* Permission is hereby granted, free of charge, to any person obtaining */ |
| 1521 | /* a copy of this software and associated documentation files (the */ |
| 1522 | /* "Software"), to deal in the Software without restriction, including */ |
| 1523 | /* without limitation the rights to use, copy, modify, merge, publish, */ |
| 1524 | /* distribute, sublicense, and/or sell copies of the Software, and to */ |
| 1525 | /* permit persons to whom the Software is furnished to do so, subject to */ |
| 1526 | /* the following conditions: */ |
| 1527 | /* */ |
| 1528 | /* The above copyright notice and this permission notice shall be */ |
| 1529 | /* included in all copies or substantial portions of the Software. */ |
| 1530 | /* */ |
| 1531 | /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ |
| 1532 | /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ |
| 1533 | /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ |
| 1534 | /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ |
| 1535 | /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ |
| 1536 | /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ |
| 1537 | /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ |
| 1538 | /**************************************************************************/ |
| 1539 | """ |
| 1540 | if len(filename := os.path.basename(filename).ljust(MARGIN)) > MARGIN: |
| 1541 | print_warning(f'Filename "{filename}" too large for copyright header.') |
| 1542 | return TEMPLATE % filename |
| 1543 | |
| 1544 | |
| 1545 | @contextlib.contextmanager |
| 1546 | def generated_wrapper( |
| 1547 | path: str, |
| 1548 | guard: bool | None = None, |
| 1549 | ) -> Generator[TextIO, None, None]: |
| 1550 | """ |
| 1551 | Wrapper class to automatically handle copyright headers and header guards |
| 1552 | for generated scripts. Meant to be invoked via `with` statement similar to |
| 1553 | creating a file. |
| 1554 | |
| 1555 | - `path`: The path of the file to be created. |
| 1556 | - `guard`: Optional bool to determine if `#pragma once` should be added. If |
| 1557 | unassigned, the value is determined by file extension. |
| 1558 | """ |
| 1559 | |
| 1560 | with open(path, "wt", encoding="utf-8", newline="\n") as file: |
| 1561 | if not path.endswith(".out"): # For test output, we only care about the content. |
| 1562 | file.write(generate_copyright_header(path)) |
| 1563 | file.write("\n/* THIS FILE IS GENERATED. EDITS WILL BE LOST. */\n\n") |
| 1564 | |
| 1565 | if guard is None: |
| 1566 | guard = path.endswith((".h", ".hh", ".hpp", ".hxx", ".inc")) |
| 1567 | if guard: |
| 1568 | file.write("#pragma once\n\n") |
| 1569 | |
| 1570 | with StringIO(newline="\n") as str_io: |
| 1571 | yield str_io |
| 1572 | file.write(str_io.getvalue().strip() or "/* NO CONTENT */") |
| 1573 | |
| 1574 | file.write("\n") |
| 1575 | |
| 1576 | |
| 1577 | def get_buffer(path: str) -> bytes: |
| 1578 | with open(path, "rb") as file: |
| 1579 | return file.read() |
| 1580 | |
| 1581 | |
| 1582 | def compress_buffer_zstd(buffer: bytes, env): |
| 1583 | # Levels selected for a good tradeoff between compression speed and size reduction, |
| 1584 | # being more aggressive on production builds. |
| 1585 | # Long-distance matching helps a lot with the editor translations on lower levels, |
| 1586 | # but costs some extra decompression time (+30%). It's not helping at high levels. |
| 1587 | level = 20 if env["production"] else 7 |
| 1588 | ldm = False if env["production"] or env.dev_build else True |
| 1589 | has_compression_zstd = True |
| 1590 | try: |
| 1591 | import compression.zstd |
| 1592 | except ImportError: |
| 1593 | has_compression_zstd = False |
| 1594 | if has_compression_zstd: |
| 1595 | CP = compression.zstd.CompressionParameter |
| 1596 | options = {CP.compression_level: level, CP.enable_long_distance_matching: ldm} |
| 1597 | return compression.zstd.compress(buffer, options=options) |
| 1598 | else: |
| 1599 | try: |
| 1600 | import zstandard |
| 1601 | except ImportError: |
| 1602 | print_error( |
| 1603 | "The Python `zstandard` module is needed. You can install it through your Python package manager." |
| 1604 | ) |
| 1605 | sys.exit(255) |
| 1606 | params = zstandard.ZstdCompressionParameters.from_level(level, enable_ldm=ldm) |
| 1607 | return zstandard.ZstdCompressor(compression_params=params).compress(buffer) |
| 1608 | |
| 1609 | |
| 1610 | def compress_buffer(buffer: bytes) -> bytes: |
| 1611 | # Use maximum zlib compression level to further reduce file size |
| 1612 | # (at the cost of initial build times). |
| 1613 | return zlib.compress(buffer, zlib.Z_BEST_COMPRESSION) |
| 1614 | |
| 1615 | |
| 1616 | def format_buffer(buffer: bytes, indent: int = 0, width: int = 120) -> str: |
| 1617 | return re.sub( |
| 1618 | f"(.{{{width - (indent * 4) - 6}}},) (?:, )?", |
| 1619 | r"\g<1>\n" + ("\t" * indent), |
| 1620 | ", ".join(map(str, buffer)), |
| 1621 | ) |
| 1622 | |
| 1623 | |
| 1624 | ############################################################ |
| 1625 | # CSTRING PARSING |
| 1626 | ############################################################ |
| 1627 | |
| 1628 | C_ESCAPABLES = [ |
| 1629 | ("\\", "\\\\"), |
| 1630 | ("\a", "\\a"), |
| 1631 | ("\b", "\\b"), |
| 1632 | ("\f", "\\f"), |
| 1633 | ("\n", "\\n"), |
| 1634 | ("\r", "\\r"), |
| 1635 | ("\t", "\\t"), |
| 1636 | ("\v", "\\v"), |
| 1637 | # ("'", "\\'"), # Skip, as we're only dealing with full strings. |
| 1638 | ('"', '\\"'), |
| 1639 | ] |
| 1640 | C_ESCAPE_TABLE = str.maketrans(dict((x, y) for x, y in C_ESCAPABLES)) |
| 1641 | |
| 1642 | |
| 1643 | def to_escaped_cstring(value: str) -> str: |
| 1644 | return value.translate(C_ESCAPE_TABLE) |
| 1645 | |
| 1646 | |
| 1647 | def to_raw_cstring(value: str | list[str]) -> str: |
| 1648 | MAX_LITERAL = 16 * 1024 |
| 1649 | |
| 1650 | if isinstance(value, list): |
| 1651 | value = "\n".join(value) + "\n" |
| 1652 | |
| 1653 | split: list[bytes] = [] |
| 1654 | offset = 0 |
| 1655 | encoded = value.encode() |
| 1656 | |
| 1657 | while offset <= len(encoded): |
| 1658 | segment = encoded[offset : offset + MAX_LITERAL] |
| 1659 | offset += MAX_LITERAL |
| 1660 | if len(segment) == MAX_LITERAL: |
| 1661 | # Try to segment raw strings at double newlines to keep readable. |
| 1662 | pretty_break = segment.rfind(b"\n\n") |
| 1663 | if pretty_break != -1: |
| 1664 | segment = segment[: pretty_break + 1] |
| 1665 | offset -= MAX_LITERAL - pretty_break - 1 |
| 1666 | # If none found, ensure we end with valid utf8. |
| 1667 | # https://github.com/halloleo/unicut/blob/master/truncate.py |
| 1668 | elif segment[-1] & 0b10000000: |
| 1669 | last_11xxxxxx_index = [i for i in range(-1, -5, -1) if segment[i] & 0b11000000 == 0b11000000][0] |
| 1670 | last_11xxxxxx = segment[last_11xxxxxx_index] |
| 1671 | if not last_11xxxxxx & 0b00100000: |
| 1672 | last_char_length = 2 |
| 1673 | elif not last_11xxxxxx & 0b0010000: |
| 1674 | last_char_length = 3 |
| 1675 | elif not last_11xxxxxx & 0b0001000: |
| 1676 | last_char_length = 4 |
| 1677 | |
| 1678 | if last_char_length > -last_11xxxxxx_index: |
| 1679 | segment = segment[:last_11xxxxxx_index] |
| 1680 | offset += last_11xxxxxx_index |
| 1681 | |
| 1682 | split += [segment] |
| 1683 | |
| 1684 | if len(split) == 1: |
| 1685 | return f'R"<!>({split[0].decode()})<!>"' |
| 1686 | else: |
| 1687 | # Wrap multiple segments in parenthesis to suppress `string-concatenation` warnings on clang. |
| 1688 | return "({})".format(" ".join(f'R"<!>({segment.decode()})<!>"' for segment in split)) |
| 1689 | |
| 1690 | |
| 1691 | def get_default_include_paths(env): |
| 1692 | if env.msvc: |
| 1693 | return [] |
| 1694 | compiler = env.subst("$CXX") |
| 1695 | target = os.path.join(env.Dir("#main").abspath, "main.cpp") |
| 1696 | args = [compiler, target, "-x", "c++", "-v"] |
| 1697 | ret = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| 1698 | output = ret.stdout |
| 1699 | match = re.search(r"#include <\.\.\.> search starts here:([\S\s]*)End of search list.", output) |
| 1700 | if not match: |
| 1701 | print_warning("Failed to find the include paths in the compiler output.") |
| 1702 | return [] |
| 1703 | return [x.strip() for x in match[1].strip().splitlines()] |