Моддинг: советы по эффективности моддинга

From Vintage Story Wiki
Revision as of 05:34, 21 February 2022 by Mirotworez (talk | contribs) (Created page with "== Поиск проблем == * Если вы столкнулись с проблемой актива, просмотрите server-main.txt и client-main.txt! Движ...")
Other languages:

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


Моддинг и даже сама разработка игр обычно требует множества проб и ошибок. Чем больше времени вы сможете сэкономить на этих итерациях, тем лучше, так как оно быстро накапливается. Помимо быстрого запуска, VS предлагает множество дополнительных приемов, которые помогут вам делать моды быстро и эффективно. Вот некоторые приемы, которые должен использовать каждый серьезный моддер.

Ярлыки

  • Используйте макросы! Переключение из/в творческий режим/режим выживания и /time set day привязаны к сочетанию клавиш. Нажмите CTRL+M, чтобы открыть диспетчер макросов, который позволит вам их настроить!
  • Когда вы редактируете файлы текстур и форм - их можно перезагрузить без перезагрузки с помощью команд .reload textures и .reload shape. Последнее может потребовать от вас размещения и удаления блока, чтобы фрагмент перерисовывался.
  • Записи перевода можно перезагрузить с помощью .reload lang, руководство можно перезагрузить с помощью .reloadhandbook
  • Настройте скрипт quickstart.bat, который содержит, например. VintageStory.exe -oTestWorld -pcreativebuilding — мгновенно запустит вас в сверхплоский творческий мир под названием «TestWorld».
  • Не перезапускайте игру полностью, чтобы проверить изменения! В 95% случаев достаточно просто выйти из игрового мира и вернуться или использовать внутриигровые команды перезагрузки. Вы можете быстро перезагрузить мир, используя сочетание клавиш CTRL+F1.
  • Оставьте свой мод распакованным в папке с модами! Его не нужно застегивать, он прекрасно загрузится в распакованном виде :-)
  • Используйте .tfedit, чтобы изменить внешний вид вашего предмета/блока в графическом интерфейсе, в руках или на земле — с предварительным просмотром в реальном времени.
  • Используйте .bsedit для редактирования выбора блоков и коллизий в игре — с предварительным просмотром в реальном времени.
  • Используйте команду /expclang для создания аккуратно отформатированного списка языковых записей, предназначенных для вашего en.json, он находится в файле с именем collectiblelang.json в той же папке, что и VintageStory.exe. Он создает языковые записи для любого блока или элемента, который в настоящее время не имеет перевода. Может сэкономить вам массу времени, поскольку вам не нужно вручную писать файл en.json.
  • Если вы изменяете файл json и хотите включить в свой мод только изменения, вы можете создать JSON патч. Обычно вы даже можете сэкономить время, написав его самостоятельно, используя ModMaker 3000 ™, инструмент командной строки, который поставляется с игрой, для создания патчей для вас.

Поиск проблем

  • Если вы столкнулись с проблемой актива, просмотрите server-main.txt и client-main.txt! Движок очень разговорчив, когда дело доходит до ошибок ассетов.
  • Включите отчет об ошибках на постоянной основе через /errorreporter 1, чтобы избавить себя от работы по поиску и просмотру файлов журналов на наличие проблем. Эта функция сделает так, чтобы диалоговое окно появлялось после завершения игры, если были обнаружены какие-либо ошибки.

When writing C# mods

  • Use break points for debugging
  • Browse through the many utility classes provided by the VS API, you might be able to save a lot of coding efforts! (e.g. ColorUtil, GameMath, ArrayExtensions, DictExtensions, HashsetExtensions, JsonUtil, ReaderWriterExtensions, SerializerUtil, WildcardUtil)
  • If you don't know it already, the LINQ extension, part of the .net framework, is an extremely powerful tool to make code more expressive.
  • Use the Hot reload feature of Visual Studio to modify code while the game is running, to see your changes immediately without restarting the world.
    • Note that this feature works if you use the official mod template and set up your mod as a "compiled" mod. It does not work if you set up your mod as a "source" mod, and it may not work with all other development environment setups.
  • If you don't have already make sure the games log output ends up in the Visual Studio output window
  • If you are working with shaders, you can reload them with .reload shaders
  • Do not hold static references unless its primitive data. Static references are not garbage collected when the player leaves a server / game world. Example: Holding a static reference of a Block will keep that block in memory, which in turn keeps the API Instance in memory, which in turn keeps the entire game world in memory.
  • The game client and server have a number of startup arguments to make your live easier

Efficient Search Methods

More often than not, you'd want your code to find something in the game world. As you might already know, computers are not exactly the best at parallel processing like human eyes are, so they have to sequentially look through the entire search space. When doing so, keep in mind that, first and foremost, the most efficient search method is one that never runs, within a search space that is of size zero ;-)
In other words, sometimes you can avoid searches altogether through other clever means! If you still need to do a search, here's some more optimal ways than the brute force way:

  • Entity Search
    Use EntityPartitioning - api.ModLoader.GetModSystem<EntityPartitioning>().WalkEntityPartitions(). This system partitions entities into 8x8x8 block buckets through the entire loaded game world, then only searches inside those buckets, within your supplied search radius, greatly reducing the search space.
  • Block Search
    a) If you want an entity to find a certain, not extremely common block, use the POI Registry. This registry lets block entities register a point of interest that entities can search through very efficiently. They are also partitioned into chunk column buckets to additionally reduce the search space. For a code sample, check out the berry bush block entity
    b) For regular full chunk scans, I recommend a separate background thread that loads the chunk and access the raw block data via chunk.Blocks. It's an array indexed with (y * chunksize + z) * chunksize + x, where the xyz are local coordinate from 0 to chunkize-1. You should only write to a chunk in the main thread however! If you want to avoid threading for now, you can still iterate through chunk.Blocks in the main thread and even slice up the task across multiple ticks, like vanilla beehives do.
    c) For rare area scans, there is api.World.GetBlockAccessorPrefetch(). This block accessor lets you pre-load an area and then rather efficiently iterate through each block in given area
 

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