- User Tools
- Site Tools
- Table of Contents
- Настройка среды разработки
- Необходимо перед началом
- Первые шаги
- Ручное управление
- IntelliJ IDEA
- Eclipse
- Visual Studio Code
- MinecraftDev IntelliJ IDEA Plugin
- Generator
- FabricMC
- Pinned
- People
- Top languages
- Most used topics
- Как установить Fabric в TLauncher / Майнкрафт
- Автоматическая установка через TLauncher
- Ручная установка Fabric
- Где скачать Fabric
- Установка Fabric
- Где найти моды на Fabric
- User Tools
- Site Tools
- Table of Contents
- Создание команда
- Что такое Brigadier?
- Что такое команда?
- Простейшая команда
- Подкоманда
- Registering the commands
- Arguments
- Static Imports
- Advanced concepts
- Why does my command not compile
- Catch or throw a CommandSyntaxException
- Issues with generics
- Can I register client side commands?
- Dark Arts
- Can I register commands in runtime?
- Can I unregister commands in runtime?
- Sorry for the mess
- Requirements
- Exceptions
- Redirects (Aliases)
- Redirects (Chainable Commands)
- What can the ServerCommandSource do?
- Some example commands examples
- Broadcast a message
- /giveMeDiamond
- Antioch
- More examples coming soon
- Custom Argument Types
- Creating a Minecraft Mod using Java and Fabric
- Selecting the tools
- Setting up the project
- 1. Clone / Download the repository
- 2. Open the project folder with your code editor
- 3. Open a terminal inside the project folder and run the client
- 4. Check that everything is working
- Getting to know the project
- gradle.properties
- src/main
- src/main/java
- src/main/resources
- Let’s build our mod!
- Detecting when players receive damage
- Accessing the current player
- Switching positions with another player
- Swapping their inventories
- The final code
- Packaging the mod
- Learning resources
- Conclusion
User Tools
Site Tools
Table of Contents
Настройка среды разработки
Необходимо перед началом
Первые шаги
Существует два основных способа создать мод для Minecraft, используя Fabric. Вы можете либо вручную скачать fabric-example-mod и установить его самостоятельно, или же воспользоваться автоматическим инструментарием.
Ручное управление
IntelliJ IDEA
Если вы используете IntelliJ IDEA от JetBrains, пожалуйста, выполните следующие действия:
Необязательно, но рекомендуется: По умолчанию IntelliJ делегирует Gradle создание проекта. Это не нужно для Fabric и вызывает более длительное время сборки и связанные с горячей заменой странности, среди прочих проблем. Чтобы исправить это используйте встроенный компилятор:
К сожалению, в настоящее время невозможно установить значение IDE по умолчанию для параметров ‘Build and run using’ и ‘Run tests using’, поэтому эти шаги должны повторяться для каждого нового проекта.
Eclipse
Visual Studio Code
Если вы используете VSCode от Microsoft, пожалуйста, следуйте этим инструкциям
MinecraftDev IntelliJ IDEA Plugin
Если вы используете IntelliJ IDEA, вы можете использовать плагин MinecraftDev. Этот плагин добавляет поддержку автоматического создания проектов Fabric, а также некоторых функций, связанных с mixin, таких как проверки, генерация accessors/shadow полей и копирование целевых ссылок Mixin (дескрипторов JVM). Плагин можно найти в репозитории плагинов IntelliJ, таким образом, вы можете установить его с помощью внутреннего браузера плагинов IntelliJ, перейдя в File → Settings → Plugins, затем перейдите на вкладку Marketplace и выполните поиск по слову Minecraft.
Generator
Если вы не можете использовать плагин MinecraftDev или fabric-example-mod, вы также можете использовать GeneratorFabricMod от ExtraCrafTX, удобный инструмент для автоматического создания новых модов Fabric из шаблона. Выполните следующие действия:
Источник
FabricMC
We’ve verified that the organization FabricMC controls the domain:
fabricmc.net
Pinned
Essential hooks for modding with Fabric.
Libre Minecraft mappings, free to use for everyone. No exceptions.
Example Fabric mod
Fabric’s mostly-version-independent mod loader.
This is a fork of cuchaz’s engima, a deobfuscation/remapping tool for Java software.
Gradle build system plugin used to automate the setup of a minecraft mod development environment.
Essential hooks for modding with Fabric.
38 Updated Oct 8, 2021
Gradle build system plugin used to automate the setup of a minecraft mod development environment.
17 Updated Oct 8, 2021
Fabric Meta is a JSON-based HTTP api that can be used to query metadata about key Fabric projects.
4 Updated Oct 8, 2021
Libre Minecraft mappings, free to use for everyone. No exceptions.
10 Updated Oct 8, 2021
Match and mapping information between different versions of Minecraft
3 Updated Oct 7, 2021
Fabric’s mostly-version-independent mod loader.
16 Updated Oct 7, 2021
Docs, tags and orchestration.
6 Updated Oct 4, 2021
This is the public repository for the CFR Java decompiler
0 Updated Oct 4, 2021
Access wideners provide a way to loosen the access limits of classes.
3 Updated Oct 4, 2021
An Installer for Fabric. For the vanilla launcher
5 Updated Oct 4, 2021
People
Top languages
Most used topics
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Как установить Fabric в TLauncher / Майнкрафт
Fabric является загрузчиком модов для Minecraft, альтернатива или аналог Forge. На Фабрик сделано уже достаточно много модов, поддерживает множество версий Minecraft. В данном гайде узнаете, как скачать и установить в ТЛаунчер версию с Fabric.
Автоматическая установка через TLauncher
В нашем лаунчере началось внедрение автоматической установки Fabric, как и с другими версиями в главном списке, они устанавливаются в один клик.
Условия: Ваш TLauncher выше версии 2.7.
Внимание: Автоматическая установка из списка, доступно пока только для Fabric 1.16.5, другие версии находятся на этапе внедрения, следите за новостями в нашем паблике ВК.
Ручная установка Fabric
Вы по прежнему сможете установить любую версию Fabric вручную в TLauncher, следуйте инструкции ниже и у вас всё получится.
0) Проверяем, что у вас последняя версия нашего лаунчера. Скачать актуальной версии TLauncher можно с главной страницы.
Где скачать Fabric
1) Самым правильный вариантом, будет скачивание с официального сайта: fabricmc.net. Мы не гарантируем, что скаченное с других сайтов запустится через наш лаунчер!
2) На представленном сайте выбираем вкладку «Vanilla» (ТОЛЬКО ЕГО!), версию можно оставлять первую (это не версия игры, а установщика, выбор версии игры будет дальше!). Скачиваем под Windows или универсальный Jar:
Установка Fabric
3) Запускаем скаченный вами Установщик (Installer) Fabric, и из списка «Minecraft Version» выбираем нужную версию игры.
4) Больше нечего можно не выбирать, только если нужно, включить галочку снапшоты! Нечего более не меняя, кликаем на «Install». Готово!
5) Закрываем установщик и открываем TLauncher, в списке версий теперь ищем новую версию «fabric-loader-XXX+XXX«. Можем запускать.
Где найти моды на Fabric
Моды на Fabric устанавливаются абсолютно так же, как и у forge, в папку mods. При такой ручной установке вам необходимо обязательно на скачиваемом сайте найти, что мод именно на Fabric. На нашем сайте есть моды Майнкрафт на Фабрик, в блоке с инструкцией установки сможете найти информации о принадлежности к Fabric или Forge:
Источник
User Tools
Site Tools
Table of Contents
Создание команда
Создание команд позволяет разработчику наращивать функционал и способ воздействия с пользователем через, собственно, команды. Это руководство расскажет как регистрировать команды и общую инофрмацию о структуре Brigadier.
Примечание: Весь код, описанный здесь, написан для 1.14.4. Что-то может быть изменено в yarn, но большая часть кода всё ещё применима и там.
Что такое Brigadier?
С исходным кодом Brigadier вы можете ознакомиться тут: https://github.com/Mojang/brigadier
Что такое команда?
Вы можете создать команду несколькими образами, которые написаны ниже:
Как лямбда-выражение
Как анонимный класс
Как часть класса
Как обращение к методу
Простейшая команда
Ниже вы можете увидеть команду, без аргументов:
Подкоманда
Чтобы добавить команде подкоманду, сначала необходимо зарегестрировать ветвь с буквальным вводом.
It is advised to indent your code as you add nodes to the command. Usually the indentation corresponds to how many nodes deep one is on the command tree. The new line also makes it visible that another node is being added. There are alternative styles to formatting the tree command that are shown later on in this tutorial.
So let’s try running the command
Most likely if you typed /foo bar in game, the command will fail to run. This is because there is no code for the game to execute when all the required arguments have been met. To fix this, you need to tell the game what to run when the command is being executed using the executes(Command) method. Below is how the command should look as an example.
Registering the commands
The event should be registered in your mod’s initializer. The callback has two parameters. The CommmandDispatcher is used to register, parse and execute commands. S is the type of command source the command dispatcher supports. The second parameter is a boolean which identifies the type of server the commands are being registered. on is an dedicated or integrated (false) server.
Inside your lambda, method reference or whatever you have chosen, you will register your commands.
If desired, you can make sure a command is only registered on a dedicated server by checking the dedicated flag
Arguments
TODO: Go into more detail on how to use arguments
Static Imports
And your imports would look something like this:
Note: Please be sure you use the literal and argument from CommandManager or you may have issues with generics when trying to compile.
Brigadier’s default arguments are at com.mojang.brigadier.arguments
Advanced concepts
Below are links to the articles about more complex concepts used in brigadier.
Page | Description |
---|---|
Requirements | Only allow users to execute commands in certain scenarios. |
Exceptions | Fail execution of a command with a descriptive message and in certain contexts. |
Suggestions | Suggesting input to be sent to the client. |
Redirects (Aliases) | Allow use of aliases to execute commands. |
Redirects (Chaining) | Allow commands to have repeating elements and flags. |
Custom Argument Types | Parse your own arguments and return your own types. |
TODO: Sections are being moved to sub categories and will be added to their respective articles as they are migrated.
Why does my command not compile
There are two immediate possibilities for why this could occur.
Catch or throw a CommandSyntaxException
The solution to this issue is to make the run or suggest methods throw a CommandSyntaxException. Don’t worry, brigadier will handle the exceptions and output the proper error message.
Issues with generics
Can I register client side commands?
Fabric doesn’t currently support client side commands. There is a third-party mod by the Cotton team that adds this functionality.
Dark Arts
A few things we don’t recommend, but are possible.
Can I register commands in runtime?
Can I unregister commands in runtime?
Sorry for the mess
Currently this article is being migrated, so things may be a mess. Below is are the parts of the article that are yet to be migrated to the new format.
Requirements
Lets say you have a command you only want operators to be able to execute. This is where the requires method comes into play. The requires method has one argument of a Predicate which will supply a ServerCommandSource to test with and determine if the CommandSource can execute the command.
For example this may look like the following:
This command will only execute if the Source of the command is a level 4 operator at minimum. If the predicate returns false, then the command will not execute. Also this has the side effect of not showing this command in tab completion to anyone who is not a level 4 operator.
Nothing prevents someone from specifying calls to permissions implementations within the requires block. Just note that if permissions change, you need to re send the command tree.
Exceptions
Brigadier supports command exceptions which can be used to end a command such as if an argument didn’t parse properly or the command failed to execute, as well as including richer details of the failure.
Though you are not just limited to a single type of exception as Brigadier also supplies Dynamic exceptions which take additional parameters for context.
Redirects (Aliases)
Redirects are Brigadier’s form of aliases. Below is how Minecraft handles /msg have an alias of /tell and /w.
The redirect tells brigadier to continue parsing the command at another command node.
Redirects (Chainable Commands)
Commands such as /execute as @e[type=player] in the_end run tp
are possible because of redirects. Below is an example of a chainable command:
The redirect can also modify the CommandSource by use of a redirect modifier which can be used for builder commands.
What can the ServerCommandSource do?
A server command source provides some additional implementation specific context when a command is run. This includes the ability to get the entity that executed the command, the world the command was ran in or the server the command was run on.
Some example commands examples
Broadcast a message
/giveMeDiamond
First the basic code where we register “giveMeDiamond” as a literal and then an executes block to tell the dispatcher which method to run.
Then since we only want to give to players, we check if the CommandSource is a player. But we can use getPlayer and do both at the same time and throw an error if the source is not a player.
Then we add to the player’s inventory, with a check to see if the inventory is full:
Antioch
…lobbest thou thy Holy Hand Grenade of Antioch towards thy foe. who being naughty in My sight, shall snuff it.
Aside from the joke this command summons a primed TNT to a specified location or the location of the sender’s cursor.
First create an entry into the CommandDispatcher that takes a literal of antioch with an optional argument of the location to summon the entity at.
Then the creation and messages behind the joke.
More examples coming soon
Custom Argument Types
Brigadier has support for custom argument types and this section goes into showing how to create a simple argument type.
Warning: Custom arguments require client mod installation to be registered correctly! If you are making a server plugin, consider using existing argument type and a custom suggestions provider instead.
For this example we will create a UuidArgumentType.
ArgumentType requires you to implement the parse method, the type it returns will match with the Generic type.
This method is where all of your parsing will occur. Either this method will return the object based on the arguments provided in the command line or throw a CommandSyntaxException and parsing will fail.
Next you will store the current position of the cursor, this is so you can substring out only the specific argument. This will always be at the beginning of where your argument appears on the command line.
Now we grab the entire argument. Depending on your argument type, you may have a different criteria or be similar to some arguments where detecting a < on the command line will require it to be closed. For a UUID we will just figure out what cursor position the argument ends at.
Then we will ask the StringReader what the current position of the cursor is an substring our argument out of the command line.
Now finally we check if our argument is correct and parse the specific argument to our liking, and throwing an exception if the parsing fails.
The ArgumentType is done, however your client will refuse the parse the argument and throw an error. This is because the server will tell the client what argument type the command node is. And the client will not parse any argument types it does not know how to parse. To fix this we need to register an ArgumentSerializer. Within your ModInitializer. For more complex argument types, you may need to create your own ArgumentSerializer.
Источник
Creating a Minecraft Mod using Java and Fabric
A few weeks ago, YouTube recommended me a Minecraft video from Dream’s Channel in which he was trying to beat the game while his friend George attempted to stop him. That video was really fun and got me to explore more of their content.
Right now, there’s a bunch of people recording and uploading Minecraft videos to YouTube, but these two found a way to make their content different. Basically, they build their own plugins to change the rules of the game and then they record themselves attempting to beat the modified game. All I can say is that I love their content, and it’s awesome to see what you can accomplish with the power of code.
A few days later, I had an idea to develop a Minecraft mod and thought Why not? It will be fun!
Selecting the tools
Just like in Minecraft, we need some tools but in this case, they will help us in the creation process of our first mod.
Multiple tools help you build Minecraft mods, and I chose Fabric because one of the mods that I usually play with was built with it.
Minecraft uses Java and so does Fabric, which means we also need to have the Java Development Kit or JDK installed. To be more specific, we need the JDK 8 to be able to compile our mod. You can download it on this page.
Last but not least, we need to pick a code editor, in this case, I chose Visual Studio Code because it’s my favorite editor. Nevertheless, you can use whatever editor you like for this guide, as most of the steps will be performed in the CLI.
Setting up the project
For this guide, we will be using a starter to move quickly into actually building our first mod. Let’s go through the following steps:
1. Clone / Download the repository
If you use Git, just clone the repo:
Exit fullscreen mode
2. Open the project folder with your code editor
Using Visual Studio Code:
Exit fullscreen mode
3. Open a terminal inside the project folder and run the client
Exit fullscreen mode
4. Check that everything is working
A Minecraft instance should be running now on your computer, and the console should have printed these two lines alongside others:
Exit fullscreen mode
If that’s not the case for you, recheck everything and if nothing seems to work, leave a comment or send me a PM and I’ll try to help you.
Getting to know the project
At the moment, we can already get our hands dirty by starting to code, but let’s get familiarized with some of the files.
gradle.properties
In this file, we can configure some values that will be used when building our mod. For example, we can change the Minecraft version, the fabric loader version, the mod version and other properties that we may need to change if we want to use new features of Fabric or Minecraft.
Exit fullscreen mode
src/main
src/main/java
All the Java code is located inside this folder. There we can find a package called starter which contains two items: the StarterMod.java file and the mixin package.
We can find the file StarterMixin.java inside the mixin package.
TIP: If you’re using Visual Studio Code, I recommend you to install the Java Extension Pack. It will power your editor with a bunch of utilities to make Java development easier.
This is the main entry point of our mod, as we can see, it belongs to the starter package and implements the onInitialize() method, which simply prints Hello Fabric world! to the console.
Exit fullscreen mode
This class belongs to the starter.mixin package. Our mod will be really small so we shouldn’t worry a lot about the file structure of our project. Let’s just assume that all mixins will be located inside the starter.mixin package.
And what are mixins?
That’s part of the magic of mixins, and this is just the tip of the iceberg, for now, this is all we need to build our mod. If you want more in-depth knowledge you should go check the Mixin docs.
Exit fullscreen mode
src/main/resources
Inside the resources folder, we can find the assets folder, which right now only contains the icon for our mod. Besides that folder, there are two JSON files:
For this file, I recommend you to go into the Fabric docs about fabric.mod.json and read about every field defined inside the file of our project.
If you prefer to read the docs later, just take a look at the entrypoints and mixins properties.
I bet you can already see a connection here. In the entrypoints is where we are telling Fabric which one of our Java classes should act as the main entry point of our mod.
Exit fullscreen mode
Remember our StarterMixin class? This is how we can tell the toolchain the mixins that we want to include in our mod. The package property is where we define the Java package where the mixins are located, and inside the mixins array is where we can put all the mixin classes that we want to include to the game.
This file follows the specification defined in the Mixin configuration files section of the Mixin Docs. Just the same as before, I recommend you to go to the docs and learn more about this file 😄
Exit fullscreen mode
Let’s build our mod!
Now that we are familiar with the project, let’s gets our hands dirty and create our mod!
In this case, the mod will simply alter one mechanic of the game: receiving damage. We’ll make it so whenever a player receives damage, it will switch its position and inventory with another player in the server.
For this, we’re going to need a mixin that injects code in the PlayerEntity class, to be more specific, just before the end of the damage() method.
Detecting when players receive damage
Let’s create this new mixin in the starter.mixin package with the name SwitchPlayerEntityMixin.java :
Exit fullscreen mode
Don’t forget to add it to the starter.mixins.json file:
Exit fullscreen mode
Just like in the GIF, you should be able to see a new line pop up in the console every time the player gets hurt, and that means we can continue to the explanation of what is going on.
Both the source and amount are parameters that the original damage method receives, and that’s the reason we can just use them in our method.
Accessing the current player
Right now, the mod is just printing a line every time a player gets hurt, our next objective is accessing the player instance.
We don’t have a way to tell the compiler that this method is being executed inside of another type of class, so we can use this trick:
Exit fullscreen mode
Exit fullscreen mode
Switching positions with another player
The world property references the current Minecraft World that is being played, and one of the things we can do with it is getting the list of the online players.
With that list, we can pick one of those players and later, swap their positions as you can see in the following code:
Exit fullscreen mode
Swapping their inventories
And now we’ll add the last feature of the mod: swapping the inventory of the players.
To swap the inventories of two players, we have to clone each inventory and after that, we can just replace and swap them. The inventory of a player can be accessed using the inventory property.
Exit fullscreen mode
As you may have noticed, we’re only swapping the inventories if both players are alive because if we don’t include this check, one of the inventories would get lost whenever a player died.
The final code
I also recommend you to rename the package from starter to whatever you want, just remember to change every occurrence in the project.
You can find the latest version of the code in the branch final-code of the starter repo. Click here see the final version of the mod.
Packaging the mod
To create a bundle of your mod, you only need to run the following command:
Exit fullscreen mode
Learning resources
Here are some resources that may come in handy if you want to learn more about Minecraft Modding:
The Fabric Wiki. This one has already been mentioned in the article, but seriously, go check it out because there’s a lot of content that I haven’t covered!
The Forge API. The Forge API is the most famous Minecraft API, you may want to check it out because some of the best mods out there have been built with it!
ScriptCraft. There seems to be a way to build mods using JavaScript, so if you have a background in web dev, you may want to try this one.
MCreator. As their site says, MCreator is a software used to make Minecraft mods and data packs using an intuitive easy-to-learn interface or with an integrated code editor. If you know about someone that wants to get started with programming, this may be a good way to introduce them!
Conclusion
Building my first Minecraft Mod was interesting because I got to know a bit more about how my favorite game works, and I even managed to craft something really fun to play.
Also, I took this as an opportunity to create this article because I think modding is a great way to get introduced to programming, and there are a lot of Minecraft players that may get interested and end up learning a lot about software development.
Источник