Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
Экспортирование пакетов, патчей и модов
Случаи использования
Зачастую возникает желание добавить функциональность в игру уже после ее развертывания.
Примеры этого включают...
Загружаемый контент: возможность добавлять функции и контент в свою игру.
Патчи: возможность исправить ошибку, которая присутствует в отправленном продукте.
Моды: предоставить другим людям возможность создавать контент для своей игры.
Эти инструменты помогают разработчикам расширить свою разработку за пределы первоначального выпуска.
Обзор файлов PCK/ZIP
Godot делает это возможным с помощью функции, называемой resource packs (файлами PCK с расширением .pck или файлами ZIP).
Преимущества:
дополнительные обновления/патчи
даёт возможность создавать DLC
даёт возможность поддержки модификаций(модов)
нет необходимости раскрывать исходный код для модов
более модульная структура проекта
пользователям не нужно заменять всю игру
Первая часть их использования включает экспорт и доставку проекта игрокам. Затем, когда позже требуется добавить функциональность или контент, они просто доставляют обновления пользователям через файлы PCK/ZIP.
Файлы PCK/ZIP обычно содержат, помимо прочего:
скрипты
сцены
шейдеры
модели
текстуры
звуковые эффекты
музыка
любой другой ассет, пригодный для импорта в игру
Файлы PCK/ZIP могут даже представлять собой совершенно другой проект Godot, который оригинальная игра загружает во время выполнения.
Можно одновременно загружать файлы PCK и ZIP в качестве дополнительных пакетов. Сравнение двух форматов см. в разделе PCK по сравнению с форматами файлов ZIP Pack.
См. также
Если вы хотите загрузить свободные файлы во время выполнения (не упакованные в PCK или ZIP-архив Godot), рассмотрите возможность использования Загрузка и сохранение файла времени выполнения. Это полезно для загрузки пользовательского контента, созданного не с помощью Godot, и не требует от пользователей упаковывать свои моды в определенный формат файла.
Недостатком такого подхода является то, что он менее прозрачен для игровой логики, поскольку не позволяет использовать те же преимущества управления ресурсами, что и файлы PCK/ZIP.
Security concerns
It is important to note that loading PCK files for patches, mods, or extra content like expansions, will require you to code a system to automatically load files based on their location, and possibly name. This is a security vulnerability in three scenarios. One, a user downloads a mod with malicious code. Two, a malicious program already exists on an end user's PC and has replaced the PCK file with a malicious copy. Three, you are distributing patch PCK files through a game launcher and the system has become compromised.
Take this into consideration when determining how to use PCK files in a project. For situations where you have a patching system via a launcher, consider using asymmetric cryptography. You could store the public key in the main PCK, and sign patch or expansion PCK files with the private key. See the Crypto class for more information.
Copyright concerns
If you want to use PCK files to distribute extra paid content, such as expansions, keep in mind that Godot provides no out-of-the-box way to prevent someone from copying the PCK file, and putting it on another person's computer. Any kind of DRM system is your responsibility to implement if that's what you want.
Создание файлов PCK
In order to pack all resources of a project into a PCK file, open the project and go to , select an export preset, and click on .
Другой метод — export from the command line с помощью --export-pack. Выходной файл должен иметь расширение .pck или .zip. В процессе экспорта будет создан файл этого типа для выбранной платформы.
Patch PCK files
Generating Patch PCK files
To create a PCK file that only contains resources not present in the original release of a project, you would create a patch PCK file. This could be used for patches, mods, or expansions. For this to work you'll first need to have a PCK file for your project at the point of its initial release.
To generate a patch PCK file, within the export menu, and with your desired preset selected, click on the tab. At the bottom is the Base Packs section. Click on the button, then navigate to the PCK file you exported that contains everything in your project for its initial release.
Now, when you go to export a PCK file of your project again, if you have the button selected, only resources that have changed will be exported in the PCK file.
You can also add any patches you export to your base packs for future use. For
example, adding patch.pck will ensure that patch2.pck will not include any
resources from that first patch.
Delta encoding
Patch PCK files can be made smaller through the use of delta encoding. This makes it so that only the parts of a file that have been changed are updated. This does have a drawback of longer load times for the resources that are updated, and each patch for a resource cumulatively increases its load time.
There are two settings for delta encoding in addition to the filters:
Delta Encoding Compression Level: Controls how much compression is applied to the files. We do not recommend any more than the default of 19. Beyond that more memory is needed for export and import for significantly fewer gains. Any positive values will have the same decompression speed, however export will take longer the higher the number is. Negative values enable fast mode, which means larger files, but the decompression speed is higher.
Delta Encoding Minimum Size Reduction: Controls how much size has to be saved at minimum for compression to be used on an individual file. For example, at a level of 10%, if the file size can only be reduced by 5%, then the file won't use delta encoding.
The default compression level, 19, is the highest recommended level.
For the smallest patch size possible we recommend turning off compression for any resources you want to patch. Even if your base PCK files were compressed that shouldn't cause an issue.
There are several places compression can be disabled for different resources:
Import settings related to compression on individually imported resources, such as translation or 3D model files
Compress Binary Resources in the editor settings
GDScript Export Mode in the tab of an export preset
Примечание
After disabling Compress Binary Resources you must delete the contents of
your projects .godot/imported/ folder, then closing and open the project
again to re-generate it.
It's important to note that when you export a delta encoded patch on top of previous patches, the packs you list under Base Packs in the tab must be the exact same files that are loaded by the game at runtime, in the exact order they are loaded in. Re-exporting previous versions may end up being slightly different, due to non-determinism in Godot's export process, which can cause the patching to fail. This only applies to delta encoded patches, regular ones don't have this issue.
Открытие файлов PCK или ZIP во время выполнения
Для загрузки файла PCK или ZIP используется синглтон ProjectSettings. В следующем примере ожидается наличие файла mod.pck в каталоге исполняемого файла игры. Файл PCK или ZIP содержит в своем корневом каталоге тестовую сцену mod_scene.tscn.
func _your_function():
# This could fail if, for example, mod.pck cannot be found.
var success = ProjectSettings.load_resource_pack(OS.get_executable_path().get_base_dir().path_join("mod.pck"))
if success:
# Now one can use the assets as if they had them in the project from the start.
var imported_scene = load("res://mod_scene.tscn")
private void YourFunction()
{
// This could fail if, for example, mod.pck cannot be found.
var success = ProjectSettings.LoadResourcePack(OS.GetExecutablePath().GetBaseDir().PathJoin("mod.pck"));
if (success)
{
// Now one can use the assets as if they had them in the project from the start.
var importedScene = (PackedScene)ResourceLoader.Load("res://mod_scene.tscn");
}
}
Предупреждение
По умолчанию, если вы импортируете файл с тем же путем/именем, что и у файла, который уже есть в вашем проекте, импортируемый файл заменит его. На это следует обращать внимание при создании DLC или модов. Эту проблему можно решить, используя инструмент, который изолирует моды в определенной подпапке mods.
Однако это также способ создания патчей для собственной игры. Такой PCK/ZIP-файл может исправить содержимое ранее загруженного PCK/ZIP-архива (поэтому порядок загрузки пакетов имеет значение).
Чтобы отказаться от этого поведения, передайте false в качестве второго аргумента функции ProjectSettings.load_resource_pack().
Примечание
Для проекта C# вам необходимо сначала создать DLL и поместить его в каталог проекта. Затем перед загрузкой пакета ресурсов вам необходимо загрузить этот DLL следующим образом: Assembly.LoadFile("mod.dll")
Устранение неполадок
Если вы загружаете пакет ресурсов и не замечаете никаких изменений, это может быть связано с тем, что пакет был загружен слишком поздно. Это особенно актуально для сцен меню, которые могут предварительно загружать другие сцены, используя preload(). Это означает, что загрузка пакета в меню не повлияет на другую сцену, которая уже была предварительно загружена.
Чтобы избежать этого, необходимо загрузить пакет как можно раньше. Для этого создайте новый скрипт autoload и вызовите ProjectSettings.load_resource_pack() в скрипте автозагрузки функцию _init(), скорее, чем _enter_tree() или _ready().
Modding considerations
If one wishes to support mods for their game, they will need their users to create similarly exported files. Assuming the original game expects a certain structure for the PCK's resources, and/or a certain interface for its scripts, then one of two things has to be done.
- The developer must document these expected structures/
interfaces, expect modders to install Godot Engine, and then also expect those modders to conform to the documentation's defined API when building mod content for the game (so that it will work). Users would then use Godot's built in exporting tools to create a PCK file, as detailed above.
- The developer uses Godot to build a GUI tool for adding their exact API
content to a project. This Godot tool must either run on a tools-enabled build of the engine or have access to one (distributed alongside or perhaps in the original game's files). The tool can then use the Godot executable to export a PCK file from the command line with OS.execute(). The game itself shouldn't use a tool-build of the engine (for security), so it's best to keep the modding tool and game separate.