Введение в систему сборки

SCоns

Godot использует SCons для сборки. Мы любим его, и мы не намерены изменять его на что-то другое. Мы даже не уверены что другие системы сборки вообще могут осуществить задачу по сборке Godot. Мы постоянно получаем запросы на изменение системы сборки на CMake, или Visual Studio, но это не произойдёт. Существуют много причин по которым мы выбрали SCons из всех возможных например:

  • Godot can be compiled for a dozen different platforms: all PC platforms, all mobile platforms, many consoles, and WebAssembly.

  • Разработчикам часто нужно компилировать для множества платформ в одно и то же время, или даже разных целей на одной платформе. Они не хотят перенастраивать и перестраивать проект каждый раз. SCons позволяет сделать это без лишней головной боли, без ломания сборок.

  • SCons никогда не сломает сборку вне зависимости от количества изменений, конфигураций, дополнений, удалений итд. Вы имеете больше шансов умереть от попадания молнии чем нужды в очистке и перестройке SCons.

  • Процесс сборки Godot не прост. Множество файлов созданы в коде(связующие(binders)), другие прошли через парсинг (шейдеры), а другие нуждаются в тонкой настройке (плагины). Всё это требует сложной логики которая может бы легко написана на подходящем языке программирования (например Python) чем использовать язык с макросами нужным только для сборки.

  • Godot build process makes heavy use of cross-compiling tools. Each platform has a specific detection process, and all these must be handled as specific cases with special code written for each.

Так что, пожалуйста имейте это ввиду и постарайтесь изучить это лучше если вы хотите собирать Godot самостоятельно.

Настройка

Пожалуйста изучите документацию для Compiling for Android, Compiling for iOS, Compiling for macOS, Compiling for Universal Windows Platform, Compiling for the Web, Компиляция под Windows и Компиляция для X11 (Linux, *BSD).

Заметьте что для Windows/Visual Studio, вам нужно использовать x86_x64 Cross Tools Command Prompt for VS 2017 или похожий, зависит от ваших установок, вместо стандартной командного терминала Windows для ввода команд ниже.

Выбор платформы

Сборка Godot начнется с обнаружения платформ на которых она может собраться. Если требуемая платформа не обнаружится она просто не появится в списке доступных платформ. Требования сборки для каждой из платформ будут описаны в оставшейся части руководства.

SCons is invoked by just calling scons. If no platform is specified, SCons will detect the target platform automatically based on the host platform. It will then start building for the target platform right away.

To list the available target platforms, use scons platform=list:

scons platform=list
scons: Reading SConscript files ...
The following platforms are available:

    android
    javascript
    server
    windows
    x11

Please run SCons again and select a valid platform: platform=<string>

To build for a platform (for example, x11), run with the platform= (or p= to make it short) argument:

scons platform=x11

This will start the build process, which will take a while. By default, Godot's SCons setup is configured to use all CPU threads but one (to keep the system responsive during compilation). If you want to adjust how many CPU threads SCons will use, use the -j <threads> parameter to specify how many threads will be used for the build.

Example for using 4 threads:

scons platform=x11 -j 4

Полученный бинарный файл

The resulting binaries will be placed in the bin/ subdirectory, generally with this naming convention:

godot.<platform>.[opt].[tools/debug].<architecture>[extension]

For the previous build attempt, the result would look like this:

ls bin
bin/godot.x11.tools.64

Это означает что бинарный файл для X11, если не оптимизирован, имеет инструменты (целый редактор) скомпилированный с ним, и нацелен на 64 битную платформу.

Бинарный файл для Windows с такой же конфигурацией будет выглядеть следующим образом:

C:\godot> dir bin/
godot.windows.tools.64.exe

Copy that binary to any location you like, as it contains the project manager, editor and all means to execute the game. However, it lacks the data to export it to the different platforms. For that the export templates are needed (which can be either downloaded from godotengine.org, or you can build them yourself).

Помимо этого, есть несколько стандартных параметров для установки во всех целях сборки, и которые будут описаны ниже.

Инструменты

Инструменты(Tools) включены по умолчанию для всех ПК целей (Linux, Windows, macOS), но отключены для всего остального. Отключение инструментов создаёт бинарный файл который годится для запуска проектов но не включает в себя редактор или менеджер проектов.

scons platform=<platform> tools=yes/no

Цель

Цель контролирует оптимизации и флаги отладки. Каждый режим означает:

  • debug: Сборка с символами отладки C++, включенными проверками во время выполнения (выполняет проверки и сообщает об ошибках) и без оптимизации.

  • release_debug: Build without C++ debugging symbols and optimization, but keep the runtime checks (performs checks and reports errors). Official editor binaries use this configuration.

  • release: Build without symbols, with optimization and with little to no runtime checks. This target can't be used together with tools=yes, as the editor requires some debug functionality and run-time checks to run.

scons platform=<platform> target=debug/release_debug/release

This flag appends the .debug suffix (for debug), or .tools (for debug with tools enabled). When optimization is enabled (release), it appends the .opt suffix.

Биты

Биты нужны для контроля версии CPU или OS необходимые для запуска исполняемых файлов. Они сделаны преимущественно для десктопных платформ и игнорируются где-то ещё.

  • 32: Собирает бинарные файлы для 32-битной платформы.

  • 64: Собирает бинарные файлы для 64-битной платформы.

  • default: Build for the architecture that matches the host platform.

scons platform=<platform> bits=default/32/64

This flag appends .32 or .64 suffixes to resulting binaries when relevant. If bits=default is used, the suffix will match the detected architecture.

Custom modules

It's possible to compile modules residing outside of Godot's directory tree, along with the built-in modules.

A custom_modules build option can be passed to the command line before compiling. The option represents a comma-separated list of directory paths containing a collection of independent C++ modules that can be seen as C++ packages, just like the built-in modules/ directory.

For instance, it's possible to provide both relative, absolute, and user directory paths containing such modules:

scons custom_modules="../modules,/abs/path/to/modules,~/src/godot_modules"

Примечание

If there's any custom module with the exact directory name as a built-in module, the engine will only compile the custom one. This logic can be used to override built-in module implementations.

Cleaning generated files

Sometimes, you may encounter an error due to generated files being present. You can remove them by using scons --clean <options>, where <options> is the list of build options you've used to build Godot previously.

Alternatively, you can use git clean -fixd which will clean build artifacts for all platforms and configurations. Beware, as this will remove all untracked and ignored files in the repository. Don't run this command if you have uncommitted work!

Другие параметры сборки

Существуют несколько других параметров сборки которые вы можете использовать для настройки способа сборки Godot (компилятор, опции отладки, итд.) также как и возможности для включения/выключения.

Посмотрите вывод scons --help для подробностей по этим командам для версии которую вы хотите скомпилировать.

Overriding the build options

Using a file

The default custom.py file can be created at the root of the Godot Engine source to initialize any SCons build options passed via the command line:

# custom.py

optimize = "size"
module_mono_enabled = "yes"
use_llvm = "yes"
extra_suffix = "game_title"

You can also disable some of the builtin modules before compiling, saving some time it takes to build the engine. See Optimizing a build for size page for more details.

См.также

You can use the online Godot build options generator to generate a custom.py file containing SCons options. You can then save this file and place it at the root of your Godot source directory.

Another custom file can be specified explicitly with the profile command line option, both overriding the default build configuration:

scons profile=path/to/custom.py

Примечание

Build options set from the file can be overridden by the command line options.

It's also possible to override the options conditionally:

# custom.py

import version

# Override options specific for Godot 3.x and 4.x versions.
if version.major == 3:
    pass
elif version.major == 4:
    pass

Using the SCONSFLAGS

SCONSFLAGS is an environment variable which is used by the SCons to set the options automatically without having to supply them via the command line.

For instance, you may want to force a number of CPU threads with the aforementioned -j option for all future builds:

export SCONSFLAGS="-j4"

Экспорт шаблонов

Официальные шаблоны экспорта загружаются с официального сайта Godot: godotengine.org. Однако, вы можете захотеть собрать их самостоятельно (в случае если вы хотите более свежих, или вы хотите подключить свои модули, или просто не доверяете собственной тени).

If you download the official export templates package and unzip it, you will notice that most files are optimized binaries or packages for each platform:

android_debug.apk
android_release.apk
webassembly_debug.zip
webassembly_release.zip
linux_server_32
linux_server_64
linux_x11_32_debug
linux_x11_32_release
linux_x11_64_debug
linux_x11_64_release
osx.zip
version.txt
windows_32_debug.exe
windows_32_release.exe
windows_64_debug.exe
windows_64_release.exe

To create those yourself, follow the instructions detailed for each platform in this same tutorial section. Each platform explains how to create its own template.

The version.txt file should contain the corresponding Godot version identifier. This file is used to install export templates in a version-specific directory to avoid conflicts. For instance, if you are building export templates for Godot 3.1.1, version.txt should contain 3.1.1.stable on the first line (and nothing else). This version identifier is based on the major, minor, patch (if present) and status lines of the version.py file in the Godot Git repository.

If you are developing for multiple platforms, macOS is definitely the most convenient host platform for cross-compilation, since you can cross-compile for almost every target (except for UWP). Linux and Windows come in second place, but Linux has the advantage of being the easier platform to set this up.