Show resource-pack item icons and edit content translations
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
package online.astradev.plus.editor.client;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
|
||||
/** Keeps the server's visual stack and falls back to its vanilla material when a pack is missing. */
|
||||
public final class CatalogIcon {
|
||||
private final ItemStack stack;
|
||||
private final ItemStack fallback;
|
||||
private final Identifier model;
|
||||
private final boolean supplied;
|
||||
private final boolean simplified;
|
||||
|
||||
public CatalogIcon(JsonObject entry) {
|
||||
ItemStack decoded = ItemStack.EMPTY;
|
||||
var minecraft = Minecraft.getInstance();
|
||||
if (entry.has("icon") && minecraft.level != null) {
|
||||
try {
|
||||
var ops = RegistryOps.create(JsonOps.INSTANCE, minecraft.level.registryAccess());
|
||||
decoded = ItemStack.CODEC.parse(ops, entry.get("icon")).result().orElse(ItemStack.EMPTY);
|
||||
} catch (RuntimeException ignored) { /* An invalid preview must not hide the definition. */ }
|
||||
}
|
||||
supplied = !decoded.isEmpty();
|
||||
if (!supplied) {
|
||||
var material = Identifier.tryParse(entry.has("material") ? entry.get("material").getAsString() : "minecraft:paper");
|
||||
decoded = material == null ? ItemStack.EMPTY : BuiltInRegistries.ITEM.getOptional(material).map(ItemStack::new).orElse(ItemStack.EMPTY);
|
||||
var id = Identifier.tryParse(entry.get("id").getAsString());
|
||||
if (!decoded.isEmpty() && id != null) decoded.set(DataComponents.ITEM_MODEL, id);
|
||||
}
|
||||
stack = decoded;
|
||||
model = stack.get(DataComponents.ITEM_MODEL);
|
||||
fallback = stack.copy();
|
||||
if (!fallback.isEmpty()) {
|
||||
var vanillaModel = fallback.getItem().components().get(DataComponents.ITEM_MODEL);
|
||||
if (vanillaModel != null) fallback.set(DataComponents.ITEM_MODEL, vanillaModel);
|
||||
}
|
||||
simplified = entry.has("iconSimplified") && entry.get("iconSimplified").getAsBoolean();
|
||||
}
|
||||
|
||||
public ItemStack stack() { return (available() ? stack : fallback).copy(); }
|
||||
|
||||
public boolean available() {
|
||||
if (model == null) return false;
|
||||
var resource = Identifier.fromNamespaceAndPath(model.getNamespace(), "items/" + model.getPath() + ".json");
|
||||
return Minecraft.getInstance().getResourceManager().getResource(resource).isPresent();
|
||||
}
|
||||
|
||||
public String hint() {
|
||||
if (stack.isEmpty()) return "Нет данных для иконки. Откройте определение и проверьте основу.";
|
||||
if (!available()) return "Показана ванильная основа. Модель " + model + " отсутствует в загруженном ресурспаке.";
|
||||
if (!supplied) return "Сервер не передал свойства иконки. Показана модель из ресурспака.";
|
||||
return simplified ? "Показана компактная иконка. Объёмные данные предмета в каталог не передаются." : "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.util.List;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
/** Updates one locale while preserving every other translation and unknown field. */
|
||||
public final class ContentTranslations {
|
||||
private ContentTranslations() {}
|
||||
|
||||
public static List<String> locales(ContentDraft draft) {
|
||||
var value = draft.get("translations");
|
||||
return value.isJsonObject() ? value.getAsJsonObject().keySet().stream().sorted().toList() : List.of();
|
||||
}
|
||||
|
||||
public static void save(ContentDraft draft, String locale, String name, boolean editLore, boolean overrideLore, String text) {
|
||||
if (!locale.matches("[a-z][a-z0-9_]{1,31}")) throw new IllegalArgumentException("Некорректный код языка.");
|
||||
var languages = draft.get("translations");
|
||||
var translations = languages.isJsonObject() ? languages.getAsJsonObject() : new JsonObject();
|
||||
if (!translations.has(locale) && translations.size() >= 128) throw new IllegalArgumentException("Допустимо не больше 128 языков.");
|
||||
var current = translations.get(locale);
|
||||
var value = current != null && current.isJsonObject() ? current.getAsJsonObject() : new JsonObject();
|
||||
if (name.length() > 256) throw new IllegalArgumentException("Название не должно превышать 256 символов.");
|
||||
if (name.isBlank()) value.remove("name"); else value.addProperty("name", name);
|
||||
if (editLore) {
|
||||
if (!overrideLore) value.remove("lore");
|
||||
else {
|
||||
var lines = text.isEmpty() ? new String[0] : text.split("\\R", -1);
|
||||
if (lines.length > 64) throw new IllegalArgumentException("Описание не должно превышать 64 строки.");
|
||||
var lore = new JsonArray();
|
||||
for (String line : lines) {
|
||||
if (line.length() > 1024) throw new IllegalArgumentException("Строка описания не должна превышать 1024 символа.");
|
||||
lore.add(line);
|
||||
}
|
||||
value.add("lore", lore);
|
||||
}
|
||||
}
|
||||
if (value.isEmpty()) translations.remove(locale); else translations.add(locale, value);
|
||||
draft.set(translations.isEmpty() ? null : translations, "translations");
|
||||
}
|
||||
|
||||
public static void remove(ContentDraft draft, String locale) {
|
||||
draft.set(null, "translations", locale);
|
||||
if (locales(draft).isEmpty()) draft.set(null, "translations");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,6 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.network.chat.Component;
|
||||
@@ -14,8 +11,8 @@ import online.astradev.plus.editor.network.EditorConnection;
|
||||
public final class ContentBrowserScreen extends EditorScreen {
|
||||
private final EditorConnection connection;
|
||||
private final EditorCatalog catalog = new EditorCatalog();
|
||||
private final Map<String, String> rows = new LinkedHashMap<>();
|
||||
private ChoiceList list;
|
||||
private JsonArray rows = new JsonArray();
|
||||
private ContentList list;
|
||||
private int page;
|
||||
private int pages = 1;
|
||||
private String query = "";
|
||||
@@ -37,8 +34,8 @@ public final class ContentBrowserScreen extends EditorScreen {
|
||||
search.setHint(Component.literal("Найти по имени или namespace:id"));
|
||||
search.setValue(query);
|
||||
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
||||
list.values(rows.keySet().stream().toList());
|
||||
list = addRenderableWidget(new ContentList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
||||
list.values(rows);
|
||||
int row = height - 94;
|
||||
int part = Math.max(50, (width - 48) / 4);
|
||||
button("+ Предмет", 12, row, part, () -> create(false));
|
||||
@@ -72,23 +69,15 @@ public final class ContentBrowserScreen extends EditorScreen {
|
||||
connection.request("list", request, response -> {
|
||||
if (generation != requestGeneration) return;
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
rows.clear();
|
||||
if (response.has("entries")) for (var value : response.getAsJsonArray("entries")) {
|
||||
var entry = value.getAsJsonObject();
|
||||
String id = entry.get("id").getAsString();
|
||||
String kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
|
||||
rows.put(kind + ": " + entry.get("name").getAsString() + " [" + id + "]", id);
|
||||
}
|
||||
rows = response.has("entries") ? response.getAsJsonArray("entries").deepCopy() : new JsonArray();
|
||||
page = response.has("page") ? response.get("page").getAsInt() : page;
|
||||
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
|
||||
list.values(rows.keySet().stream().toList());
|
||||
list.values(rows);
|
||||
status("Страница " + (page + 1) + " / " + pages + ": Выберите определение для редактирования.", false);
|
||||
});
|
||||
}
|
||||
|
||||
private void load(String label) {
|
||||
String id = rows.get(label);
|
||||
if (id == null) return;
|
||||
private void load(String id) {
|
||||
var request = new JsonObject(); request.addProperty("id", id);
|
||||
status("Открывается " + id + "…", false);
|
||||
connection.request("get", request, response -> {
|
||||
|
||||
@@ -68,9 +68,11 @@ public final class ContentEditorScreen extends EditorScreen {
|
||||
if (pages > 1) {
|
||||
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } }).active = page > 0;
|
||||
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } }).active = page + 1 < pages;
|
||||
labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
|
||||
if (!draft.block() || width >= 420) labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
|
||||
}
|
||||
if (draft.block()) button("Зачарования", width - 142, bottom, 130, this::enchantments);
|
||||
button("Переводы", draft.block() ? (width >= 420 ? width - 254 : 80) : width - 116, bottom, draft.block() && width < 420 ? 96 : 104,
|
||||
() -> minecraft.gui.setScreen(new TranslationsScreen(this, draft, true)));
|
||||
int size = (width - 40) / 3;
|
||||
button("Назад", 12, height - 27, size, this::onClose);
|
||||
save = button("Сохранить", 20 + size, height - 27, size, "Проверить и применить определение на сервере.", this::save);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
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.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.ObjectSelectionList;
|
||||
import net.minecraft.client.input.MouseButtonEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.CatalogIcon;
|
||||
|
||||
/** Inventory icons, names and identifiers stay readable independently in the content catalog. */
|
||||
public final class ContentList extends ObjectSelectionList<ContentList.Row> {
|
||||
private final Consumer<String> selected;
|
||||
|
||||
public ContentList(Minecraft minecraft, int x, int y, int width, int height, Consumer<String> selected) {
|
||||
super(minecraft, width, height, y, 36);
|
||||
setX(x);
|
||||
this.selected = selected;
|
||||
}
|
||||
|
||||
public void values(JsonArray entries) {
|
||||
clearEntries();
|
||||
entries.forEach(entry -> addEntry(new Row(entry.getAsJsonObject())));
|
||||
}
|
||||
|
||||
@Override public int getRowWidth() { return width - 16; }
|
||||
|
||||
public final class Row extends ObjectSelectionList.Entry<Row> {
|
||||
private final String id;
|
||||
private final String name;
|
||||
private final String kind;
|
||||
private final CatalogIcon icon;
|
||||
|
||||
private Row(JsonObject entry) {
|
||||
id = entry.get("id").getAsString();
|
||||
name = entry.get("name").getAsString();
|
||||
kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
|
||||
icon = new CatalogIcon(entry);
|
||||
}
|
||||
|
||||
@Override public Component getNarration() { return Component.literal(kind + ": " + 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 + 4, x + 26, y + 30, 0xFF101C23);
|
||||
var stack = icon.stack();
|
||||
if (stack.isEmpty()) graphics.text(minecraft.font, "?", x + 10, y + 13, 0xFF91A6B2);
|
||||
else graphics.item(stack, x + 5, y + 9);
|
||||
int textX = x + 34, textWidth = Math.max(0, getContentWidth() - 42);
|
||||
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(name, textWidth), textX, y + 5, 0xFFE5EFF1);
|
||||
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(kind + " " + id, textWidth), textX, y + 19, 0xFF9AAFB8);
|
||||
if (hovered) {
|
||||
String hint = icon.hint();
|
||||
String tooltip = kind + ": " + name + "\n" + id + (hint.isEmpty() ? "" : "\n\n" + hint);
|
||||
graphics.setTooltipForNextFrame(minecraft.font, Component.literal(tooltip), mouseX, mouseY);
|
||||
}
|
||||
}
|
||||
|
||||
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||
if (event.button() != 0) return false;
|
||||
setSelected(this);
|
||||
selected.accept(id);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@ public final class MobEditorScreen extends EditorScreen {
|
||||
var sections = new ArrayList<Section>();
|
||||
sections.add(new Section("Основное", this::basic));
|
||||
if (!skill) sections.add(new Section("Свойства и защита", this::options));
|
||||
if (!skill) sections.add(new Section("Переводы", () -> minecraft.gui.setScreen(new TranslationsScreen(this, draft, false))));
|
||||
sections.add(new Section(skill ? "Последовательность" : "События и действия", () -> minecraft.gui.setScreen(new MobActionsScreen(this, draft, catalog, !skill))));
|
||||
sections.add(new Section(skill ? "Условия исполнителя" : "ИИ и выбор цели", skill ? () -> conditions("conditions", "Условия исполнителя") : this::ai));
|
||||
sections.add(new Section(skill ? "Условия цели" : "Лут", skill ? () -> conditions("targetConditions", "Условия цели") : () -> minecraft.gui.setScreen(new MobDropsScreen(this, draft, catalog))));
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.MultiLineEditBox;
|
||||
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.ContentTranslations;
|
||||
|
||||
public final class TranslationEditScreen extends EditorScreen {
|
||||
private final TranslationsScreen parent;
|
||||
private final ContentDraft draft;
|
||||
private final String locale;
|
||||
private final boolean lore;
|
||||
private final String originalName, originalText;
|
||||
private final boolean originalOverride;
|
||||
private String name, text;
|
||||
private boolean override;
|
||||
|
||||
public TranslationEditScreen(TranslationsScreen parent, ContentDraft draft, String locale, boolean lore) {
|
||||
super("Перевод: " + locale); this.parent = parent; this.draft = draft; this.locale = locale; this.lore = lore;
|
||||
name = draft.text("", "translations", locale, "name");
|
||||
var lines = new ArrayList<String>();
|
||||
var translated = draft.get("translations", locale, "lore");
|
||||
override = translated.isJsonArray();
|
||||
if (override) translated.getAsJsonArray().forEach(line -> lines.add(line.getAsString()));
|
||||
text = String.join("\n", lines);
|
||||
originalName = name; originalText = text; originalOverride = override;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var input = addRenderableWidget(new EditBox(font, 12, 58, width - 24, 20, Component.literal("Название на этом языке")));
|
||||
input.setMaxLength(256); input.setValue(name);
|
||||
input.setHint(Component.literal(draft.text(draft.id(), "name")));
|
||||
input.setResponder(value -> name = value);
|
||||
if (lore) {
|
||||
button(override ? "Описание: перевод на этот язык" : "Описание: основное из свойств", 12, 88, width - 24, () -> {
|
||||
override = !override; rebuildWidgets();
|
||||
});
|
||||
var description = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(126).setShowDecorations(false)
|
||||
.setPlaceholder(Component.literal(override ? "Пропущенные строки используют основное описание" : "Наследуется minecraft:lore из свойств предмета"))
|
||||
.build(font, width - 24, Math.max(26, height - 202), Component.literal("Перевод описания")));
|
||||
description.setCharacterLimit(64 * 1025); description.setValue(text);
|
||||
description.setValueListener(value -> text = value); description.active = override;
|
||||
}
|
||||
int part = (width - 40) / 3;
|
||||
button("Отмена", 12, height - 27, part, this::onClose);
|
||||
button("Удалить язык", 20 + part, height - 27, part, () -> {
|
||||
ContentTranslations.remove(draft, locale); minecraft.gui.setScreen(parent);
|
||||
}).active = ContentTranslations.locales(draft).contains(locale);
|
||||
button("В черновик", 28 + part * 2, height - 27, part, () -> {
|
||||
try {
|
||||
ContentTranslations.save(draft, locale, name, lore, override, text);
|
||||
minecraft.gui.setScreen(parent);
|
||||
} catch (IllegalArgumentException error) { status(error.getMessage(), true); }
|
||||
});
|
||||
if (status.isBlank()) status(lore ? "Пропущенные строки используют основное описание. Число строк общее для всех языков. Сохраните определение и соберите ресурспак."
|
||||
: "Пустое название использует основное. «В черновик» не изменяет сервер: сохраните определение и соберите ресурспак.", false);
|
||||
}
|
||||
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||
graphics.text(font, "Название на этом языке", 12, 43, 0xFFB3C8D1);
|
||||
if (lore) graphics.text(font, "Описание: одна строка текста — одна строка подсказки", 12, 114, 0xFFB3C8D1);
|
||||
}
|
||||
|
||||
@Override public void onClose() {
|
||||
if (!name.equals(originalName) || !text.equals(originalText) || override != originalOverride)
|
||||
minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||
Component.literal("Отменить изменения перевода?"), Component.literal("Перевод ещё не перенесён в черновик.")));
|
||||
else minecraft.gui.setScreen(parent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.ContentTranslations;
|
||||
|
||||
/** Per-definition resource-pack translations; the Minecraft interface language stays unchanged. */
|
||||
public final class TranslationsScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final ContentDraft draft;
|
||||
private final boolean lore;
|
||||
private final Map<String, String> languages = new LinkedHashMap<>();
|
||||
private String pending;
|
||||
|
||||
public TranslationsScreen(Screen parent, ContentDraft draft, boolean lore) {
|
||||
super("Переводы контента"); this.parent = parent; this.draft = draft; this.lore = lore;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
languages.clear();
|
||||
minecraft.getLanguageManager().getLanguages().forEach((id, info) -> languages.put(id + " " + info.toComponent().getString(), id));
|
||||
var rows = new LinkedHashMap<String, String>();
|
||||
for (String locale : ContentTranslations.locales(draft)) {
|
||||
var info = minecraft.getLanguageManager().getLanguage(locale);
|
||||
String name = draft.text("Основное название", "translations", locale, "name");
|
||||
rows.put(locale + " " + (info == null ? "" : info.toComponent().getString() + " ") + name, locale);
|
||||
}
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 42, width - 24, Math.max(26, height - 141),
|
||||
row -> open(rows.get(row))));
|
||||
list.values(rows.keySet().stream().toList());
|
||||
button("+ Добавить язык", 12, height - 90, Math.min(170, width - 24), () -> minecraft.gui.setScreen(new ChoiceScreen(this,
|
||||
"Язык перевода", languages.keySet().stream().filter(label -> !ContentTranslations.locales(draft).contains(languages.get(label))).toList(),
|
||||
label -> pending = languages.get(label)))).active = rows.size() < 128;
|
||||
button("Готово", 12, height - 27, 120, this::onClose);
|
||||
status(rows.isEmpty() ? "Переводов пока нет. Используется основное название" + (lore ? " и описание предмета." : ".")
|
||||
: "Языков: " + rows.size() + ". Сохраните определение и соберите ресурспак. Для новых ключей получите новый образец.", false);
|
||||
}
|
||||
|
||||
private void open(String locale) { minecraft.gui.setScreen(new TranslationEditScreen(this, draft, locale, lore)); }
|
||||
|
||||
@Override public void tick() {
|
||||
if (pending != null) { String locale = pending; pending = null; open(locale); }
|
||||
}
|
||||
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
Reference in New Issue
Block a user