Modding:Setting up your Development Environment/ru: Difference between revisions

From Vintage Story Wiki
(Created page with "==== Добавить мод ====")
(Created page with "Добавляет новый проект мода в вашу рабочую область, а также создает <code>assets</code>, папку <code>src</code> и...")
Line 196: Line 196:
{{Syntax|add <modid>}}
{{Syntax|add <modid>}}


Adds a new mod project to your workspace, also generates an <code>assets</code>, a <code>src</code> folder and a <code>modinfo.json</code> file. The mod will be added to your visual studio solution and will be loaded by Vintage Story. Make sure to fill in all additional information in <code>modinfo.json</code>.
Добавляет новый проект мода в вашу рабочую область, а также создает <code>assets</code>, папку <code>src</code> и файл <code>modinfo.json</code>. Мод будет добавлен в ваше визуальное студийное решение и загружен Vintage Story. Обязательно заполните всю дополнительную информацию в <code>modinfo.json</code>.


==== Delete Mod ====
==== Delete Mod ====

Revision as of 07:22, 16 June 2022

Other languages:

Эта страница проверялась в последний раз для версии Vintage Story 1.15.


Программное обеспечение

Когда вы будете готовы приступить к кодированию модов для Vintage Story, вы, вероятно, захотите настроить среду разработки, которая упростит процесс кодирования и тестирования ваших творений. Есть несколько приложений, которые помогут вам в разработке модов. Вот несколько предложений:

  • Visual Studio Community это бесплатная и очень мощная среда разработки, описанная в руководстве ниже. Это также инструмент, который команда Vintage Story использует для создания игры. Он также имеет MacOS версию.
  • Jetbrains Rider — это бесплатная и современная среда разработки с бесшовной поддержкой проектов, сочетаний клавиш и макетов Visual Studio. Это корпоративный продукт, и некоторые функции заблокированы лицензией (проверка дублирования кода, инструменты веб-разработчика), но все функции, необходимые для разработки модов VS, бесплатны. Функции индексации/перехода к ссылкам и встроенные функции декомпиляции очень эффективны, так как вы можете нажать на метод, который использует Vintage Story, и он покажет вам код, стоящий за ним. Обратите внимание, что в настоящее время в нем есть одна ошибка + задокументировано обходное решение. тут.
  • MonoDevelop — еще одна IDE, более легкая, чем Visual Studio Community.
  • Notepad++ ваш самый простой инструмент для редактирования текста с некоторыми дополнительными функциями. На самом деле, вы можете кодировать моды в любом текстовом редакторе. Однако при программировании отсутствует мгновенная контекстно-зависимая обратная связь, что очень полезно. Если вы выберете этот путь, вы сможете использовать саму игру для проб и ошибок, перезагрузив их во время игры.

Установить средство разработки

VintageStory разработан на C#. Выберите одну из вышеперечисленных IDE или другие альтернативы. Мы предлагаем использовать Visual Studio Community для Windows. Для Linux вы можете использовать Visual Studio Code, Rider или MonoDevelop.

После загрузки IDE вы можете получить проект мода или вручную настроить проект мода. Шаблон мода предлагает удобный инструмент для настройки нескольких проектов модов, а также для быстрой упаковки и получения готового к отправке мода.

Руководство по установке в Windows/macOS с Visual Studio

OS Repo Command
Windows скачать exe Запустить загруженный файл
macOS скачать dmg Запустить загруженный файл

Руководство по установке на Linux/macOS с MonoDevelop

Вы можете использовать MonoDevelop IDE для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы добавить репозиторий, затем запустите команду установки.

OS Repo Command
Debian 8-10 repo sudo apt-get install monodevelop
Ubuntu 14.04-20.04 repo sudo apt-get install monodevelop
CentOS / RedHat repo yum install monodevelop
Используя Flatpak Скачать Flatpak flatpak install --user --from https://download.mono-project.com/repo/monodevelop.flatpakref
macOS руководство по сборке Используйте Visual Studio или соберите из исходного кода
Другие Компиляции из исходников Следуйте инструкциям для компиляции из исходников

Руководство по установке на Linux / macOS с Visual Studio Code

Вы можете использовать Visual Studio Code для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы загрузить ее.

OS Download Command
Debian 8-10 скачать deb sudo dpkg -i /path/to/vscode/file.deb && sudo apt-get install -f
Ubuntu 18.04-20.04 скачать deb sudo apt install /path/to/vscode/file.deb
CentOS / RedHat / Fedora / SUSE скачать rpm rpm -ih /path/to/vscode/file.rpm
Arch пакет yay -S visual-studio-code-bin
Использовать Snap скачать snapd sudo snap install code --classic
macOS скачать zip Запустить загруженный файл
Другие компилирование из исходников Следуйте инструкциям для компиляции из исходников

Руководство по установке на Windows / Linux / macOS с JetBrains Rider

Вы можете использовать Jetbrains Rider для создания модов VS в Linux. Инструкции по загрузке приведены ниже, выберите свою ОС и перейдите по ссылке, чтобы загрузить ее.

OS Download Command
Windows скачать exe Запустить загруженный файл
Arch Пакет yay -S rider mono mono-msbuild
Используя Toolbox СкачатьToolbox Следуйте приведенным инструкциям для вашей ОС
Используя Snap Скачать snapd sudo snap install rider --classic
macOS Скачать dmg Запустить загруженный файл
Другие Скачать .tar.gz sudo tar -xzf ideaIU.tar.gz -C /opt && cd /opt/idea-dir-edit-me && sudo ./idea.sh

Шаблоны модов

Настройка с использованием официального шаблона мода

Для начала загрузите решение VSModTemplate с GitHub. Теперь вам просто нужно распаковать zip-архив в нужное место.

VSMods9.png

Перейдите к vsmodtemplate-x.y.z и дважды щелкните VSMods.sln (работает, только если установлена Visual Studio). В качестве альтернативы вы также можете запустить Visual Studio, нажав File -> Open -> Project/Solution..., перейти к извлеченной папке и выбрать VSMods.sln.

Но прежде чем вы сможете начать работать, вы должны сначала настроить ModTools.

Запустить ModTools

ModTools позволяет вам довольно легко выполнять различные задачи, вводя команду. Для каждой платформы требуется свой способ запуска. Обратите внимание, что инструменты модификации были протестированы только с Visual Studio и MonoDevelop, но они не требуются для модификации игры, они просто упрощают некоторые задачи.

Windows

Дважды щелкните vsmodtools.exe.

Linux

Откройте терминал, перейдите в эту папку и введите mono vsmodtools.exe.

Mac OS

Дважды щелкните modtools.command.

ModTools.png

Настройка

Syntax: setup [optional path]


Прежде чем делать что-либо еще, вы должны настроить свое рабочее пространство. Просто введите setup, и он автоматически попытается найти каталог установки Vintage Story. Если он не может найти его, вам будет предложено ввести полный путь. После того, как вы введете свой путь, он обновит файлы вашего проекта, чтобы вы могли начать с ним работать. Теперь снова откройте проект и запустите первый тест, нажав Start VSMods10.png. Если все настроено правильно, должна запуститься Vintage Story.

Настройка проекта (ZIP)

Система исходных модов позволяет вам создавать zip-моды, которые могут отправлять исходный код помимо своих активов. Исходный код компилируется во время выполнения движком modloader. Это имеет большое преимущество в том, что оно открыто и легко модифицируется во время выполнения, но также имеет один существенный недостаток, заключающийся в том, что встроенный компилятор исходного кода может компилировать код только до версии C# 6.0, поэтому более новые функции языка не поддерживаются. Если это для вас шоу-стоппер, мы советуем вам собрать скомпилированный мод.

Добавить мод

Syntax: add <modid>


Добавляет новый проект мода в вашу рабочую область, а также создает assets, папку src и файл modinfo.json. Мод будет добавлен в ваше визуальное студийное решение и загружен Vintage Story. Обязательно заполните всю дополнительную информацию в modinfo.json.

Delete Mod

Syntax: delete <modid>


Before executing, make sure your project is closed, otherwise you might run into some difficulties. Running this command will delete the given mod completely (irreversible).

Pack Mod

Syntax: pack <modid>


Creates a mod zip file and places it in /releases/<modid>/<modid>_v<modversion>.zip. This file is ready for use and can be shared with other people.


Syntax: pack-all


Packs all mods in your workspace at once.

Project Setup (Compiled Zip)

Both dll and zip mods have their advantages and disadvantages, so why not combine them together? This project setup is very similar to zip. Instead of adding the source code to the zip file, it uses the compiled dll. This allows you to have all the dll benefits while still having the zip mod asset structure.

Add Mod

Syntax: add <modid> compiled


Adds a compiled zip mod template to your workspace. The difference is that it uses a compiled dll instead of the actual source code. All other commands are equal to the zip ones.

Set Mod

Syntax: set <modid> <source|compiled>


Sets the given zip mod either to source or compiled. This can be useful if you want to change the type of your mod later on.

Project Setup (DLL)

Dll mods are way more powerful than source mods, but they have two major downsides. Firstly, they are not able to carry assets which will be loaded by the game, secondly because they are so powerful they can be dangerous. Besides that dll mods can (unlike the others) have cross mod references, provide APIs and use C# 7. We recommend this type of mod for more experienced mod developers.

Add Mod

Syntax: add-dll <modid>


Adds a new mod project to your workspace. A generated AssemblyInfo.cs file will be in your properties folder, it contains the mod information (name, author, version, description etc.) so make sure to change them before you spread the mod to other people. The mod will be added to your visual studio solution and will be loaded by VintageStory.

Delete Mod

Syntax: delete <modid>


Before executing, make sure your project is closed, otherwise you might run into some difficulties. Running this command will delete the given mod completely (irreversible).

Release Mod

Once you launch VintageStory in your workspace, the DLL mod will be compiled. You can find it in your mods folder, with the give name: <modid>.dll. If you want to upload this mod or share it with your friends this is the file you need to use.

Manual setup

  • Create a new project
  • Add at least a library reference to the VintageStoryApi.dll (on Windows it's located in the installation directory)
  • Open the project properties. Under debug select "Start external program" select the VintageStory.exe. Also adjust the working directory to where the executable is located.
  • If you compile to a .dll file, set up a ModInfo attribute in your AssemblyInfo.cs (example)
    • Add the following command line arguments: -openWorld="modsamplestest" -pcreativebuilding --addModPath="C:\path\to\your\bin\folder" --addOrigin="C:\path\to\your\assets\folder\if\you\have\any"
  • If want to ship a source mod or mod with assets, set up a modinfo.json (example). Make sure your folders are set up in a way that the modPath contains the modinfo.json and a folder named "src" containing your source files. Optionally it can also contain an assets folder for your assets.
    • Add the following command line arguments: -openWorld="modsamplestest" -pcreativebuilding --addModPath="C:\path\to\your\modPath"
  • I recommend adding the RedirectLogs.cs file to your project, so that you can see the log output in your visual studio output window. Be sure not to ship your mod with it though.
  • Run the project and hope for the best :D
  • To ship a mod have a look at Mod Packaging

If you are having troubles, you might be able to learn from the vsmodexamples project

Moving Forward

If you've successfully managed to setup your development environment and can run Vintage Story through the VSMods project in your IDE then it's time to get started on your first code mod. At this point there are many options you can choose from as code mods can alter almost any aspect of the game. However, the best place to start is likely one again with Blocks and Items (since you should be familiar with making them using JSONS by this point).

Head over to the Advanced Blocks page to make your first advanced code block.

Or head over to the Advanced Items page to make your first advanced code item.

Icon Sign.png

Wondering where some links have gone?
The modding navbox is going through some changes! Check out Navigation Box Updates for more info and help finding specific pages.

Modding
Modding Introduction Getting Started Пакет тем
Content Modding Content Mods Developing a Content Mod Basic Tutorials Intermediate Tutorials Advanced Tutorials Content Mod Concepts
Code Modding Code Mods Setting up your Development Environment
Property Overview ItemEntityBlockBlock BehaviorsBlock ClassesBlock EntitiesBlock Entity BehaviorsWorld properties
Workflows & Infrastructure Modding Efficiency TipsMod-engine compatibilityMod ExtensibilityVS Engine
Additional Resources Community Resources Modding API Updates Programming Languages List of server commandsList of client commandsClient startup parametersServer startup parameters
Example ModsAPI DocsGitHub Repository