Add visual recipe editor and static mob catalog previews

This commit is contained in:
2026-09-08 22:42:54 +03:00
parent 8a62ee0e6f
commit 5a996a5fda
16 changed files with 706 additions and 25 deletions
+19 -1
View File
@@ -6,10 +6,11 @@
## Установка и работа ## Установка и работа
1. Установите `AstraPlusEditor-0.3.3.jar` из `build/libs` в папку `mods` **клиента администратора**. 1. Установите `AstraPlusEditor-0.3.4.jar` из `build/libs` в папку `mods` **клиента администратора**.
Этот JAR не устанавливается на сервер. Для меню мобов требуется серверный **AstraPlus 0.5.0 или новее**. Этот JAR не устанавливается на сервер. Для меню мобов требуется серверный **AstraPlus 0.5.0 или новее**.
Версия протокола редактора остаётся 1; каналы необязательны. Версия протокола редактора остаётся 1; каналы необязательны.
Для вкладки **Зачарования** требуется **AstraPlus 0.5.5**. Для вкладки **Зачарования** требуется **AstraPlus 0.5.5**.
Для вкладки **Рецепты** требуется **AstraPlus 0.5.8**, для котла дополнительно **AstraCauldron 0.2.1**.
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**. 2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
Клавиша переназначается в управлении Minecraft. Клавиша переназначается в управлении Minecraft.
3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы. 3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы.
@@ -23,10 +24,27 @@
Общие параметры мода остаются в `config/astraplus.json`. Каждый предмет и блок сохраняется Общие параметры мода остаются в `config/astraplus.json`. Каждый предмет и блок сохраняется
в своём файле `astraplus/contents/<namespace>/items|blocks/<path>.json` на сервере. в своём файле `astraplus/contents/<namespace>/items|blocks/<path>.json` на сервере.
Тип существующего определения, его ID и постоянный слот блока редактор не меняет. Тип существующего определения, его ID и постоянный слот блока редактор не меняет.
## Рецепты и превью мобов
Во вкладке «Рецепты» выберите рабочий блок и настройте его слоты. Нажатие открывает каталог
с поиском, локализованными названиями, иконками, вариантами зелий и предметами AstraPlus.
Перетаскивание меняет предметы местами, ПКМ очищает слот. Количество результата, время,
опыт, стоимость, вероятность и жидкость настраиваются через «Параметры» согласно выбранному блоку.
Поддерживаются верстак, три печи, костёр, камнерез, кузнечный стол, точило, картографический стол,
ткацкий станок, наковальня, компостница, зельеварка и котёл. Слоты редактируют локальный черновик;
сервер меняется только после «Сохранить». Рецепты находятся в `contents/<namespace>/recipes`.
Список мобов показывает неподвижную миниатюру модели рядом с названием. Собственные модели
используют исходную позу и фиксированный ракурс; сущности без собственной модели показываются
через ванильный рендер. Предпросмотр не создаёт сущностей в игровом мире.
Для нового блока свободный слот назначает сервер. Для нового блока свободный слот назначает сервер.
## Пользовательские зачарования ## Пользовательские зачарования
В 0.3.4 добавлен эффект «Дальность широкого взмаха» для Размаха (AstraPlus 0.5.8).
Значения задаются в блоках, например `1, 2` для двух уровней.
Вкладка **Зачарования** позволяет создавать собственные определения для оружия, брони Вкладка **Зачарования** позволяет создавать собственные определения для оружия, брони
и других предметов. Разделы: уровни/вес/стоимость, допустимые предметы и слоты действия, и других предметов. Разделы: уровни/вес/стоимость, допустимые предметы и слоты действия,
несовместимость, получение и спавн, эффекты. Можно выдать книгу выбранного уровня. несовместимость, получение и спавн, эффекты. Можно выдать книгу выбранного уровня.
+2 -1
View File
@@ -4,7 +4,7 @@ plugins {
} }
group = "online.astradev" group = "online.astradev"
version = "0.3.3" version = "0.3.4"
repositories { mavenCentral() } repositories { mavenCentral() }
dependencies { dependencies {
testImplementation("com.google.code.gson:gson:2.14.0") testImplementation("com.google.code.gson:gson:2.14.0")
@@ -46,6 +46,7 @@ neoForge {
loadedMods.set(setOf(mods.getByName("astrapluseditor"), mods.getByName("astrapluseditor_verify"))) loadedMods.set(setOf(mods.getByName("astrapluseditor"), mods.getByName("astrapluseditor_verify")))
gameDirectory.set(layout.buildDirectory.dir("isolated-editor")) gameDirectory.set(layout.buildDirectory.dir("isolated-editor"))
systemProperty("astrapluseditor.isolatedVerification", "true") systemProperty("astrapluseditor.isolatedVerification", "true")
systemProperty("astrapluseditor.recipeVerification", providers.gradleProperty("recipeVerification").orElse("false").get())
systemProperty("astrapluseditor.enchantmentVerification", providers.gradleProperty("enchantmentVerification").orElse("false").get()) systemProperty("astrapluseditor.enchantmentVerification", providers.gradleProperty("enchantmentVerification").orElse("false").get())
systemProperty("astrapluseditor.networkVerification", providers.gradleProperty("networkVerification").orElse("false").get()) systemProperty("astrapluseditor.networkVerification", providers.gradleProperty("networkVerification").orElse("false").get())
systemProperty("astrapluseditor.mobTransportVerification", providers.gradleProperty("mobTransportVerification").orElse("false").get()) systemProperty("astrapluseditor.mobTransportVerification", providers.gradleProperty("mobTransportVerification").orElse("false").get())
@@ -6,18 +6,18 @@ import com.google.gson.JsonArray;
public final class EnchantmentFields { public final class EnchantmentFields {
public static final Map<String, String> TYPES = Map.of( public static final Map<String, String> TYPES = Map.of(
"damage_bonus", "Бонус урона", "recovery", "Ускорение восстановления", "slow", "Замедление цели", "sweep_reach", "Дальность широкого взмаха", "damage_bonus", "Бонус урона", "recovery", "Ускорение восстановления", "slow", "Замедление цели",
"lifesteal", "Лечение за попадание", "damage_reduction", "Снижение входящего урона", "lifesteal", "Лечение за попадание", "damage_reduction", "Снижение входящего урона",
"hit_effect", "Эффект на цель при попадании", "passive_effect", "Пассивный эффект владельца", "use_effect", "Эффект при использовании"); "hit_effect", "Эффект на цель при попадании", "passive_effect", "Пассивный эффект владельца", "use_effect", "Эффект при использовании");
public static List<FormField> effect(ContentDraft local, List<String> potions) { public static List<FormField> effect(ContentDraft local, List<String> potions) {
String type = local.text("damage_bonus", "type"); String type = local.text("damage_bonus", "type");
var fields = new java.util.ArrayList<FormField>(); var fields = new java.util.ArrayList<FormField>();
boolean potion = type.endsWith("effect"); boolean potion = type.endsWith("effect");
double max = potion ? 255 : type.equals("damage_bonus") ? 10 : 0.9; double max = potion ? 255 : type.equals("damage_bonus") || type.equals("sweep_reach") ? 10 : 0.9;
fields.add(FormField.text("values", "Значения по уровням", potion ? "Усилитель: 0 = I, 1 = II. Через запятую." : "Доли: 0.1 = 10%. Через запятую. Для лечения — доля максимального здоровья.", fields.add(FormField.text("values", "Значения по уровням", type.equals("sweep_reach") ? "Дополнительные блоки по уровням: 1, 2. Действует на широкий взмах." : potion ? "Усилитель: 0 = I, 1 = II. Через запятую." : "Доли: 0.1 = 10%. Через запятую. Для лечения — доля максимального здоровья.",
() -> { var values = local.get("values"); return values.isJsonArray() ? java.util.stream.StreamSupport.stream(values.getAsJsonArray().spliterator(), false).map(v -> v.getAsString()).collect(java.util.stream.Collectors.joining(", ")) : "0.1"; }, () -> { var values = local.get("values"); return values.isJsonArray() ? java.util.stream.StreamSupport.stream(values.getAsJsonArray().spliterator(), false).map(v -> v.getAsString()).collect(java.util.stream.Collectors.joining(", ")) : "0.1"; },
value -> local.set(parseValues(value, max, potion), "values"))); value -> local.set(parseValues(value, max, potion), "values")));
fields.add(DataFields.number(local, "Вероятность", "1 = 100%. Проверяется на каждое срабатывание.", "1", false, 0, 1, "chance")); if (!type.equals("sweep_reach")) fields.add(DataFields.number(local, "Вероятность", "1 = 100%. Проверяется на каждое срабатывание.", "1", false, 0, 1, "chance"));
if (List.of("damage_bonus", "recovery", "slow", "lifesteal", "hit_effect").contains(type)) { if (List.of("damage_bonus", "recovery", "slow", "lifesteal", "hit_effect").contains(type)) {
fields.add(DataFields.number(local, "Минимум целей", "Для восстановления считаются успешные попадания.", "1", true, 1, 100, "minTargets")); fields.add(DataFields.number(local, "Минимум целей", "Для восстановления считаются успешные попадания.", "1", true, 1, 100, "minTargets"));
fields.add(DataFields.bool(local, "Только широкий взмах", false, "sweepOnly")); fields.add(DataFields.bool(local, "Только широкий взмах", false, "sweepOnly"));
@@ -0,0 +1,73 @@
package online.astradev.plus.editor.form;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public final class RecipeDraft {
public record Station(String name, String block, int inputs) {}
public static final Map<String, Station> STATIONS = java.util.Collections.unmodifiableMap(new LinkedHashMap<>(Map.ofEntries(
Map.entry("crafting", new Station("Верстак", "crafting_table", 9)),
Map.entry("smelting", new Station("Печь", "furnace", 1)),
Map.entry("stonecutting", new Station("Камнерез", "stonecutter", 1)),
Map.entry("smithing", new Station("Стол кузнеца", "smithing_table", 3)),
Map.entry("grindstone", new Station("Точило", "grindstone", 2)),
Map.entry("cartography", new Station("Стол картографа", "cartography_table", 2)),
Map.entry("loom", new Station("Ткацкий станок", "loom", 3)),
Map.entry("smoking", new Station("Коптильня", "smoker", 1)),
Map.entry("blasting", new Station("Плавильная печь", "blast_furnace", 1)),
Map.entry("campfire", new Station("Костёр", "campfire", 1)),
Map.entry("anvil", new Station("Наковальня", "anvil", 2)),
Map.entry("composting", new Station("Компостница", "composter", 1)),
Map.entry("brewing", new Station("Зельеварка", "brewing_stand", 2)),
Map.entry("cauldron", new Station("Котёл", "cauldron", 1)))));
public static JsonObject empty() { var slot = new JsonObject(); slot.addProperty("id", ""); slot.addProperty("count", 1); return slot; }
public static ContentDraft create() {
var doc = new JsonObject(); doc.addProperty("id", "astraplus:new_recipe"); doc.addProperty("name", "Новый рецепт");
doc.addProperty("enabled", true); doc.add("result", empty());
var draft = new ContentDraft(doc, "new"); station(draft, "crafting"); return draft;
}
public static void station(ContentDraft draft, String type) {
int count = STATIONS.get(type).inputs(); var inputs = new JsonArray();
var old = draft.get("inputs");
for (int i = 0; i < count; i++) inputs.add(old.isJsonArray() && i < old.getAsJsonArray().size() ? old.getAsJsonArray().get(i).deepCopy() : empty());
draft.set(inputs, "inputs"); draft.string(type, "station");
}
public static JsonObject slot(ContentDraft draft, int index) {
return index < 0 ? draft.get("result").getAsJsonObject() : draft.get("inputs").getAsJsonArray().get(index).getAsJsonObject();
}
public static void slot(ContentDraft draft, int index, JsonObject value) {
var copy = value.deepCopy(); if (index >= 0) copy.addProperty("count", 1);
if (index < 0) draft.set(copy, "result");
else { var inputs = draft.get("inputs").getAsJsonArray(); inputs.set(index, copy); draft.set(inputs, "inputs"); }
}
public static void swap(ContentDraft draft, int from, int to) {
var first = slot(draft, from); var second = slot(draft, to); slot(draft, from, second); slot(draft, to, first);
}
public static List<FormField> fields(ContentDraft draft) {
var fields = new ArrayList<FormField>(); String station = draft.text("crafting", "station");
fields.add(FormField.text("name", "Название", "Название в списке рецептов", () -> draft.text("", "name"), value -> draft.string(value, "name")));
if (!station.equals("composting")) fields.add(FormField.text("result.count", "Количество результата", "От 1 до максимального размера стопки предмета", () -> draft.text("1", "result", "count"), value -> draft.number(value, true, 1, 64, "result", "count")));
fields.add(new FormField("enabled", "Рецепт включён", "Отключённый рецепт сохраняется, но не работает", () -> draft.text("true", "enabled"), value -> draft.bool(Boolean.parseBoolean(value), "enabled"), List.of("true", "false"), true));
if (station.equals("crafting")) fields.add(new FormField("shapeless", "Без формы", "false — расположение важно; true — ингредиенты в любых ячейках", () -> draft.text("false", "shapeless"), value -> draft.bool(Boolean.parseBoolean(value), "shapeless"), List.of("false", "true"), true));
if (List.of("smelting", "blasting", "smoking", "campfire").contains(station)) {
fields.add(number(draft, "time", "Время, тики", "20 тиков = 1 секунда", "200", true, 1, 72000));
fields.add(number(draft, "experience", "Опыт", "Опыт за один результат", "0", false, 0, 1000));
}
if (station.equals("anvil")) fields.add(number(draft, "levels", "Стоимость, уровни", "От 0 до 39 уровней", "1", true, 0, 39));
if (station.equals("grindstone")) fields.add(number(draft, "experience", "Опыт", "Опыт за обработку", "0", true, 0, 1000));
if (station.equals("composting")) fields.add(number(draft, "chance", "Шанс наполнения", "0.3 = 30%; первый слой гарантирован, как в ванилле", "1", false, 0.001, 1));
if (station.equals("cauldron")) {
fields.add(new FormField("liquid", "Содержимое", "Обычный котёл: вода, лава, снег или пустой", () -> draft.text("water", "liquid"), value -> draft.string(value, "liquid"), List.of("water", "lava", "powder_snow", "empty"), true));
fields.add(number(draft, "liquidLevel", "Уровень до обработки", "Пустой: 0; вода/снег: 1–3; лава: 3", "3", true, 0, 3));
fields.add(number(draft, "liquidCost", "Расход жидкости", "Вода/снег: 0–3; лава: 0 или 3", "1", true, 0, 3));
}
return fields;
}
private static FormField number(ContentDraft draft, String key, String label, String hint, String fallback, boolean integer, double min, double max) {
return FormField.text(key, label, hint, () -> draft.text(fallback, key), value -> draft.number(value, integer, min, max, key));
}
}
@@ -25,11 +25,7 @@ public final class ContentBrowserScreen extends EditorScreen {
} }
@Override protected void init() { @Override protected void init() {
int tab = (width - 48) / 4; EditorTabs.add(this, connection, 0);
button("Предметы и блоки", 12, 38, tab, () -> {}).active = false;
button("Мобы", 20 + tab, 38, tab, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, false)));
button("Навыки", 28 + tab * 2, 38, tab, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, true)));
button("Зачарования", 36 + tab * 3, 38, tab, () -> minecraft.gui.setScreen(new EnchantmentBrowserScreen(connection)));
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск"))); var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
search.setMaxLength(256); search.setMaxLength(256);
search.setHint(Component.literal("Найти по имени или namespace:id")); search.setHint(Component.literal("Найти по имени или namespace:id"));
@@ -31,12 +31,14 @@ public final class ContentList extends ObjectSelectionList<ContentList.Row> {
public final class Row extends ObjectSelectionList.Entry<Row> { public final class Row extends ObjectSelectionList.Entry<Row> {
private final String id; private final String id;
private final String selectionId;
private final String name; private final String name;
private final String kind; private final String kind;
private final CatalogIcon icon; private final CatalogIcon icon;
private Row(JsonObject entry) { private Row(JsonObject entry) {
id = entry.get("id").getAsString(); id = entry.get("id").getAsString();
selectionId = entry.has("selectionKey") ? entry.get("selectionKey").getAsString() : id;
name = entry.get("name").getAsString(); name = entry.get("name").getAsString();
kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет"; kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
icon = new CatalogIcon(entry); icon = new CatalogIcon(entry);
@@ -65,7 +67,7 @@ public final class ContentList extends ObjectSelectionList<ContentList.Row> {
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) { @Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return false; if (event.button() != 0) return false;
setSelected(this); setSelected(this);
selected.accept(id); selected.accept(selectionId);
return true; return true;
} }
} }
@@ -0,0 +1,22 @@
package online.astradev.plus.editor.screen;
import net.minecraft.client.Minecraft;
import online.astradev.plus.editor.network.EditorConnection;
final class EditorTabs {
static void add(EditorScreen screen, EditorConnection connection, int selected) {
String[] names = {"Предметы и блоки", "Мобы", "Навыки", "Зачарования", "Рецепты"};
int part = (screen.width - 56) / 5;
for (int index = 0; index < names.length; index++) {
int tab = index;
String label = Minecraft.getInstance().font.plainSubstrByWidth(names[index], Math.max(0, part - 8));
screen.button(label, 12 + index * (part + 8), 38, part, names[index], () -> Minecraft.getInstance().gui.setScreen(switch (tab) {
case 0 -> new ContentBrowserScreen(connection);
case 1 -> new MobBrowserScreen(connection, false);
case 2 -> new MobBrowserScreen(connection, true);
case 3 -> new EnchantmentBrowserScreen(connection);
default -> new RecipeBrowserScreen(connection);
})).active = selected != index;
}
}
}
@@ -18,11 +18,7 @@ public final class EnchantmentBrowserScreen extends EditorScreen {
private int page, pages = 1, delay, generation; private int page, pages = 1, delay, generation;
public EnchantmentBrowserScreen(EditorConnection connection) { super("AstraPlus: зачарования"); this.connection = connection; } public EnchantmentBrowserScreen(EditorConnection connection) { super("AstraPlus: зачарования"); this.connection = connection; }
@Override protected void init() { @Override protected void init() {
int part = (width - 48) / 4; EditorTabs.add(this, connection, 3);
button("Предметы и блоки", 12, 38, part, () -> minecraft.gui.setScreen(new ContentBrowserScreen(connection)));
button("Мобы", 20 + part, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, false)));
button("Навыки", 28 + part * 2, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, true)));
button("Зачарования", 36 + part * 3, 38, part, () -> {}).active = false;
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск"))); var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
search.setMaxLength(256); search.setHint(Component.literal("Название или namespace:id")); search.setValue(query); search.setMaxLength(256); search.setHint(Component.literal("Название или namespace:id")); search.setValue(query);
search.setResponder(value -> { query = value; page = 0; delay = 6; }); search.setResponder(value -> { query = value; page = 0; delay = 6; });
@@ -16,6 +16,7 @@ public final class MobBrowserScreen extends EditorScreen {
private final boolean skill; private final boolean skill;
private final Map<String, String> rows = new LinkedHashMap<>(); private final Map<String, String> rows = new LinkedHashMap<>();
private ChoiceList list; private ChoiceList list;
private MobList mobList;
private net.minecraft.client.gui.components.Button previous, next; private net.minecraft.client.gui.components.Button previous, next;
private String query = ""; private String query = "";
private int page, pages = 1, delay, generation; private int page, pages = 1, delay, generation;
@@ -23,16 +24,15 @@ public final class MobBrowserScreen extends EditorScreen {
super(skill ? "AstraPlus: навыки" : "AstraPlus: мобы"); this.connection = connection; this.skill = skill; super(skill ? "AstraPlus: навыки" : "AstraPlus: мобы"); this.connection = connection; this.skill = skill;
} }
@Override protected void init() { @Override protected void init() {
int part = (width - 48) / 4; EditorTabs.add(this, connection, skill ? 2 : 1);
button("Предметы и блоки", 12, 38, part, () -> minecraft.gui.setScreen(new ContentBrowserScreen(connection)));
button("Мобы", 20 + part, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, false))).active = skill;
button("Навыки", 28 + part * 2, 38, part, () -> minecraft.gui.setScreen(new MobBrowserScreen(connection, true))).active = !skill;
button("Зачарования", 36 + part * 3, 38, part, () -> minecraft.gui.setScreen(new EnchantmentBrowserScreen(connection)));
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск"))); var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
search.setMaxLength(256); search.setHint(Component.literal("Поиск по названию или namespace:id")); search.setValue(query); search.setMaxLength(256); search.setHint(Component.literal("Поиск по названию или namespace:id")); search.setValue(query);
search.setResponder(value -> { query = value; page = 0; delay = 6; }); search.setResponder(value -> { query = value; page = 0; delay = 6; });
if (skill) {
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(26, height - 193), row -> load(rows.get(row)))); list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(26, height - 193), row -> load(rows.get(row))));
list.values(rows.keySet().stream().toList()); list.values(rows.keySet().stream().toList());
} else mobList = addRenderableWidget(new MobList(minecraft, 12, 92, width - 24,
Math.max(52, height - 193), connection, this::load));
button(skill ? "+ Навык" : "+ Моб", 12, height - 94, 130, this::create); button(skill ? "+ Навык" : "+ Моб", 12, height - 94, 130, this::create);
button("Обновить", width - 142, height - 94, 130, this::refresh); button("Обновить", width - 142, height - 94, 130, this::refresh);
previous = button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } }); previous.active = page > 0; previous = button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } }); previous.active = page > 0;
@@ -59,7 +59,8 @@ public final class MobBrowserScreen extends EditorScreen {
} }
page = response.has("page") ? response.get("page").getAsInt() : page; page = response.has("page") ? response.get("page").getAsInt() : page;
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1); pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
list.values(rows.keySet().stream().toList()); if (skill) list.values(rows.keySet().stream().toList());
else mobList.values(response.has("entries") ? response.getAsJsonArray("entries") : new com.google.gson.JsonArray());
previous.active = page > 0; next.active = page + 1 < pages; previous.active = page > 0; next.active = page + 1 < pages;
status("Страница " + (page + 1) + " / " + pages + ". " + (skill ? "Откройте навык, чтобы изучить действия и условия." : "Откройте моба, чтобы изучить модель, поведение и получить яйцо."), false); status("Страница " + (page + 1) + " / " + pages + ". " + (skill ? "Откройте навык, чтобы изучить действия и условия." : "Откройте моба, чтобы изучить модель, поведение и получить яйцо."), false);
}); });
@@ -0,0 +1,129 @@
package online.astradev.plus.editor.screen;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.screens.inventory.InventoryScreen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.LivingEntity;
import online.astradev.plus.editor.client.preview.PreviewModel;
import online.astradev.plus.editor.client.preview.PreviewScene;
import online.astradev.plus.editor.network.EditorConnection;
/** Visible rows load their model lazily; every thumbnail uses a fixed rest pose. */
public final class MobList extends ObjectSelectionList<MobList.Row> {
private static int nextPreviewId = -1;
private final EditorConnection connection;
private final Consumer<String> selected;
private final Map<String, Thumbnail> models = new HashMap<>();
private int pending;
public MobList(Minecraft minecraft, int x, int y, int width, int height,
EditorConnection connection, Consumer<String> selected) {
super(minecraft, width, height, y, 52);
setX(x); this.connection = connection; this.selected = selected;
}
public void values(JsonArray entries) {
clearEntries(); models.clear();
entries.forEach(entry -> addEntry(new Row(entry.getAsJsonObject())));
}
@Override public int getRowWidth() { return width - 16; }
private Thumbnail model(String id) {
Thumbnail thumbnail = models.get(id);
if (thumbnail != null || pending >= 2) return thumbnail;
thumbnail = new Thumbnail(); models.put(id, thumbnail); pending++;
Thumbnail target = thumbnail;
var request = new JsonObject(); request.addProperty("id", id); request.addProperty("animation", "");
connection.request("model_preview", request, response -> {
pending--;
if (models.get(id) != target) return;
target.hint = EditorConnection.message(response);
if (!EditorConnection.success(response)) return;
try {
target.scene = new PreviewScene(PreviewModel.read(response));
target.hint = !target.scene.missing().isEmpty() ? "Модель отсутствует в ресурспаке"
: target.scene.hasGeometry() ? "" : "Модель не содержит отображаемой геометрии";
} catch (RuntimeException error) { target.hint = "Предпросмотр недоступен"; }
});
return thumbnail;
}
private static final class Thumbnail {
private PreviewScene scene;
private String hint = "Загружается модель…";
}
public final class Row extends ObjectSelectionList.Entry<Row> {
private final String id, name, entityId, modelId;
private LivingEntity entity;
private boolean resolved;
private Row(JsonObject entry) {
id = entry.get("id").getAsString();
name = entry.has("name") ? entry.get("name").getAsString() : id;
entityId = entry.has("entity") ? entry.get("entity").getAsString() : "";
modelId = entry.has("models") && !entry.getAsJsonArray("models").isEmpty()
? entry.getAsJsonArray("models").get(0).getAsString() : "";
}
@Override public Component getNarration() { return Component.literal(name + ", " + id); }
@Override public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean hovered, float a) {
int x = getContentX() + 4, y = getContentY();
graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight() - 2,
getSelected() == this ? 0xFF304C53 : hovered ? 0xFF293D46 : 0xFF1B2830);
graphics.fill(x, y + 2, x + 46, y + 48, 0xFF101C23);
String hint = "";
if (!modelId.isEmpty()) {
Thumbnail thumbnail = model(modelId);
if (thumbnail != null && thumbnail.scene != null && thumbnail.scene.hasGeometry() && thumbnail.scene.missing().isEmpty())
thumbnail.scene.extract(graphics, x + 1, y + 3, x + 45, y + 47, 0, 0.65F, -0.15F, 1);
else {
hint = thumbnail == null ? "Загружается модель…" : thumbnail.hint;
graphics.text(minecraft.font, "…", x + 19, y + 21, 0xFF91A6B2);
}
} else {
if (!resolved && minecraft.level != null) {
resolved = true;
Identifier key = Identifier.tryParse(entityId);
if (key != null) BuiltInRegistries.ENTITY_TYPE.getOptional(key).ifPresent(type -> {
var created = type.create(minecraft.level, EntitySpawnReason.COMMAND);
if (created instanceof LivingEntity living) { entity = living; entity.setId(nextPreviewId--); }
});
}
if (entity != null) {
int size = Math.max(1, (int) (34 / Math.max(1, Math.max(entity.getBbHeight(), entity.getBbWidth()))));
InventoryScreen.renderEntityInInventoryFollowsAngle(graphics, x + 1, y + 3, x + 45, y + 47,
size, 0, -0.7F, 0.1F, entity);
} else {
hint = "Предпросмотр этого типа сущности недоступен";
graphics.text(minecraft.font, "?", x + 19, y + 21, 0xFF91A6B2);
}
}
int textX = x + 54, textWidth = Math.max(0, getContentWidth() - 62);
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(name, textWidth), textX, y + 6, 0xFFE5EFF1);
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(id, textWidth), textX, y + 21, 0xFF9AAFB8);
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(entityId, textWidth), textX, y + 35, 0xFF91A6B2);
if (hovered) graphics.setTooltipForNextFrame(minecraft.font,
Component.literal(name + "\n" + id + (hint.isEmpty() ? "" : "\n" + hint)), mouseX, mouseY);
}
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return false;
setSelected(this); selected.accept(id); return true;
}
}
}
@@ -0,0 +1,55 @@
package online.astradev.plus.editor.screen;
import java.util.LinkedHashMap;
import com.google.gson.JsonObject;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.RecipeDraft;
import online.astradev.plus.editor.network.EditorConnection;
public final class RecipeBrowserScreen extends EditorScreen {
private final EditorConnection connection;
private final LinkedHashMap<String, String> rows = new LinkedHashMap<>();
private ChoiceList list;
private int page, pages = 1, delay, generation;
private String query = "";
public RecipeBrowserScreen(EditorConnection connection) { super("AstraPlus: рецепты"); this.connection = connection; }
@Override protected void init() {
EditorTabs.add(this, connection, 4);
var search = addRenderableWidget(new EditBox(font, 12, 66, width - 24, 20, Component.literal("Поиск")));
search.setMaxLength(256); search.setHint(Component.literal("Название или namespace:id")); search.setValue(query);
search.setResponder(value -> { query = value; page = 0; delay = 6; });
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(26, height - 193), label -> load(rows.get(label))));
list.values(rows.keySet().stream().toList());
button("+ Рецепт", 12, height - 94, 120, () -> minecraft.gui.setScreen(new RecipeEditorScreen(this, connection, RecipeDraft.create())));
button("Обновить", width - 132, height - 94, 120, this::refresh);
button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } });
button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } });
button("Закрыть", width - 112, height - 27, 100, this::onClose); refresh();
}
@Override public void tick() { if (delay > 0 && --delay == 0) refresh(); }
private void refresh() {
int current = ++generation; var request = new JsonObject(); request.addProperty("query", query); request.addProperty("page", page);
connection.request("recipe_list", request, response -> {
if (generation != current) return;
if (!EditorConnection.success(response)) { status(EditorConnection.message(response), true); return; }
rows.clear();
for (var value : response.getAsJsonArray("entries")) {
var entry = value.getAsJsonObject(); String id = entry.get("id").getAsString(), station = entry.get("station").getAsString();
rows.put(entry.get("name").getAsString() + " [" + id + "] " + RecipeDraft.STATIONS.get(station).name()
+ (entry.get("enabled").getAsBoolean() ? "" : " (отключён)"), id);
}
page = response.get("page").getAsInt(); pages = response.get("pages").getAsInt(); list.values(rows.keySet().stream().toList());
status("Страница " + (page + 1) + " / " + pages + ". Выберите рецепт или создайте новый.", false);
});
}
private void load(String id) {
var request = new JsonObject(); request.addProperty("id", id);
connection.request("recipe_get", request, response -> {
if (!EditorConnection.success(response)) { status(EditorConnection.message(response), true); return; }
if (minecraft.gui.screen() == this) minecraft.gui.setScreen(new RecipeEditorScreen(this, connection,
new ContentDraft(response.getAsJsonObject("document"), response.get("revision").getAsString())));
});
}
}
@@ -0,0 +1,171 @@
package online.astradev.plus.editor.screen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonObject;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.world.item.ItemStack;
import online.astradev.plus.editor.client.CatalogIcon;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.RecipeDraft;
import online.astradev.plus.editor.network.EditorConnection;
/** Ghost slots edit a draft only. Click selects an item; drag swaps slots; right-click clears. */
public final class RecipeEditorScreen extends EditorScreen {
private record Cell(int index, int x, int y, String label) {}
private final Screen parent;
private final EditorConnection connection;
private final ContentDraft draft;
private final List<Cell> cells = new ArrayList<>();
private final Map<String, CatalogIcon> icons = new HashMap<>();
private final Set<String> requested = new HashSet<>();
private int pending, pressed = -2;
private double pressX, pressY;
private boolean dragging, saving;
public RecipeEditorScreen(Screen parent, EditorConnection connection, ContentDraft draft) {
super("AstraPlus: редактор рецепта"); this.parent = parent; this.connection = connection; this.draft = draft;
}
@Override protected void init() {
pressed = -2; dragging = false;
var id = addRenderableWidget(new EditBox(font, 12, 40, width - 24, 20, Component.literal("ID рецепта")));
id.setMaxLength(256); id.setValue(draft.id()); id.setEditable(draft.fresh()); id.setResponder(value -> draft.string(value, "id"));
String station = draft.text("crafting", "station");
button(RecipeDraft.STATIONS.get(station).name() + "…", 12, 68, Math.max(90, (width - 32) / 2), () -> {
var names = RecipeDraft.STATIONS.values().stream().map(RecipeDraft.Station::name).sorted().toList();
minecraft.gui.setScreen(new ChoiceScreen(this, "Блок рецепта", names, name -> {
RecipeDraft.STATIONS.entrySet().stream().filter(e -> e.getValue().name().equals(name)).findFirst().ifPresent(e -> RecipeDraft.station(draft, e.getKey()));
}));
});
button("Параметры…", 20 + (width - 32) / 2, 68, (width - 32) / 2, () -> minecraft.gui.setScreen(new SettingsScreen(this,
"Параметры рецепта", draft.document(), RecipeDraft::fields, draft::replace, List.of(), "Настройки относятся только к выбранному блоку.")));
layout();
button("Сохранить", 12, height - 27, 100, this::save).active = !saving;
button("Назад", width - 112, height - 27, 100, this::onClose);
}
private void layout() {
cells.clear(); int x = width / 2 - 90, y = height < 300 ? 99 : 117; String station = draft.text("crafting", "station");
switch (station) {
case "crafting" -> { for (int i = 0; i < 9; i++) cells.add(new Cell(i, x + (i % 3) * 24, y + (i / 3) * 24, "Ингредиент " + (i + 1))); }
case "smithing" -> { for (int i = 0; i < 3; i++) cells.add(new Cell(i, x + i * 30, y + 24, List.of("Шаблон", "Основа", "Добавка").get(i))); }
case "loom" -> {
cells.add(new Cell(0, x + 15, y + 12, "Знамя")); cells.add(new Cell(1, x + 45, y + 12, "Краситель"));
cells.add(new Cell(2, x + 30, y + 42, "Узор, не расходуется"));
}
case "brewing" -> {
cells.add(new Cell(1, x + 30, y, "Добавка"));
for (int i = 0; i < 3; i++) cells.add(new Cell(0, x + i * 30, y + 42 + (i == 1 ? 5 : 0), "Основа зелья — одинаковый рецепт для каждой бутылки"));
}
case "anvil" -> { cells.add(new Cell(0, x, y + 24, "Левый предмет")); cells.add(new Cell(1, x + 60, y + 24, "Правый предмет")); }
case "grindstone", "cartography" -> { cells.add(new Cell(0, x + 30, y, "Основной предмет")); cells.add(new Cell(1, x + 30, y + 42, "Дополнительный предмет")); }
default -> cells.add(new Cell(0, x + 30, y + 12, "Ингредиент"));
}
if (!station.equals("composting")) cells.add(new Cell(-1, x + 144, y + 24, "Результат"));
}
private CatalogIcon icon(JsonObject slot) {
String id = slot.get("id").getAsString(); if (id.isEmpty()) return null;
String key = slot.toString();
if (icons.containsKey(key)) return icons.get(key);
if (BuiltInRegistries.ITEM.containsKey(Identifier.parse(id))) {
var row = new JsonObject(); row.addProperty("id", id); row.addProperty("material", id); row.add("icon", slot.deepCopy());
var icon = new CatalogIcon(row); icons.put(key, icon); return icon;
}
if (pending < 2 && requested.add(id)) {
pending++; var request = new JsonObject(); request.addProperty("query", id);
connection.request("list", request, response -> {
pending--;
if (EditorConnection.success(response)) for (var row : response.getAsJsonArray("entries"))
if (row.getAsJsonObject().get("id").getAsString().equals(id)) icons.put(id, new CatalogIcon(row.getAsJsonObject()));
});
}
return icons.get(id);
}
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a);
String station = draft.text("crafting", "station"); int x = width / 2 - 90;
int shift = height < 300 ? -18 : 0;
if (height >= 300) graphics.text(font, font.plainSubstrByWidth(draft.text("Новый рецепт", "name"), width - 24), 12, 99, 0xFFE0F4F4);
graphics.fill(x - 12, 111 + shift, x + 180, 193 + shift, 0xFF24343D);
graphics.text(font, "→", x + 111, 149 + shift, 0xFFE0F4F4);
for (Cell cell : cells) {
boolean hovered = contains(cell, mouseX, mouseY);
graphics.fill(cell.x, cell.y, cell.x + 22, cell.y + 22, hovered ? 0xFF8AA9AD : 0xFF64747A);
graphics.fill(cell.x + 1, cell.y + 1, cell.x + 21, cell.y + 21, 0xFF101C23);
var slot = RecipeDraft.slot(draft, cell.index); var icon = icon(slot);
if (icon != null) {
graphics.item(icon.stack(), cell.x + 3, cell.y + 3);
int count = slot.has("count") ? slot.get("count").getAsInt() : 1;
if (count > 1) graphics.text(font, String.valueOf(count), cell.x + 13, cell.y + 14, 0xFFFFFFFF);
}
if (hovered && !dragging) graphics.setTooltipForNextFrame(font, Component.literal(cell.label + "\n"
+ (icon == null ? "Пустой слот" : icon.stack().getHoverName().getString()) + "\nНажать — выбрать; тянуть — переместить; ПКМ — очистить"), mouseX, mouseY);
}
if (List.of("smelting", "smoking", "blasting", "brewing").contains(station)) {
var fuel = new ItemStack(station.equals("brewing") ? net.minecraft.world.item.Items.BLAZE_POWDER : net.minecraft.world.item.Items.COAL);
graphics.item(fuel, x - 5, 169 + shift);
}
if (station.equals("composting")) graphics.item(new ItemStack(net.minecraft.world.item.Items.BONE_MEAL), x + 146, 143 + shift);
if (height >= 300) graphics.text(font, font.plainSubstrByWidth(hint(station), width - 24), 12, 203, 0xFF9AAFB8);
if (dragging && pressed != -2) { var icon = icon(RecipeDraft.slot(draft, pressed)); if (icon != null) graphics.item(icon.stack(), mouseX - 8, mouseY - 8); }
}
private String hint(String station) {
return switch (station) {
case "smelting", "smoking", "blasting" -> "Топливо — ванильное. Время и опыт — в параметрах.";
case "brewing" -> "3 бутылки, огненный порошок, 20 секунд. Результат — для каждой бутылки.";
case "composting" -> "Предмет → слой компоста. Шанс — в параметрах. Выход — костная мука.";
case "cauldron" -> "Содержимое, уровень и расход жидкости — в параметрах.";
case "loom" -> "Знамя + краситель; узор при необходимости. Узор не расходуется.";
default -> "Нажмите слот для выбора предмета или перетащите предмет между слотами.";
};
}
private boolean contains(Cell cell, double x, double y) { return x >= cell.x && x < cell.x + 22 && y >= cell.y && y < cell.y + 22; }
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
for (Cell cell : cells) if (contains(cell, event.x(), event.y())) {
if (event.button() == 1) { RecipeDraft.slot(draft, cell.index, RecipeDraft.empty()); return true; }
if (event.button() == 0) { pressed = cell.index; pressX = event.x(); pressY = event.y(); dragging = false; return true; }
}
return super.mouseClicked(event, doubleClick);
}
@Override public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) {
if (pressed != -2) { dragging |= Math.hypot(event.x() - pressX, event.y() - pressY) > 3; return true; }
return super.mouseDragged(event, dx, dy);
}
@Override public boolean mouseReleased(MouseButtonEvent event) {
if (pressed != -2) {
int source = pressed; pressed = -2;
for (Cell target : cells) if (contains(target, event.x(), event.y())) {
if (dragging && source != target.index) RecipeDraft.swap(draft, source, target.index);
else if (!dragging && source == target.index) minecraft.gui.setScreen(new RecipeItemPicker(this, connection, row -> {
var selection = row.getAsJsonObject("selection"); RecipeDraft.slot(draft, source, selection);
icons.put(selection.get("id").getAsString(), new CatalogIcon(row));
}));
break;
}
dragging = false; return true;
}
return super.mouseReleased(event);
}
private void save() {
if (saving) return;
saving = true; var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("revision", draft.revision()); request.add("document", draft.document());
connection.request("recipe_save", request, response -> {
saving = false;
if (EditorConnection.success(response)) draft.saved(response.getAsJsonObject("document"), response.get("revision").getAsString());
status(EditorConnection.message(response), !EditorConnection.success(response)); rebuildWidgets();
});
}
@Override public void onClose() {
if (draft.dirty()) minecraft.gui.setScreen(new ConfirmScreen(yes -> minecraft.gui.setScreen(yes ? parent : this), Component.literal("Закрыть без сохранения?"), Component.literal("Изменения рецепта останутся несохранёнными.")));
else minecraft.gui.setScreen(parent);
}
}
@@ -0,0 +1,97 @@
package online.astradev.plus.editor.screen;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.serialization.JsonOps;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.RegistryOps;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.alchemy.PotionContents;
import online.astradev.plus.editor.network.EditorConnection;
/** Localized vanilla items and potion variants plus paged server-owned custom items. */
public final class RecipeItemPicker extends EditorScreen {
private final Screen parent;
private final EditorConnection connection;
private final Consumer<JsonObject> selected;
private final List<JsonObject> vanilla = new ArrayList<>();
private final Map<String, JsonObject> shown = new LinkedHashMap<>();
private ContentList list;
private String query = "";
private int page, pages = 1, delay, generation;
public RecipeItemPicker(Screen parent, EditorConnection connection, Consumer<JsonObject> selected) {
super("Выбор предмета для слота"); this.parent = parent; this.connection = connection; this.selected = selected;
}
@Override protected void init() {
if (vanilla.isEmpty()) {
for (var item : BuiltInRegistries.ITEM) if (item != Items.AIR) vanilla.add(entry(new ItemStack(item)));
if (minecraft.level != null) for (var potion : minecraft.level.registryAccess().lookupOrThrow(Registries.POTION).listElements().toList()) {
for (var item : List.of(Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION, Items.TIPPED_ARROW)) {
var stack = new ItemStack(item); stack.set(DataComponents.POTION_CONTENTS, new PotionContents(potion)); vanilla.add(entry(stack));
}
}
}
var search = addRenderableWidget(new EditBox(font, 12, 40, width - 24, 20, Component.literal("Поиск")));
search.setHint(Component.literal("Название или namespace:id")); search.setMaxLength(256); search.setValue(query);
search.setResponder(value -> { query = value; page = 0; delay = 5; });
list = addRenderableWidget(new ContentList(minecraft, 12, 66, width - 24, Math.max(36, height - 136), id -> {
selected.accept(shown.get(id).deepCopy()); minecraft.gui.setScreen(parent);
}));
button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } });
button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } });
button("Отмена", width - 112, height - 27, 100, this::onClose); refresh();
}
private JsonObject entry(ItemStack stack) {
String id = BuiltInRegistries.ITEM.getKey(stack.getItem()).toString();
var row = new JsonObject(); row.addProperty("id", id); row.addProperty("name", stack.getHoverName().getString());
row.addProperty("kind", "item"); row.addProperty("material", id);
var selection = new JsonObject(); selection.addProperty("id", id); selection.addProperty("count", 1);
if (minecraft.level != null) {
var encoded = ItemStack.CODEC.encodeStart(RegistryOps.create(JsonOps.INSTANCE, minecraft.level.registryAccess()), stack).getOrThrow().getAsJsonObject();
row.add("icon", encoded); if (encoded.has("components")) selection.add("components", encoded.get("components").deepCopy());
}
row.add("selection", selection); return row;
}
@Override public void tick() { if (delay > 0 && --delay == 0) refresh(); }
private void refresh() {
int current = ++generation;
String needle = query.toLowerCase(Locale.ROOT);
var matches = vanilla.stream().filter(e -> e.get("id").getAsString().contains(needle) || e.get("name").getAsString().toLowerCase(Locale.ROOT).contains(needle)).toList();
var local = new JsonArray();
int localPages = Math.max(1, (matches.size() + 79) / 80);
for (int i = page * 80; i < Math.min(matches.size(), (page + 1) * 80); i++) local.add(matches.get(i).deepCopy());
show(local, localPages);
var request = new JsonObject(); request.addProperty("query", query); request.addProperty("page", page);
connection.request("list", request, response -> {
if (generation != current || minecraft.gui.screen() != this) return;
if (!EditorConnection.success(response)) { status(EditorConnection.message(response), true); return; }
int customPages = response.get("pages").getAsInt();
if (page < customPages) for (var value : response.getAsJsonArray("entries")) {
var row = value.getAsJsonObject().deepCopy(); var selection = new JsonObject();
selection.add("id", row.get("id")); selection.addProperty("count", 1); row.add("selection", selection); local.add(row);
}
show(local, Math.max(localPages, customPages));
});
}
private void show(JsonArray rows, int pages) {
this.pages = pages; shown.clear(); var display = new JsonArray(); int index = 0;
for (var value : rows) {
var row = value.getAsJsonObject(); String key = "selection:" + index++;
shown.put(key, row); var copy = row.deepCopy(); copy.addProperty("selectionKey", key); display.add(copy);
}
list.values(display); status("Страница " + (page + 1) + " / " + pages + ". Нажмите на предмет, чтобы выбрать.", false);
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -0,0 +1,24 @@
package online.astradev.plus.editor.form;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
final class RecipeDraftTest {
@Test void draggingPreservesComponentsAndStationChangesPreserveOtherSettings() {
var draft = RecipeDraft.create(); var item = RecipeDraft.empty(); item.addProperty("id", "minecraft:potion");
var components = new com.google.gson.JsonObject(); var contents = new com.google.gson.JsonObject(); contents.addProperty("potion", "minecraft:healing");
components.add("minecraft:potion_contents", contents); item.add("components", components); RecipeDraft.slot(draft, 0, item);
RecipeDraft.swap(draft, 0, 8);
assertEquals(item, RecipeDraft.slot(draft, 8)); assertEquals("", RecipeDraft.slot(draft, 0).get("id").getAsString());
draft.string("keep", "future"); RecipeDraft.station(draft, "smithing");
assertEquals(3, draft.get("inputs").getAsJsonArray().size()); assertEquals("keep", draft.text("", "future"));
}
@Test void allFourteenWorkstationsHaveUsableDraftSlots() {
assertEquals(14, RecipeDraft.STATIONS.size());
for (var station : RecipeDraft.STATIONS.entrySet()) {
var draft = RecipeDraft.create(); RecipeDraft.station(draft, station.getKey());
assertEquals(station.getValue().inputs(), draft.get("inputs").getAsJsonArray().size());
assertFalse(RecipeDraft.fields(draft).isEmpty());
}
}
}
@@ -44,6 +44,7 @@ public final class EditorVerification {
private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null; private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null;
private final IconVerification icons = Boolean.getBoolean("astrapluseditor.iconVerification") ? new IconVerification() : null; private final IconVerification icons = Boolean.getBoolean("astrapluseditor.iconVerification") ? new IconVerification() : null;
private final EnchantmentGuiVerification enchantments = Boolean.getBoolean("astrapluseditor.enchantmentVerification") ? new EnchantmentGuiVerification() : null; private final EnchantmentGuiVerification enchantments = Boolean.getBoolean("astrapluseditor.enchantmentVerification") ? new EnchantmentGuiVerification() : null;
private final RecipeGuiVerification recipes = Boolean.getBoolean("astrapluseditor.recipeVerification") ? new RecipeGuiVerification() : null;
public EditorVerification() { public EditorVerification() {
if (!Boolean.getBoolean("astrapluseditor.isolatedVerification")) if (!Boolean.getBoolean("astrapluseditor.isolatedVerification"))
@@ -52,6 +53,7 @@ public final class EditorVerification {
} }
private void tick(ClientTickEvent.Post event) { private void tick(ClientTickEvent.Post event) {
if (recipes != null) { recipes.tick(); return; }
if (enchantments != null) { enchantments.tick(); return; } if (enchantments != null) { enchantments.tick(); return; }
if (icons != null) { icons.tick(); return; } if (icons != null) { icons.tick(); return; }
if (network != null) { network.tick(); return; } if (network != null) { network.tick(); return; }
@@ -0,0 +1,94 @@
package online.astradev.plus.editor.verification;
import java.nio.file.Files;
import java.util.List;
import com.google.gson.JsonObject;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Screenshot;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.screens.ConnectScreen;
import net.minecraft.client.gui.screens.DisconnectedScreen;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.multiplayer.resolver.ServerAddress;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import online.astradev.plus.editor.form.ContentDraft;
import online.astradev.plus.editor.form.RecipeDraft;
import online.astradev.plus.editor.network.EditorConnection;
import online.astradev.plus.editor.screen.*;
import org.lwjgl.glfw.GLFW;
/** Captures actual workstation layouts and mob thumbnails, exercising click and drag with a live client. */
public final class RecipeGuiVerification {
private final long start = System.nanoTime();
private boolean connected, finished;
private int tick, captures, phase;
private final List<String> stations = RecipeDraft.STATIONS.keySet().stream().sorted().toList();
private ContentDraft draft;
private RecipeEditorScreen editor;
public void tick() {
if (finished) return;
var mc = Minecraft.getInstance();
try {
if (System.nanoTime() - start > 180_000_000_000L) throw new IllegalStateException("GUI verification timed out, phase " + phase);
if (!connected) {
if (!mc.isGameLoadFinished() || mc.gui.overlay() != null) return;
connected = true; GLFW.glfwHideWindow(mc.getWindow().handle()); mc.options.pauseOnLostFocus = false;
mc.options.guiScale().set(2); mc.resizeGui();
String address = "127.0.0.1:26702";
ConnectScreen.startConnecting(mc.gui.screen(), mc, ServerAddress.parseString(address), new ServerData("Recipe verification", address, ServerData.Type.OTHER), false, null);
return;
}
if (mc.gui.screen() instanceof DisconnectedScreen) throw new IllegalStateException("Disconnected");
if (mc.player == null || !EditorConnection.INSTANCE.available()) return;
mc.gui.toastManager().clear();
if (++tick % 20 != 0) return;
if (phase < stations.size() * 2) {
String station = stations.get(phase / 2);
if (phase % 2 == 0) {
draft = RecipeDraft.create(); RecipeDraft.station(draft, station);
for (int i = 0; i < RecipeDraft.STATIONS.get(station).inputs(); i++) {
var slot = RecipeDraft.empty(); slot.addProperty("id", i % 2 == 0 ? "minecraft:diamond" : "minecraft:iron_ingot"); RecipeDraft.slot(draft, i, slot);
}
var output = RecipeDraft.empty(); output.addProperty("id", "minecraft:netherite_sword"); RecipeDraft.slot(draft, -1, output);
editor = new RecipeEditorScreen(new RecipeBrowserScreen(EditorConnection.INSTANCE), EditorConnection.INSTANCE, draft); mc.gui.setScreen(editor);
} else capture("recipe-" + station + ".png");
phase++; return;
}
switch (phase++ - stations.size() * 2) {
case 0 -> {
RecipeDraft.station(draft, "crafting"); mc.gui.setScreen(editor);
var first = RecipeDraft.empty(); first.addProperty("id", "minecraft:diamond"); RecipeDraft.slot(draft, 0, first);
var second = RecipeDraft.empty(); second.addProperty("id", "minecraft:iron_ingot"); RecipeDraft.slot(draft, 1, second);
int x = editor.width / 2 - 90 + 8, y = 125;
editor.mouseClicked(mouse(x, y, 0), false); editor.mouseDragged(mouse(x + 24, y, 0), 24, 0); editor.mouseReleased(mouse(x + 24, y, 0));
if (!RecipeDraft.slot(draft, 1).get("id").getAsString().equals("minecraft:diamond")) throw new IllegalStateException("Drag did not swap slots");
editor.mouseClicked(mouse(x, y, 1), false);
if (!RecipeDraft.slot(draft, 0).get("id").getAsString().isEmpty()) throw new IllegalStateException("Right-click did not clear slot");
editor.mouseClicked(mouse(x, y, 0), false); editor.mouseReleased(mouse(x, y, 0));
if (!(mc.gui.screen() instanceof RecipeItemPicker)) throw new IllegalStateException("Click did not open item picker");
}
case 1 -> capture("recipe-item-picker.png");
case 2 -> { mc.options.guiScale().set(3); mc.resizeGui(); mc.gui.setScreen(editor); }
case 3 -> capture("recipe-small.png");
case 4 -> { mc.options.guiScale().set(2); mc.resizeGui(); mc.gui.setScreen(new MobBrowserScreen(EditorConnection.INSTANCE, false)); }
case 5, 6, 7 -> { }
case 8 -> capture("mob-list-static-a.png");
case 9 -> capture("mob-list-static-b.png");
case 10 -> { if (captures != 18) throw new IllegalStateException("Incomplete screenshots: " + captures); finish("PASS: 14 workstation layouts, picker, drag, clear, compact view, two static mob frames"); }
default -> { }
}
} catch (Exception error) { finish("FAIL: " + error); }
}
private static MouseButtonEvent mouse(int x, int y, int button) { return new MouseButtonEvent(x, y, new MouseButtonInfo(button, 0)); }
private void capture(String name) {
var mc = Minecraft.getInstance(); var screen = mc.gui.screen();
for (var child : screen.children()) if (child instanceof AbstractWidget w && (w.getX() < 0 || w.getY() < 0 || w.getX() + w.getWidth() > screen.width || w.getY() + w.getHeight() > screen.height)) throw new IllegalStateException("Widget outside screen");
Screenshot.grab(mc.gameDirectory, name, mc.gameRenderer.mainRenderTarget(), 1, ignored -> captures++);
}
private void finish(String result) {
finished = true; var mc = Minecraft.getInstance();
try { Files.writeString(mc.gameDirectory.toPath().resolve("recipe-gui-result.txt"), result); } catch (Exception error) { throw new IllegalStateException(error); }
mc.stop();
}
}