Майнкрафт — это одна из самых знаменитых игр нашего времени. Над ее созданием и поддержкой трудится команда шведских разработчиков Mojang Java Studios. Исходный код в Майнкрафт в целом держится в секрете, не считая тех наработок, что есть в darknet’е. Однако буквально недавно команда разработчиков опубликовала несколько легальных частей кода под свободной лицензией. Чуть позже остановимся на этом подробнее.
Почему считают, что Майнкрафт — для детей?
Принято считать, что в эту игруиграют в основном дети. Геймплей Майнкрафта состоит из построения собственного мира и защиты от монстров. Так как эта игра в основном популярна у детей, на ее основе создали большой объем обучающих курсов по программированию. Так дети, проходя их, будут обучаться самостоятельно создавать элементы игры или даже прописывать ее сценарий развития.
НравитсяМайнкрафт детям по нескольким простым причинам:
- по своей сути он очень напоминает LEGO, но только в «цифре»;
- фантазия ребенка в игре ничем не ограничена;
- абсолютно свободные действия в игре: ломать, строить, рыть, ходить — легко.
Код Майнкрафта — это Java?
В начале своего создания Minecraft практически на 100% использовал код Java. Это практически единичный случай, когда вся игра создана с помощью всего одного языка. Возможно, из-за этого сам язык программирования Java и приобрел такую популярность, потому что было время, когда мир программирования для многих открывался именно через эту игру. А раз код Майнкрафта — это Java, то многие начинающие программисты и начинали изучать именно этот язык.
Наверно, поэтому большое количество модов для Майнкрафта написаны тоже на Java, что опять же доказывает повышенный интерес как к самой игре, так и к языку, на котором она написана. Но, как известно, время вносит свои коррективы. Буквально до 2017 года все было так, как описано выше, однако, начиная с 17-го года, код базовой версии Minecraft поменялся на С++.
Сделано это для того, чтобы была возможность объединять все версии с разных платформ:
Windows;
Linux;
MacOS;
Android;
iOS.
К сожалению, Java не могла обеспечить работу игры на iOS, поэтому было принято такое решение.
Вот и получается, что код Майнкрафта доступен в двух версиях:
на С++;
на Java Edition.
Где найти исходный код Майнкрафта?
Как мы говорили выше, в целом исходный код Майнкрафта в закрытом доступе. Да, есть какие-то наработки и куски кода от «черных» энтузиастов или от тех, кто декомпилировал исходный код Майнкрафт. То есть конвертировал машинный двоичный код в Java, но, честно говоря, не все образцы были понятны и читаемыми.
Но вот, буквально недавно, были легально опубликованы несколько пакетов кода Java Edition. Найти их можно на GitHub. Они распространяются открыто и со свободной лицензией MIT корпорации Microsoft. В своем составе они представляют две библиотеки Java:
- Brigadier;
- DataFixerUpper.
Эти библиотеки открыли возможность разбивки, отправки, обработки пользовательских команд и данных от новых версий игры.
На этом все не остановится. Как говорят разработчики, в дальнейшем они планируют еще опубликовать в открытом доступе другие библиотеки и куски исходного кода Майнкрафт. Это будет делаться для того, чтобы облегчить разработку других подобных игр и труд разработчиков модификаций.
Библиотека Brigadier
Данная библиотека в основном используется как парсинг и диспетчер команд. Как говорят разработчики, их «Бригадир» может использовать данные (строку кода), которые вводит пользователь, чтобы превратить их в функцию, и уже данную функцию Майнкрафт сможет выполнить. Для пользователей же это обычная консоль, куда можно вводить команды.Команды, правда, нужно вводить на языке Java.
Brigadier делит любую команду пользователя, чтобы проверить ее на ошибки и воспроизвести. Еще обработчик команд старается быть ненавязчивым и полезным, чтобы ускорить ваш процесс. Например, при вводе команд он предложит вам возможные варианты на выбор.
Данной библиотекой пользоваться довольно просто — нужны минимальные знания.
Библиотека DataFixerUpper
Данная библиотека представляет собой набор инструментов, чтобы можно было собрать, склеить и оптимизировать преобразованные данные, которые нужны будут для добавления их в новые версии игры Майнкрафт.
Если простым языком, то этот исходный код Minecraft делает следующее:допустим, вы загружаете какой-нибудь мир в Майнкрафт. И так получилось, что там есть данные, которые не трогались больше 5 лет, потому что вы не посещали эти чанки все эти 5 лет. Так вот, как только игра начинает запускаться, сам Майнкрафт обращается к библиотеке DataFixerEpper, которая приводит чанки к современному формату.
Полностью Java код Майнкрафта пока открывать не будет, хотя у разработчиков были мысли и об этом. Он говорят, что пока исходный код Minecraft будет открываться частями и по запланированному графику.
Мы разрабатываем моды для Minecraft, а значит находимся в очень тесной связи и с ним.
Иногда возникают вопросы вида:
* Как сделать портал?
* Как отловить правый клик по блоку?
* Как добавить описание под названием предмета?
Ответы на подобного вида вопросы ВСЕГДА нужно искать в исходном коде Minecraft. 99% того, что вы хотите создать в своем
моде уже было реализовано в Minecraft. Можно просто посмотреть, как (правильно) сделано в игре, и, на основе готового
примера, сделать что-то свое.
Для этого нам нужно уметь обращаться к исходным кодам и ресурсам (звукам, текстурам, моделям) Minecraft.
Idea#
В Intellij Idea исходники можно найти, открыв в проводнике слева вкладку External Libraries и найдя файл «forgeSrc-версия Minecraft—версия Forge.jar».
Например, в моем случае .jar файл называется так: forgeSrc-1.11.2-13.20.0.2228.jar
.
Откройте его и увидите достаточно много папок:
Eclipse#
В Eclipse действия аналогичные. Вам необходимо открыть в проводнике слева вкладку «Project and External Dependencies», а в ней
найти .jar файл «forgeSrc-версия Minecraft—версия Forge.jar», например forgeSrc-1.11.2-13.20.0.2228.jar
.
Пояснение#
В пакете assets/minecraft
находятся все ресурсы Minecraft: текстуры, JSON описания моделей, файлы локализации и так далее.
Кстати, именно потому что в Minecraft все ресурсы располагаются по пути assets/minecraft
, мы и при разработке модов
в папке resources создаем папку assets/*modid*
. Так как модели самого Minecraft располагаются в папке models
, то и
мы в наших модах создаем папку models
и так далее.
В пакете net.minecraft
находится исходный код игры. Файлов там очень много и именно там находятся ответы на 90%
всех ваших вопросов.
Пример#
Как сделать, чтобы блок взрывался при клике правой кнопкой на нем? Мы знаем, что сундук можно открыть правой кнопкой
мыши. Находим в пакете net.minecraft.block
файл BlockChest.java
.
Там есть следующий кусок кода:
/**
* Called when the block is right clicked by a player.
*/
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
...
}
Вот мы и нашли метод, который надо записать в файле нашего блока. Он будет выполняться, когда по нашему блоку кликнут.
Теперь про взрывы. Отличный пример — TNT. Все в том же пакете ищем файл BlockTNT.java
. Там мы можем найти интересный метод
explode(...)
. Внутри него видим, что при активации TNT он превращается некую сущность entity
под названием EntityTNTPrimed
.
Ищем этот файл в пакете net.minecraft.entity
. Он будет находиться в пакете net.minecraft.entity.item
.
Внутри него видим следующий метод:
private void explode()
{
float f = 4.0F;
this.world.createExplosion(this, this.posX, this.posY + (double)(this.height / 16.0F), this.posZ, 4.0F, true);
}
Строчка this.world.createExplosion(this, this.posX, this.posY + (double)(this.height / 16.0F), this.posZ, 4.0F, true);
как раз
то, что нам нужно!
В нашем блоке BlockTest.java
осталось записать:
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if (!worldIn.isRemote)
{
this.world.createExplosion(this, pos.getX(), pos.getY(), pos.getZ(), 4.0F, true);
}
return true;
}
Итог#
Почти наверняка то, что вы хотите добавить в своем моде уже реализовано в игре в том или ином смысле.
Старайтесь найти примеры в исходном коде и используйте их для реализации своих идей.
К тому же, ориентируясь на исходники игры, вы будете лучше понимать их внутреннюю структуру, что сильно облегчает создание модов.
#1
beefree
-
- Пользователи
- Сообщений: 3
Странник
Написал 08.11.2014 — 08:33
Друзья!
Есть очень важный вопрос для серьёзных программистов разбирающихся в исходном коде minecraft’а.
Возможно ли изменить исходный код игры, добавляя, к примеру:
— новые виды блоковпредметов, и затем натягивать на них новые текстурки (к примеру новые виды руды)
— менять генерацию мира под конкретные цели, увеличивая ширину или глубину мира в блоках. Т.е. изменять заложенные параметры генерации.
— изменять параметры каждого блока предмета.
— Дабавлять новый функционал по типу магии, отличный от существующего в лицензии сервера.
Буду искренне благодарен за расширеный ответ, а так же готов пообщаться на данную тему лично с разбирающимся человеком (даже платно).
- Наверх
#2
DarKShaM
DarKShaM
-
- Модераторы
- Сообщений: 2080
Тонущий в песках душ
-
Ник в Minecraft:
_DarKShaM_ - Откуда: Уфа
Написал 08.11.2014 — 10:45
Моды, не?
Раздел на официальном форуме.
- Наверх
#3
Cyxapuk
Cyxapuk
-
- Главные модераторы
- Сообщений: 8706
-
Ник в Minecraft:
Meegoo
Написал 08.11.2014 — 11:55
Скажу так, редактирование исходников майна не приветствуется в моддинг коммьюнити. Все, что ты перечислил делается через фордж. Если нужен доступ к приватным методамполям, копай в сторону рефлексии. Если собираешься менять в ваниле что-то серьезное, то спасет coremod форджа.
Блокипредметы добавляются за 5 минут, больше половины гайдов моддинга на фордже начинаются именно с этого.
Генерацию умеет менять какой нибудь Alternate Terrain Generation. Как он точно это делает, не знаю.
Если надо поменять что-то типо максимальной высоты мира, то тут уже надо менять формат сейва, а следовательно появятся такие нехилые проблемы с совместимостью. Вообщем в эти дебри лучше не лезть.
Основные параметры любых блоков меняются сменой нужной переменной (например Blocks.planks.setResistance(2000.0F); сделает планки неуязвимыми к тнт). Если поле приватное, то, опять же, рефлексия. Если протектед, то расширяй класс.
Дроп меняется как-то так
@SubscribeEventpublic void onBlockHarvest(HarvestDropsEvent event) {if (event.block == Blocks.blockYouWant) {event.drops.clear(); // remove vanilla dropsevent.drops.add(new ItemStack(Items.itemYouWant));}}
Ну и так далее.
Добавить новый функционал своим блокам не составляет проблем. Так же есть в большинстве гайдов.
Новый функционал ванильным блокам так просто не добавить. Придется перезаписывать ванильный блок своим.
- Наверх
#4
beefree
beefree
-
- Пользователи
- Сообщений: 3
Странник
Написал 08.11.2014 — 12:14
Гигантский респект за обширный ответ.
Очень рад тому, что основные моменты меняются модами и нет необходимости лезть в исходный код.
Сам я в майнкрафте совершенно не разбираюсь и в планах нанять серьёзного человека на полноценную ежемесячную оплату труда (~20-30т.р.), который полностью возьмётся за создание нужного мне мира, а так же будет заниматься поддержкой пользователей.
- Наверх
#5
QWistor
QWistor
-
- Пользователи
- Сообщений: 137
Добытчик дерева
-
Ник в Minecraft:
Azbes - Откуда: Новочебоксарск ЧР
Написал 08.11.2014 — 20:04
Гигантский респект за обширный ответ.
Очень рад тому, что основные моменты меняются модами и нет необходимости лезть в исходный код.
Сам я в майнкрафте совершенно не разбираюсь и в планах нанять серьёзного человека на полноценную ежемесячную оплату труда (~20-30т.р.), который полностью возьмётся за создание нужного мне мира, а так же будет заниматься поддержкой пользователей.
Хочешь создать свою игру на базе этой?
Большие планы строим…
- Наверх
#6
beefree
beefree
-
- Пользователи
- Сообщений: 3
Странник
Написал 09.11.2014 — 08:02
У взрослых людей взрослые планы =)
Собственно да, есть желание открыть сервер совершенно отличный от всего того, что есть на данный момент.
По факту игра останется та же ввиду того, что исходя из вашего ответа, всё строится на модах и в код лезть не придётся.
Самая большая проблема это найти действительно серьёзного профессионала, который будет готов за месяц-два разработать и поставить сервер в рабочее состояние.
- Наверх
#7
Bupyc
Bupyc
-
- Пользователи
- Сообщений: 4
Странник
Написал 11.11.2014 — 18:24
>серьёзного человека на полноценную ежемесячную оплату труда (~20-30т.р.)
>У взрослых людей взрослые планы =)
>серьёзного профессионала
>за месяц-два разработать и поставить сервер в рабочее состояние
Уважаемый взрослый человек! Узнайте цены профессионалов, спросите про сроки. И спуститесь наконец на землю!
Сообщение отредактировал Bupyc: 11.11.2014 — 18:28
- Наверх
by Josh Wulf
Usually, modifying Minecraft requires coding in Java, and a lot of scaffolding. Now you can write and share Minecraft mods using TypeScript/Javascript.
ScriptCraft is an open source JavaScript Minecraft modding library, and we’ve written support for TypeScript, and a bunch of tooling to create a familiar developer experience for those coming from JavaScript land (including Yeoman and NPM).
In this article I’ll walk you through getting set up and building your first TypeScript Minecraft mod in under an hour — as little as 20 minutes, depending on your internet connection.
In this video (click here if the embed doesn’t work above) I show you how to write a basic Minecraft mod using TypeScript, and run it on your local computer with both a desktop and a mobile Minecraft server.
Below, I’ll walk you through the steps, with links to resources.
Prerequisites
You’ll need some software installed on your computer, to run the Minecraft server and the tools for writing your plugin. Install all of the four following:
- Docker — a containerisation solution.
- Node.js — a JavaScript execution engine and library.
- Portainer — a web-based GUI for managing Docker containers.
- Visual Studio Code — a code editor.
Minecraft Client
You need a Minecraft client to test your plugin.
Install at least one of the following:
- Minecraft Java Edition — a desktop client, if you want to test against a Bukkit server.
- Minecraft Pocket Edition — a mobile client, if you want to test against a Nukkit server (phone/tablet/Xbox). If you use this, you can use Minecraft Pocket Edition Bedrock Launcher to run the mobile client on your computer.
Installation
Now that you have the prerequisites installed, it is time to install the tools for the server and for plugin development.
- Run the following command:
npm i -g smac yo generator-sma-plugin typescript
This will install four things on your computer:
smac
— Scriptcraft Modular Architecture Controller, a program that runs Minecraft Servers for your plugins.yo
— Yeoman, a scaffolding tool.generator-sma-plugin
— a Yeoman plugin for generating a new Minecraft plugin using the Scriptcraft Modular Architecture.typescript
— the TypeScript transpiler, for converting TypeScript code into ES5 JavaScript that can run in Minecraft.
Create a new plugin
Now that you have the toolset installed, create a new plugin by running this command:
yo sma-plugin
This starts the plugin wizard:
➜ yo sma-plugin
_-----_ ╭──────────────────────────╮ | | │ Welcome to the │ |--(o)--| │ Scriptcraft SMA Plugin │ `---------´ │ generator by │ ( _´U`_ ) │ Magikcraft.io! │ /___A___ /╰──────────────────────────╯ | ~ | __'.___.'__ ´ ` |° ´ Y `
? Your package name (workspace)
There is only one question you need to answer here — the name of your plugin. The wizard will create a new folder with the name of the plugin, and place the files for the new plugin in it.
This screencast shows you the process:
Scaffold a Minecraft plugin using Magikcraft
Magikcraft.io allows you to write Minecraft plugins in TypeScript/JavaScript that will run on Desktop / Mobile.asciinema.org
Once the wizard completes, it emits a message similar to this (I chose the name my-sma-plugin
in this example):
Edit your new plugin
Start Visual Studio Code and open the directory containing your new plugin.
Here is a description of the files in your new plugin:
__tests__
— a directory containing unit tests for your plugin. These are run with Jasmine. Add more tests in here as you develop your plugin..vscode
— settings for Visual Studio code.autoload
— any files in here are automatically executed when your plugin is enabled in the Minecraft server. Use this for initialisation tasks, registering event handlers, and so forth.lib
— A place for you to put files that should not be automatically loaded (or that are required from your autoloaded files). If your plugin provides functionality to other plugins, then you export that vialib/index.ts
.node_modules
— modules from npm are installed here. You cannot use modules from npm that use V8 APIs (like fs or http). Many of the features that you need are provided by the Scriptcraft API and by the@magikcraft/core
package..editorconfig
— settings for the editor..gitattributes
— settings forgit
..gitignore
— files to ignore forgit
..prettierrc
— settings for code formatting.package-lock.json
—versions of installed dependencies.package.json
—configuration for this plugin, including dependencies and scripts.README.md
— instructions for developing and testing your plugin.smac-nukkit.json
— a configuration for running a Nukkit server with your plugin loaded.smac.json
— a configuration for running a Bukkit server with your plugin loaded.tsconfig.json
— the TypeScript configuration for transpiling your plugin to JavaScript.
Open autoload/index.ts
:
This file is automatically executed when the plugin is loaded. Changes that you make here will be visible when you (re)load the plugin.
Start a development server
You can load your plugin in a development server. There are two servers that you can use — one for the desktop Java client, and the other for the mobile Pocket Edition client.
Start the desktop server
Run this to start a desktop server:
npm run start:bukkit
This will:
- Pull the Bukkit server image from Docker Hub.
- Start the Bukkit server with your plugin loaded.
- Start the TypeScript transpiler to transpile your code to ES5.
You can now connect to the server with your desktop client. Click on Multiplayer
then Direct Connect
, then use the server address 127.0.0.1
:
Start the mobile server
Run this command to start a mobile server:
npm run start:nukkit
This will:
- Pull the Nukkit server image from Docker Hub.
- Start the Nukkit server with your plugin loaded.
- Start the TypeScript transpiler to transpile your code to ES5.
You can now connect to the server with your pocket edition client. Click on Play
then Servers
, then add a server with the address 127.0.0.1
:
Reload changes to your plugin
As you change your plugin and save the changed TypeScript, it will automatically be transpiled to JavaScript.
To reload the changes in the development server, type the following in the server console:
ts onrefresh()
See the screencast below to see what this looks like.
Stop the server
To stop the server, type this command at the server console:
smac stop
See the screencast below to see what it looks like when you run this command.
Screencast: Start, Reload, and Stop
This screencast shows you starting the desktop server, reloading the plugin code, and also stopping the development server.
Start a Magikcraft Development Server
Start a Magikcraft Development Server.asciinema.org
Further Resources
- Magikcraft on GitHub
- Magikcraft on YouTube
- MCT1 Source Code (Example Plugin)
- ScriptCraft on GitHub
- Bukkit API Docs
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
by Josh Wulf
Usually, modifying Minecraft requires coding in Java, and a lot of scaffolding. Now you can write and share Minecraft mods using TypeScript/Javascript.
ScriptCraft is an open source JavaScript Minecraft modding library, and we’ve written support for TypeScript, and a bunch of tooling to create a familiar developer experience for those coming from JavaScript land (including Yeoman and NPM).
In this article I’ll walk you through getting set up and building your first TypeScript Minecraft mod in under an hour — as little as 20 minutes, depending on your internet connection.
In this video (click here if the embed doesn’t work above) I show you how to write a basic Minecraft mod using TypeScript, and run it on your local computer with both a desktop and a mobile Minecraft server.
Below, I’ll walk you through the steps, with links to resources.
Prerequisites
You’ll need some software installed on your computer, to run the Minecraft server and the tools for writing your plugin. Install all of the four following:
- Docker — a containerisation solution.
- Node.js — a JavaScript execution engine and library.
- Portainer — a web-based GUI for managing Docker containers.
- Visual Studio Code — a code editor.
Minecraft Client
You need a Minecraft client to test your plugin.
Install at least one of the following:
- Minecraft Java Edition — a desktop client, if you want to test against a Bukkit server.
- Minecraft Pocket Edition — a mobile client, if you want to test against a Nukkit server (phone/tablet/Xbox). If you use this, you can use Minecraft Pocket Edition Bedrock Launcher to run the mobile client on your computer.
Installation
Now that you have the prerequisites installed, it is time to install the tools for the server and for plugin development.
- Run the following command:
npm i -g smac yo generator-sma-plugin typescript
This will install four things on your computer:
smac
— Scriptcraft Modular Architecture Controller, a program that runs Minecraft Servers for your plugins.yo
— Yeoman, a scaffolding tool.generator-sma-plugin
— a Yeoman plugin for generating a new Minecraft plugin using the Scriptcraft Modular Architecture.typescript
— the TypeScript transpiler, for converting TypeScript code into ES5 JavaScript that can run in Minecraft.
Create a new plugin
Now that you have the toolset installed, create a new plugin by running this command:
yo sma-plugin
This starts the plugin wizard:
➜ yo sma-plugin
_-----_ ╭──────────────────────────╮ | | │ Welcome to the │ |--(o)--| │ Scriptcraft SMA Plugin │ `---------´ │ generator by │ ( _´U`_ ) │ Magikcraft.io! │ /___A___ /╰──────────────────────────╯ | ~ | __'.___.'__ ´ ` |° ´ Y `
? Your package name (workspace)
There is only one question you need to answer here — the name of your plugin. The wizard will create a new folder with the name of the plugin, and place the files for the new plugin in it.
This screencast shows you the process:
Scaffold a Minecraft plugin using Magikcraft
Magikcraft.io allows you to write Minecraft plugins in TypeScript/JavaScript that will run on Desktop / Mobile.asciinema.org
Once the wizard completes, it emits a message similar to this (I chose the name my-sma-plugin
in this example):
Edit your new plugin
Start Visual Studio Code and open the directory containing your new plugin.
Here is a description of the files in your new plugin:
__tests__
— a directory containing unit tests for your plugin. These are run with Jasmine. Add more tests in here as you develop your plugin..vscode
— settings for Visual Studio code.autoload
— any files in here are automatically executed when your plugin is enabled in the Minecraft server. Use this for initialisation tasks, registering event handlers, and so forth.lib
— A place for you to put files that should not be automatically loaded (or that are required from your autoloaded files). If your plugin provides functionality to other plugins, then you export that vialib/index.ts
.node_modules
— modules from npm are installed here. You cannot use modules from npm that use V8 APIs (like fs or http). Many of the features that you need are provided by the Scriptcraft API and by the@magikcraft/core
package..editorconfig
— settings for the editor..gitattributes
— settings forgit
..gitignore
— files to ignore forgit
..prettierrc
— settings for code formatting.package-lock.json
—versions of installed dependencies.package.json
—configuration for this plugin, including dependencies and scripts.README.md
— instructions for developing and testing your plugin.smac-nukkit.json
— a configuration for running a Nukkit server with your plugin loaded.smac.json
— a configuration for running a Bukkit server with your plugin loaded.tsconfig.json
— the TypeScript configuration for transpiling your plugin to JavaScript.
Open autoload/index.ts
:
This file is automatically executed when the plugin is loaded. Changes that you make here will be visible when you (re)load the plugin.
Start a development server
You can load your plugin in a development server. There are two servers that you can use — one for the desktop Java client, and the other for the mobile Pocket Edition client.
Start the desktop server
Run this to start a desktop server:
npm run start:bukkit
This will:
- Pull the Bukkit server image from Docker Hub.
- Start the Bukkit server with your plugin loaded.
- Start the TypeScript transpiler to transpile your code to ES5.
You can now connect to the server with your desktop client. Click on Multiplayer
then Direct Connect
, then use the server address 127.0.0.1
:
Start the mobile server
Run this command to start a mobile server:
npm run start:nukkit
This will:
- Pull the Nukkit server image from Docker Hub.
- Start the Nukkit server with your plugin loaded.
- Start the TypeScript transpiler to transpile your code to ES5.
You can now connect to the server with your pocket edition client. Click on Play
then Servers
, then add a server with the address 127.0.0.1
:
Reload changes to your plugin
As you change your plugin and save the changed TypeScript, it will automatically be transpiled to JavaScript.
To reload the changes in the development server, type the following in the server console:
ts onrefresh()
See the screencast below to see what this looks like.
Stop the server
To stop the server, type this command at the server console:
smac stop
See the screencast below to see what it looks like when you run this command.
Screencast: Start, Reload, and Stop
This screencast shows you starting the desktop server, reloading the plugin code, and also stopping the development server.
Start a Magikcraft Development Server
Start a Magikcraft Development Server.asciinema.org
Further Resources
- Magikcraft on GitHub
- Magikcraft on YouTube
- MCT1 Source Code (Example Plugin)
- ScriptCraft on GitHub
- Bukkit API Docs
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
1.15
NPCs
Java
-
Search
-
Search all Forums
-
Search this Forum
-
Search this Thread
-
-
Tools
-
Jump to Forum
-
-
#1
May 30, 2022
jstastny-
View User Profile
-
View Posts
-
Send Message
- Tree Puncher
- Join Date:
4/3/2021
- Posts:
20
- Member Details
Hello,
I am writing this post regarding an issue I stumbled upon recently. About a week ago, I downloaded a small mod called Villager Names from Natamus for 1.15. As the name of the mod suggests, it generates random names to NPC villagers. It is overall a nice mod, but I noticed one very annoying feature about this mod — it gives female names to the villagers significantly more often than the male ones. I decided to fix this issue, and since I am no stranger to Java coding, it didn’t take me long to figure out, using Java Decompiler, where the problem in the mod code is and how to fix it. The only problem is I can’t find out how to actually edit the original mod code. I tried writing my own modified class file using NetBeans and then replacing the respective file in the mod folder, but it didn’t work since NetBeans refused to compile the modified file. Any ideas? Thanks for reply.
(Note: For those who might think modifiing someone else’s mods is unethical, I am not doing this for any questionable reasons. I have no interest in posting my modified version of the mod, I just want my villages to be more gender balanced.)
-
-
#2
May 30, 2022
You’ll have to use a bytecode editor, not a decompiler, unless you plan on compiling it with the entire mod.
-
#3
May 30, 2022
Depending on what needs to be changed it may be simple to edit the bytecode; for example, until 1.13 I maintained a mod that reverted the changes to cave generation in 1.7, which could be done by simply changing a couple values in the bytecode, which looked like this:
// Decompiled source int i = this.b.nextInt(this.b.nextInt(this.b.nextInt(15) + 1) + 1); if (this.b.nextInt(7) != 0) i = 0; // Bytecode; note that the parameter to nextInt comes before the method call; bipush 15 corresponds to nextInt(15) and bipush 7 corresponds to nextInt(7), and 1.6.4 cave generation uses 40 and 15 respectively bipush 15 invokevirtual java/util/Random/nextInt(I)I iconst_1 iadd invokevirtual java/util/Random/nextInt(I)I iconst_1 iadd invokevirtual java/util/Random/nextInt(I)I istore 7 aload_0 getfield apn/b Ljava/util/Random; bipush 7 invokevirtual java/util/Random/nextInt(I)I
Likewise, if the mod uses a simple random call to determine the chance of a name you can change the value, which may be a float (e.g. nextFloat() < chance) but the same principle applies. More complex edits are much more difficult to do; one thing I once did was to compile the method I wanted to change and copy the bytecode over (this won’t help though if it contains references to Minecraft and/or Forge and/or external libraries, which will error since they can’t be resolved without a proper setup that includes all the necessary libraries).
Note that the first search result for «java bytecode editor» is the one that I used but it was only designed for Java 5 and earlier so be sure you use one designed for newer versions (it apparently does work if the method being edited only contains Java <= 5 bytecode but only simpler methods can be edited).
-
#5
May 31, 2022
jstastny-
View User Profile
-
View Posts
-
Send Message
- Tree Puncher
- Join Date:
4/3/2021
- Posts:
20
- Member Details
Thanks for all replies. Unfortunately, only changing strings won’t be enough in this case. I need to partially rewrite an entire method, including adding two new lists and a new block of code which will randomly choose whether to use male or female name. Is there any software that allows the user to decompile the code, perform nesscasary changes and then recompile it again, or any tutorial how to perform that in the bytecode format?
-
-
#6
Jun 1, 2022
Is there any software that allows the user to decompile the code, perform nesscasary changes and then recompile it again, or any tutorial how to perform that in the bytecode format?
No, you cannot decompile and recompile just that class. You will get compiler linker errors (compiling class not «existing»). Bytecode is the only way, unless you plan on decompiling the entire mod and recompiling it.
If you want to do it in bytecode (assembly) which is the easiest method, TheMasterCaver has already given advice on how to go about doing it (second paragraph).
Another method you could use, I guess, is making your own mod and hijacking that class during runtime with the Sponge Mixin library.
- To post a comment, please login.
Posts Quoted:
Reply
Clear All Quotes
1.15
NPCs
Java
-
Search
-
Search all Forums
-
Search this Forum
-
Search this Thread
-
-
Tools
-
Jump to Forum
-
-
#1
May 30, 2022
jstastny-
View User Profile
-
View Posts
-
Send Message
- Tree Puncher
- Join Date:
4/3/2021
- Posts:
20
- Member Details
Hello,
I am writing this post regarding an issue I stumbled upon recently. About a week ago, I downloaded a small mod called Villager Names from Natamus for 1.15. As the name of the mod suggests, it generates random names to NPC villagers. It is overall a nice mod, but I noticed one very annoying feature about this mod — it gives female names to the villagers significantly more often than the male ones. I decided to fix this issue, and since I am no stranger to Java coding, it didn’t take me long to figure out, using Java Decompiler, where the problem in the mod code is and how to fix it. The only problem is I can’t find out how to actually edit the original mod code. I tried writing my own modified class file using NetBeans and then replacing the respective file in the mod folder, but it didn’t work since NetBeans refused to compile the modified file. Any ideas? Thanks for reply.
(Note: For those who might think modifiing someone else’s mods is unethical, I am not doing this for any questionable reasons. I have no interest in posting my modified version of the mod, I just want my villages to be more gender balanced.)
-
-
#2
May 30, 2022
You’ll have to use a bytecode editor, not a decompiler, unless you plan on compiling it with the entire mod.
-
#3
May 30, 2022
Depending on what needs to be changed it may be simple to edit the bytecode; for example, until 1.13 I maintained a mod that reverted the changes to cave generation in 1.7, which could be done by simply changing a couple values in the bytecode, which looked like this:
// Decompiled source int i = this.b.nextInt(this.b.nextInt(this.b.nextInt(15) + 1) + 1); if (this.b.nextInt(7) != 0) i = 0; // Bytecode; note that the parameter to nextInt comes before the method call; bipush 15 corresponds to nextInt(15) and bipush 7 corresponds to nextInt(7), and 1.6.4 cave generation uses 40 and 15 respectively bipush 15 invokevirtual java/util/Random/nextInt(I)I iconst_1 iadd invokevirtual java/util/Random/nextInt(I)I iconst_1 iadd invokevirtual java/util/Random/nextInt(I)I istore 7 aload_0 getfield apn/b Ljava/util/Random; bipush 7 invokevirtual java/util/Random/nextInt(I)I
Likewise, if the mod uses a simple random call to determine the chance of a name you can change the value, which may be a float (e.g. nextFloat() < chance) but the same principle applies. More complex edits are much more difficult to do; one thing I once did was to compile the method I wanted to change and copy the bytecode over (this won’t help though if it contains references to Minecraft and/or Forge and/or external libraries, which will error since they can’t be resolved without a proper setup that includes all the necessary libraries).
Note that the first search result for «java bytecode editor» is the one that I used but it was only designed for Java 5 and earlier so be sure you use one designed for newer versions (it apparently does work if the method being edited only contains Java <= 5 bytecode but only simpler methods can be edited).
-
#5
May 31, 2022
jstastny-
View User Profile
-
View Posts
-
Send Message
- Tree Puncher
- Join Date:
4/3/2021
- Posts:
20
- Member Details
Thanks for all replies. Unfortunately, only changing strings won’t be enough in this case. I need to partially rewrite an entire method, including adding two new lists and a new block of code which will randomly choose whether to use male or female name. Is there any software that allows the user to decompile the code, perform nesscasary changes and then recompile it again, or any tutorial how to perform that in the bytecode format?
-
-
#6
Jun 1, 2022
Is there any software that allows the user to decompile the code, perform nesscasary changes and then recompile it again, or any tutorial how to perform that in the bytecode format?
No, you cannot decompile and recompile just that class. You will get compiler linker errors (compiling class not «existing»). Bytecode is the only way, unless you plan on decompiling the entire mod and recompiling it.
If you want to do it in bytecode (assembly) which is the easiest method, TheMasterCaver has already given advice on how to go about doing it (second paragraph).
Another method you could use, I guess, is making your own mod and hijacking that class during runtime with the Sponge Mixin library.
- To post a comment, please login.
Posts Quoted:
Reply
Clear All Quotes