Use native recipe backgrounds, inline settings, station icons and slot quantities

This commit is contained in:
2026-09-08 23:13:46 +03:00
parent 5a996a5fda
commit 137ed4cbb0
7 changed files with 230 additions and 47 deletions
+14 -3
View File
@@ -6,11 +6,11 @@
## Установка и работа ## Установка и работа
1. Установите `AstraPlusEditor-0.3.4.jar` из `build/libs` в папку `mods` **клиента администратора**. 1. Установите `AstraPlusEditor-0.3.5.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**. Для количества ингредиентов и параметров варки требуется **AstraPlus 0.5.9**, для котла дополнительно **AstraCauldron 0.2.2**.
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**. 2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
Клавиша переназначается в управлении Minecraft. Клавиша переназначается в управлении Minecraft.
3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы. 3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы.
@@ -30,7 +30,18 @@
Во вкладке «Рецепты» выберите рабочий блок и настройте его слоты. Нажатие открывает каталог Во вкладке «Рецепты» выберите рабочий блок и настройте его слоты. Нажатие открывает каталог
с поиском, локализованными названиями, иконками, вариантами зелий и предметами AstraPlus. с поиском, локализованными названиями, иконками, вариантами зелий и предметами AstraPlus.
Перетаскивание меняет предметы местами, ПКМ очищает слот. Количество результата, время, Перетаскивание меняет предметы местами, ПКМ очищает слот. Количество результата, время,
опыт, стоимость, вероятность и жидкость настраиваются через «Параметры» согласно выбранному блоку. опыт, стоимость, вероятность и жидкость настраиваются справа от схемы на том же экране.
На небольшом экране параметры переключаются стрелками без открытия отдельного окна.
Тип рабочего блока выбирается в каталоге с иконками. Топливо и выход компостницы имеют
собственные неподвижные слоты с поясняющими подсказками.
Используются родные фоны окон Minecraft. У блоков без окна показана схема с иконкой блока.
Количество выбранного входного слота задаётся под схемой и отображается в правом нижнем углу
иконки, включая единицу. Сервер проверяет и списывает заданное количество за каждый рецепт.
У зельеварки отдельно задаются время в тиках и порошок на варку до трёх бутылок. Ноль порошка
сохраняет ванильный режим (один порошок на 20 варок); положительное число — целые предметы
порошка на одну варку. При разных рецептах бутылок берутся наибольшие время и расход.
Бутылочный слот вмещает одну бутылку. Порция компостирования больше одного предмета
работает при ручной подаче; ванильная воронка подаёт предметы по одному.
Поддерживаются верстак, три печи, костёр, камнерез, кузнечный стол, точило, картографический стол, Поддерживаются верстак, три печи, костёр, камнерез, кузнечный стол, точило, картографический стол,
ткацкий станок, наковальня, компостница, зельеварка и котёл. Слоты редактируют локальный черновик; ткацкий станок, наковальня, компостница, зельеварка и котёл. Слоты редактируют локальный черновик;
сервер меняется только после «Сохранить». Рецепты находятся в `contents/<namespace>/recipes`. сервер меняется только после «Сохранить». Рецепты находятся в `contents/<namespace>/recipes`.
+1 -1
View File
@@ -4,7 +4,7 @@ plugins {
} }
group = "online.astradev" group = "online.astradev"
version = "0.3.4" version = "0.3.5"
repositories { mavenCentral() } repositories { mavenCentral() }
dependencies { dependencies {
testImplementation("com.google.code.gson:gson:2.14.0") testImplementation("com.google.code.gson:gson:2.14.0")
@@ -40,7 +40,7 @@ public final class RecipeDraft {
return index < 0 ? draft.get("result").getAsJsonObject() : draft.get("inputs").getAsJsonArray().get(index).getAsJsonObject(); return index < 0 ? draft.get("result").getAsJsonObject() : draft.get("inputs").getAsJsonArray().get(index).getAsJsonObject();
} }
public static void slot(ContentDraft draft, int index, JsonObject value) { public static void slot(ContentDraft draft, int index, JsonObject value) {
var copy = value.deepCopy(); if (index >= 0) copy.addProperty("count", 1); var copy = value.deepCopy();
if (index < 0) draft.set(copy, "result"); if (index < 0) draft.set(copy, "result");
else { var inputs = draft.get("inputs").getAsJsonArray(); inputs.set(index, copy); draft.set(inputs, "inputs"); } else { var inputs = draft.get("inputs").getAsJsonArray(); inputs.set(index, copy); draft.set(inputs, "inputs"); }
} }
@@ -58,6 +58,10 @@ public final class RecipeDraft {
fields.add(number(draft, "experience", "Опыт", "Опыт за один результат", "0", false, 0, 1000)); 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("anvil")) fields.add(number(draft, "levels", "Стоимость, уровни", "От 0 до 39 уровней", "1", true, 0, 39));
if (station.equals("brewing")) {
fields.add(number(draft, "brewingTime", "Время варки, тики", "20 тиков = 1 секунда; для нескольких рецептов за варку берётся наибольшее время", "400", true, 1, 32767));
fields.add(number(draft, "brewingPowder", "Огненный порошок, шт.", "На одну варку до трёх бутылок; наибольший расход среди рецептов. 0 — ванильное топливо: 20 варок на порошок", "0", true, 0, 64));
}
if (station.equals("grindstone")) fields.add(number(draft, "experience", "Опыт", "Опыт за обработку", "0", true, 0, 1000)); 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("composting")) fields.add(number(draft, "chance", "Шанс наполнения", "0.3 = 30%; первый слой гарантирован, как в ванилле", "1", false, 0.001, 1));
if (station.equals("cauldron")) { if (station.equals("cauldron")) {
@@ -24,10 +24,17 @@ import online.astradev.plus.editor.network.EditorConnection;
/** Ghost slots edit a draft only. Click selects an item; drag swaps slots; right-click clears. */ /** Ghost slots edit a draft only. Click selects an item; drag swaps slots; right-click clears. */
public final class RecipeEditorScreen extends EditorScreen { public final class RecipeEditorScreen extends EditorScreen {
private record Cell(int index, int x, int y, String label) {} private record Cell(int index, int x, int y, String label) {}
private record Decoration(ItemStack stack, int x, int y, String label) {}
private record Label(String text, int x, int y, int width) {}
private final Screen parent; private final Screen parent;
private final EditorConnection connection; private final EditorConnection connection;
private final ContentDraft draft; private final ContentDraft draft;
private final List<Cell> cells = new ArrayList<>(); private final List<Cell> cells = new ArrayList<>();
private final List<Decoration> decorations = new ArrayList<>();
private final List<Label> labels = new ArrayList<>();
private final Map<String, String> typed = new HashMap<>(), errors = new HashMap<>();
private int parameterPage, boardX, boardY, panelX, selectedSlot;
private net.minecraft.client.gui.components.Button saveButton;
private final Map<String, CatalogIcon> icons = new HashMap<>(); private final Map<String, CatalogIcon> icons = new HashMap<>();
private final Set<String> requested = new HashSet<>(); private final Set<String> requested = new HashSet<>();
private int pending, pressed = -2; private int pending, pressed = -2;
@@ -41,20 +48,21 @@ public final class RecipeEditorScreen extends EditorScreen {
var id = addRenderableWidget(new EditBox(font, 12, 40, width - 24, 20, Component.literal("ID рецепта"))); 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")); id.setMaxLength(256); id.setValue(draft.id()); id.setEditable(draft.fresh()); id.setResponder(value -> draft.string(value, "id"));
String station = draft.text("crafting", "station"); String station = draft.text("crafting", "station");
button(RecipeDraft.STATIONS.get(station).name() + "…", 12, 68, Math.max(90, (width - 32) / 2), () -> { panelX = Math.max(226, width / 2);
var names = RecipeDraft.STATIONS.values().stream().map(RecipeDraft.Station::name).sorted().toList(); button(RecipeDraft.STATIONS.get(station).name() + "…", 36, 68, panelX - 52,
minecraft.gui.setScreen(new ChoiceScreen(this, "Блок рецепта", names, name -> { () -> minecraft.gui.setScreen(new RecipeStationPicker(this, type -> {
RecipeDraft.STATIONS.entrySet().stream().filter(e -> e.getValue().name().equals(name)).findFirst().ifPresent(e -> RecipeDraft.station(draft, e.getKey())); RecipeDraft.station(draft, type); parameterPage = 0; selectedSlot = 0; typed.clear(); errors.clear(); status("", false);
})); })));
});
button("Параметры…", 20 + (width - 32) / 2, 68, (width - 32) / 2, () -> minecraft.gui.setScreen(new SettingsScreen(this,
"Параметры рецепта", draft.document(), RecipeDraft::fields, draft::replace, List.of(), "Настройки относятся только к выбранному блоку.")));
layout(); layout();
button("Сохранить", 12, height - 27, 100, this::save).active = !saving; parameters();
slotQuantity();
saveButton = button("Сохранить", 12, height - 27, 100, this::save); saveButton.active = !saving && errors.isEmpty();
button("Назад", width - 112, height - 27, 100, this::onClose); button("Назад", width - 112, height - 27, 100, this::onClose);
} }
private void layout() { private void layout() {
cells.clear(); int x = width / 2 - 90, y = height < 300 ? 99 : 117; String station = draft.text("crafting", "station"); cells.clear(); decorations.clear();
boardX = 12 + (panelX - 24 - 192) / 2; boardY = 98;
int x = boardX, y = boardY; String station = draft.text("crafting", "station");
switch (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 "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 "smithing" -> { for (int i = 0; i < 3; i++) cells.add(new Cell(i, x + i * 30, y + 24, List.of("Шаблон", "Основа", "Добавка").get(i))); }
@@ -64,13 +72,110 @@ public final class RecipeEditorScreen extends EditorScreen {
} }
case "brewing" -> { case "brewing" -> {
cells.add(new Cell(1, x + 30, y, "Добавка")); cells.add(new Cell(1, x + 30, y, "Добавка"));
decorations.add(new Decoration(new ItemStack(net.minecraft.world.item.Items.BLAZE_POWDER), x - 1, y, "Топливо: огненный порошок (ванильное)"));
for (int i = 0; i < 3; i++) cells.add(new Cell(0, x + i * 30, y + 42 + (i == 1 ? 5 : 0), "Основа зелья — одинаковый рецепт для каждой бутылки")); 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 "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, "Дополнительный предмет")); } case "grindstone", "cartography" -> { cells.add(new Cell(0, x + 30, y, "Основной предмет")); cells.add(new Cell(1, x + 30, y + 42, "Дополнительный предмет")); }
case "smelting", "smoking", "blasting" -> {
cells.add(new Cell(0, x + 30, y, "Ингредиент"));
decorations.add(new Decoration(new ItemStack(net.minecraft.world.item.Items.COAL), x + 30, y + 44, "Пример топлива; используется ванильное топливо"));
}
default -> cells.add(new Cell(0, x + 30, y + 12, "Ингредиент")); default -> cells.add(new Cell(0, x + 30, y + 12, "Ингредиент"));
} }
if (!station.equals("composting")) cells.add(new Cell(-1, x + 144, y + 24, "Результат")); if (!station.equals("composting")) cells.add(new Cell(-1, x + 144, y + 24, "Результат"));
else decorations.add(new Decoration(new ItemStack(net.minecraft.world.item.Items.BONE_MEAL), x + 144, y + 24, "Результат полного компостирования: костная мука"));
nativeLayout(station);
}
private void nativeLayout(String station) {
int[][] positions = switch (station) {
case "crafting" -> new int[][]{{30,17},{48,17},{66,17},{30,35},{48,35},{66,35},{30,53},{48,53},{66,53},{124,35}};
case "smithing" -> new int[][]{{8,48},{26,48},{44,48},{98,48}};
case "loom" -> new int[][]{{13,26},{33,26},{23,45},{143,57}};
case "brewing" -> new int[][]{{79,17},{56,51},{79,58},{102,51},{145,51}};
case "anvil" -> new int[][]{{27,47},{76,47},{134,47}};
case "grindstone" -> new int[][]{{49,19},{49,40},{129,34}};
case "cartography" -> new int[][]{{15,15},{15,52},{145,39}};
case "stonecutting" -> new int[][]{{20,33},{143,33}};
case "smelting", "smoking", "blasting" -> new int[][]{{56,17},{116,35}};
default -> null;
};
if (positions != null) for (int i = 0; i < cells.size(); i++) {
var cell = cells.get(i); cells.set(i, new Cell(cell.index, boardX + positions[i][0] - 1, boardY + positions[i][1] - 1, cell.label));
}
if (!decorations.isEmpty() && !station.equals("composting")) {
var decoration = decorations.getFirst(); boolean brewing = station.equals("brewing");
decorations.set(0, new Decoration(decoration.stack, boardX + (brewing ? 16 : 55), boardY + (brewing ? 16 : 52), decoration.label));
}
}
private void background(GuiGraphicsExtractor graphics, String station) {
String texture = switch (station) {
case "crafting" -> "crafting_table"; case "smithing" -> "smithing";
case "brewing" -> "brewing_stand"; case "smelting" -> "furnace";
case "smoking" -> "smoker"; case "blasting" -> "blast_furnace";
case "stonecutting" -> "stonecutter"; case "cartography" -> "cartography_table";
case "anvil", "grindstone", "loom" -> station; default -> null;
};
if (texture != null) graphics.blit(net.minecraft.client.renderer.RenderPipelines.GUI_TEXTURED,
Identifier.withDefaultNamespace("textures/gui/container/" + texture + ".png"), boardX, boardY, 0, 0, 176, 83, 256, 256);
else {
graphics.fill(boardX, boardY, boardX + 176, boardY + 83, 0xFFC6C6C6);
graphics.item(new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(RecipeDraft.STATIONS.get(station).block()))), boardX + 80, boardY + 27);
graphics.text(font, "→", boardX + 113, boardY + 31, 0xFF404040);
}
}
private void parameters() {
labels.clear();
var fields = RecipeDraft.fields(draft); int rows = Math.max(1, (height - 180) / 40 + 1);
int pages = Math.max(1, (fields.size() + rows - 1) / rows); parameterPage = Math.min(parameterPage, pages - 1);
int fieldWidth = width - panelX - 12;
labels.add(new Label("Параметры" + (pages > 1 ? " " + (parameterPage + 1) + "/" + pages : ""), panelX, 74, fieldWidth - (pages > 1 ? 66 : 0)));
if (pages > 1) {
button("←", width - 74, 68, 28, () -> { parameterPage--; rebuildWidgets(); }).active = parameterPage > 0;
button("→", width - 42, 68, 28, () -> { parameterPage++; rebuildWidgets(); }).active = parameterPage + 1 < pages;
}
for (int i = parameterPage * rows; i < Math.min(fields.size(), (parameterPage + 1) * rows); i++) {
var field = fields.get(i); int y = 110 + (i % rows) * 40;
labels.add(new Label(field.label(), panelX, y - 11, fieldWidth));
if (field.cycle()) button(display(field.read().get()), panelX, y, fieldWidth, field.hint(), () -> {
int selected = field.choices().indexOf(field.read().get());
edit(field, field.choices().get((selected + 1) % field.choices().size())); rebuildWidgets();
});
else {
var box = addRenderableWidget(new EditBox(font, panelX, y, fieldWidth, 20, Component.literal(field.label())));
box.setMaxLength(field.key().equals("name") ? 128 : 32); box.setValue(typed.getOrDefault(field.key(), field.read().get()));
box.setTooltip(net.minecraft.client.gui.components.Tooltip.create(Component.literal(field.hint())));
box.setResponder(value -> edit(field, value));
}
}
}
private void slotQuantity() {
int index = selectedSlot;
String key = "input.count." + index;
var field = online.astradev.plus.editor.form.FormField.text(key, "Количество в слоте " + (index + 1), "Предметов в этом слоте на один рецепт", () -> RecipeDraft.slot(draft, index).get("count").getAsString(), value -> {
int count;
try { count = Integer.parseInt(value); } catch (NumberFormatException error) { throw new IllegalArgumentException("Введите целое число"); }
var slot = RecipeDraft.slot(draft, index).deepCopy(); var icon = icon(slot);
int max = icon == null ? 64 : icon.stack().getMaxStackSize();
if (draft.text("", "station").equals("brewing") && index == 0) max = 1;
if (count < 1 || count > max) throw new IllegalArgumentException("От 1 до " + max);
slot.addProperty("count", count); RecipeDraft.slot(draft, index, slot);
});
labels.add(new Label("Слот " + (index + 1) + ": количество", 12, 192, panelX - 78));
var box = addRenderableWidget(new EditBox(font, panelX - 62, 187, 46, 18, Component.literal(field.label())));
box.setMaxLength(2); box.setValue(typed.getOrDefault(key, field.read().get()));
box.setEditable(!RecipeDraft.slot(draft, index).get("id").getAsString().isEmpty());
box.setResponder(value -> edit(field, value));
}
private static String display(String value) {
return switch (value) { case "true" -> "Да"; case "false" -> "Нет"; case "water" -> "Вода";
case "lava" -> "Лава"; case "powder_snow" -> "Рыхлый снег"; case "empty" -> "Пустой котёл"; default -> value; };
}
private void edit(online.astradev.plus.editor.form.FormField field, String value) {
try { field.write().accept(value); typed.remove(field.key()); errors.remove(field.key()); }
catch (IllegalArgumentException error) { typed.put(field.key(), value); errors.put(field.key(), field.label() + ": " + error.getMessage()); }
status(errors.isEmpty() ? "" : errors.values().iterator().next(), !errors.isEmpty());
if (saveButton != null) saveButton.active = !saving && errors.isEmpty();
} }
private CatalogIcon icon(JsonObject slot) { private CatalogIcon icon(JsonObject slot) {
String id = slot.get("id").getAsString(); if (id.isEmpty()) return null; String id = slot.get("id").getAsString(); if (id.isEmpty()) return null;
@@ -92,46 +197,39 @@ public final class RecipeEditorScreen extends EditorScreen {
} }
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) { @Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
super.extractRenderState(graphics, mouseX, mouseY, a); super.extractRenderState(graphics, mouseX, mouseY, a);
String station = draft.text("crafting", "station"); int x = width / 2 - 90; String station = draft.text("crafting", "station"); int x = boardX;
int shift = height < 300 ? -18 : 0; graphics.item(new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse("minecraft:" + RecipeDraft.STATIONS.get(station).block()))), 14, 70);
if (height >= 300) graphics.text(font, font.plainSubstrByWidth(draft.text("Новый рецепт", "name"), width - 24), 12, 99, 0xFFE0F4F4); background(graphics, station);
graphics.fill(x - 12, 111 + shift, x + 180, 193 + shift, 0xFF24343D); labels.forEach(label -> graphics.text(font, font.plainSubstrByWidth(label.text, label.width), label.x, label.y, 0xFFB9CDD3));
graphics.text(font, "→", x + 111, 149 + shift, 0xFFE0F4F4);
for (Cell cell : cells) { for (Cell cell : cells) {
boolean hovered = contains(cell, mouseX, mouseY); 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, cell.y, cell.x + 18, cell.y + 18, hovered ? 0xFF8AA9AD : cell.index == selectedSlot ? 0xFFE5C06A : 0xFF373737);
graphics.fill(cell.x + 1, cell.y + 1, cell.x + 21, cell.y + 21, 0xFF101C23); graphics.fill(cell.x + 1, cell.y + 1, cell.x + 17, cell.y + 17, 0xFF8B8B8B);
var slot = RecipeDraft.slot(draft, cell.index); var icon = icon(slot); var slot = RecipeDraft.slot(draft, cell.index); var icon = icon(slot);
if (icon != null) { if (icon != null) {
graphics.item(icon.stack(), cell.x + 3, cell.y + 3); graphics.item(icon.stack(), cell.x + 1, cell.y + 1);
int count = slot.has("count") ? slot.get("count").getAsInt() : 1; 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); graphics.text(font, String.valueOf(count), cell.x + 17 - font.width(String.valueOf(count)), cell.y + 9, 0xFFFFFFFF);
} }
if (hovered && !dragging) graphics.setTooltipForNextFrame(font, Component.literal(cell.label + "\n" if (hovered && !dragging) graphics.setTooltipForNextFrame(font, Component.literal(cell.label + "\n"
+ (icon == null ? "Пустой слот" : icon.stack().getHoverName().getString()) + "\nНажать — выбрать; тянуть — переместить; ПКМ — очистить"), mouseX, mouseY); + (icon == null ? "Пустой слот" : icon.stack().getHoverName().getString()) + "\nНажать — выбрать; тянуть — переместить; ПКМ — очистить"), mouseX, mouseY);
} }
if (List.of("smelting", "smoking", "blasting", "brewing").contains(station)) { for (var decoration : decorations) {
var fuel = new ItemStack(station.equals("brewing") ? net.minecraft.world.item.Items.BLAZE_POWDER : net.minecraft.world.item.Items.COAL); graphics.fill(decoration.x, decoration.y, decoration.x + 18, decoration.y + 18, 0xFF373737);
graphics.item(fuel, x - 5, 169 + shift); graphics.fill(decoration.x + 1, decoration.y + 1, decoration.x + 17, decoration.y + 17, 0xFF8B8B8B);
graphics.item(decoration.stack, decoration.x + 1, decoration.y + 1);
int count = station.equals("brewing") ? Math.max(1, Integer.parseInt(draft.text("0", "brewingPowder"))) : 1;
graphics.text(font, String.valueOf(count), decoration.x + 17 - font.width(String.valueOf(count)), decoration.y + 9, 0xFFFFFFFF);
if (mouseX >= decoration.x && mouseX < decoration.x + 18 && mouseY >= decoration.y && mouseY < decoration.y + 18)
graphics.setTooltipForNextFrame(font, Component.literal(decoration.label), mouseX, mouseY);
} }
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); } 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) { private boolean contains(Cell cell, double x, double y) { return x >= cell.x && x < cell.x + 18 && y >= cell.y && y < cell.y + 18; }
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) { @Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
for (Cell cell : cells) if (contains(cell, event.x(), event.y())) { 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 (cell.index >= 0) selectedSlot = cell.index;
if (event.button() == 1) { RecipeDraft.slot(draft, cell.index, RecipeDraft.empty()); clearSlotError(cell.index); rebuildWidgets(); return true; }
if (event.button() == 0) { pressed = cell.index; pressX = event.x(); pressY = event.y(); dragging = false; return true; } if (event.button() == 0) { pressed = cell.index; pressX = event.x(); pressY = event.y(); dragging = false; return true; }
} }
return super.mouseClicked(event, doubleClick); return super.mouseClicked(event, doubleClick);
@@ -144,9 +242,10 @@ public final class RecipeEditorScreen extends EditorScreen {
if (pressed != -2) { if (pressed != -2) {
int source = pressed; pressed = -2; int source = pressed; pressed = -2;
for (Cell target : cells) if (contains(target, event.x(), event.y())) { for (Cell target : cells) if (contains(target, event.x(), event.y())) {
if (dragging && source != target.index) RecipeDraft.swap(draft, source, target.index); if (dragging && source != target.index) { RecipeDraft.swap(draft, source, target.index); rebuildWidgets(); }
else if (!dragging && source == target.index) minecraft.gui.setScreen(new RecipeItemPicker(this, connection, row -> { else if (!dragging && source == target.index) minecraft.gui.setScreen(new RecipeItemPicker(this, connection, row -> {
var selection = row.getAsJsonObject("selection"); RecipeDraft.slot(draft, source, selection); var selection = row.getAsJsonObject("selection"); RecipeDraft.slot(draft, source, selection);
clearSlotError(source);
icons.put(selection.get("id").getAsString(), new CatalogIcon(row)); icons.put(selection.get("id").getAsString(), new CatalogIcon(row));
})); }));
break; break;
@@ -155,8 +254,12 @@ public final class RecipeEditorScreen extends EditorScreen {
} }
return super.mouseReleased(event); return super.mouseReleased(event);
} }
private void clearSlotError(int index) {
String key = index < 0 ? "result.count" : "input.count." + index;
typed.remove(key); errors.remove(key); status(errors.isEmpty() ? "" : errors.values().iterator().next(), !errors.isEmpty());
}
private void save() { private void save() {
if (saving) return; if (saving || !errors.isEmpty()) return;
saving = true; var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("revision", draft.revision()); request.add("document", draft.document()); 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 -> { connection.request("recipe_save", request, response -> {
saving = false; saving = false;
@@ -0,0 +1,40 @@
package online.astradev.plus.editor.screen;
import java.util.Locale;
import java.util.function.Consumer;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import online.astradev.plus.editor.form.RecipeDraft;
/** Workstation names and their actual block icons. */
public final class RecipeStationPicker extends EditorScreen {
private final Screen parent;
private final Consumer<String> selected;
public RecipeStationPicker(Screen parent, Consumer<String> selected) {
super("Блок рецепта"); this.parent = parent; this.selected = selected;
}
@Override protected void init() {
var list = addRenderableWidget(new ContentList(minecraft, 12, 66, width - 24, Math.max(36, height - 136), id -> {
selected.accept(id); minecraft.gui.setScreen(parent);
}));
var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск блока")));
search.setMaxLength(128); search.setHint(Component.literal("Название блока"));
search.setResponder(query -> list.values(entries(query))); list.values(entries(""));
button("Назад", 12, height - 27, 100, this::onClose);
}
private JsonArray entries(String query) {
var rows = new JsonArray(); String needle = query.toLowerCase(Locale.ROOT);
RecipeDraft.STATIONS.entrySet().stream().sorted(java.util.Comparator.comparing(e -> e.getValue().name()))
.filter(e -> e.getValue().name().toLowerCase(Locale.ROOT).contains(needle) || e.getValue().block().contains(needle)).forEach(e -> {
var row = new JsonObject(); String id = "minecraft:" + e.getValue().block();
row.addProperty("id", id); row.addProperty("material", id); row.addProperty("kind", "block");
row.addProperty("name", e.getValue().name()); row.addProperty("selectionKey", e.getKey());
var icon = new JsonObject(); icon.addProperty("id", id); row.add("icon", icon); rows.add(row);
});
return rows;
}
@Override public void onClose() { minecraft.gui.setScreen(parent); }
}
@@ -21,4 +21,15 @@ final class RecipeDraftTest {
assertFalse(RecipeDraft.fields(draft).isEmpty()); assertFalse(RecipeDraft.fields(draft).isEmpty());
} }
} }
@Test void slotSwapKeepsQuantitiesAndBrewingHasEditableTimingAndFuel() {
var draft = RecipeDraft.create(); var item = RecipeDraft.empty(); item.addProperty("id", "minecraft:paper"); item.addProperty("count", 4);
RecipeDraft.slot(draft, 4, item); RecipeDraft.swap(draft, 4, 8);
assertEquals(4, RecipeDraft.slot(draft, 8).get("count").getAsInt());
RecipeDraft.station(draft, "brewing");
for (var field : RecipeDraft.fields(draft)) {
if (field.key().equals("brewingTime")) field.write().accept("60");
if (field.key().equals("brewingPowder")) field.write().accept("2");
}
assertEquals("60", draft.text("", "brewingTime")); assertEquals("2", draft.text("", "brewingPowder"));
}
} }
@@ -48,7 +48,8 @@ public final class RecipeGuiVerification {
if (phase % 2 == 0) { if (phase % 2 == 0) {
draft = RecipeDraft.create(); RecipeDraft.station(draft, station); draft = RecipeDraft.create(); RecipeDraft.station(draft, station);
for (int i = 0; i < RecipeDraft.STATIONS.get(station).inputs(); i++) { 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 slot = RecipeDraft.empty(); slot.addProperty("id", i % 2 == 0 ? "minecraft:diamond" : "minecraft:iron_ingot");
slot.addProperty("count", station.equals("brewing") && i == 0 ? 1 : i % 2 == 0 ? 4 : 2); RecipeDraft.slot(draft, i, slot);
} }
var output = RecipeDraft.empty(); output.addProperty("id", "minecraft:netherite_sword"); RecipeDraft.slot(draft, -1, output); 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); editor = new RecipeEditorScreen(new RecipeBrowserScreen(EditorConnection.INSTANCE), EditorConnection.INSTANCE, draft); mc.gui.setScreen(editor);
@@ -60,8 +61,8 @@ public final class RecipeGuiVerification {
RecipeDraft.station(draft, "crafting"); mc.gui.setScreen(editor); RecipeDraft.station(draft, "crafting"); mc.gui.setScreen(editor);
var first = RecipeDraft.empty(); first.addProperty("id", "minecraft:diamond"); RecipeDraft.slot(draft, 0, first); 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); var second = RecipeDraft.empty(); second.addProperty("id", "minecraft:iron_ingot"); RecipeDraft.slot(draft, 1, second);
int x = editor.width / 2 - 90 + 8, y = 125; int x = 12 + (Math.max(226, editor.width / 2) - 216) / 2 + 37, y = 122;
editor.mouseClicked(mouse(x, y, 0), false); editor.mouseDragged(mouse(x + 24, y, 0), 24, 0); editor.mouseReleased(mouse(x + 24, y, 0)); editor.mouseClicked(mouse(x, y, 0), false); editor.mouseDragged(mouse(x + 18, y, 0), 18, 0); editor.mouseReleased(mouse(x + 18, y, 0));
if (!RecipeDraft.slot(draft, 1).get("id").getAsString().equals("minecraft:diamond")) throw new IllegalStateException("Drag did not swap slots"); 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); 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"); if (!RecipeDraft.slot(draft, 0).get("id").getAsString().isEmpty()) throw new IllegalStateException("Right-click did not clear slot");
@@ -75,7 +76,20 @@ public final class RecipeGuiVerification {
case 5, 6, 7 -> { } case 5, 6, 7 -> { }
case 8 -> capture("mob-list-static-a.png"); case 8 -> capture("mob-list-static-a.png");
case 9 -> capture("mob-list-static-b.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"); } case 10 -> mc.gui.setScreen(new RecipeStationPicker(editor, ignored -> {}));
case 11 -> capture("recipe-station-picker.png");
case 12 -> {
mc.gui.setScreen(editor);
var count = editor.children().stream().filter(c -> c instanceof net.minecraft.client.gui.components.EditBox box && box.getMessage().getString().equals("Количество результата"))
.map(c -> (net.minecraft.client.gui.components.EditBox)c).findFirst().orElseThrow();
count.setValue("oops");
var save = editor.children().stream().filter(c -> c instanceof net.minecraft.client.gui.components.Button button && button.getMessage().getString().equals("Сохранить"))
.map(c -> (net.minecraft.client.gui.components.Button)c).findFirst().orElseThrow();
if (save.active) throw new IllegalStateException("Invalid inline value allowed save");
count.setValue("1"); if (!save.active) throw new IllegalStateException("Corrected inline value did not enable save");
if (captures != 19) throw new IllegalStateException("Incomplete screenshots: " + captures);
finish("PASS: 14 layouts, inline validation, station icons, picker, drag, clear, compact view, static mob frames");
}
default -> { } default -> { }
} }
} catch (Exception error) { finish("FAIL: " + error); } } catch (Exception error) { finish("FAIL: " + error); }