Add mob and skill catalogs with condition editing and native animation preview
This commit is contained in:
@@ -6,9 +6,9 @@
|
|||||||
|
|
||||||
## Установка и работа
|
## Установка и работа
|
||||||
|
|
||||||
1. Установите `AstraPlusEditor-0.2.0.jar` из `build/libs` в папку `mods` **клиента администратора**.
|
1. Установите `AstraPlusEditor-0.3.0.jar` из `build/libs` в папку `mods` **клиента администратора**.
|
||||||
Этот JAR не устанавливается на сервер. Требуется серверный **AstraPlus 0.4.0 или новее**:
|
Этот JAR не устанавливается на сервер. Для меню мобов требуется серверный **AstraPlus 0.5.0 или новее**.
|
||||||
он передаёт свойства основы и расширенный каталог. Версия протокола редактора остаётся 1.
|
Версия протокола редактора остаётся 1; каналы необязательны.
|
||||||
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
|
2. Подключитесь к серверу. Нажмите **F8** или введите **`/astraplus-editor`**.
|
||||||
Клавиша переназначается в управлении Minecraft.
|
Клавиша переназначается в управлении Minecraft.
|
||||||
3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы.
|
3. Найдите определение по имени или ID. Поиск выполняется на сервере, результаты разбиты на страницы.
|
||||||
@@ -73,8 +73,41 @@
|
|||||||
графика появляется после сборки и доставки ресурспака игрокам. Клиентская коллизия блока
|
графика появляется после сборки и доставки ресурспака игрокам. Клиентская коллизия блока
|
||||||
по-прежнему определяется ванильным носителем; произвольная модель её не изменяет.
|
по-прежнему определяется ванильным носителем; произвольная модель её не изменяет.
|
||||||
|
|
||||||
Сущности, мебель, блоки с собственными инвентарями и пользовательские мобы относятся
|
## Мобы и навыки
|
||||||
к следующему этапу. В этой версии редактор предназначен для предметов и обычных блоков.
|
|
||||||
|
В верхней строке каталога доступны **Предметы и блоки**, **Мобы**, **Навыки**. Каталоги
|
||||||
|
содержат загруженные сервером определения; просмотр ничего не призывает и не сохраняет.
|
||||||
|
Каждый моб и навык находится в отдельном файле `astraplus/contents/<namespace>/mobs|skills/<path>.json`.
|
||||||
|
|
||||||
|
- Карточка моба показывает ванильную основу, здоровье и урон. **Основное** и **Свойства и защита**
|
||||||
|
открывают атрибуты, движение, коллизии, гравитацию, неуязвимость, исчезновение, угрозу и защиту от повреждений.
|
||||||
|
У необязательных числовых настроек пустое поле наследует значение основы или сервера.
|
||||||
|
- **Яйцо призыва** выдаёт яйцо сохранённого моба. **Призвать рядом** создаёт настоящего моба
|
||||||
|
в мире. Несохранённый черновик к этим операциям не применяется.
|
||||||
|
- **Модели и анимации** открывает нативный 3D предпросмотр после входа на сервер. Модель
|
||||||
|
вращается перетаскиванием мыши, масштаб меняется колесом. Выбор содержит все доступные
|
||||||
|
клипы модели; есть пауза, запуск сначала, исходная поза и сброс вида. Геометрия и текстуры
|
||||||
|
берутся из полученного ресурспака; для отсутствующего ресурса показывается объяснение.
|
||||||
|
- **События и действия** редактирует последовательность, события призыва/загрузки/атаки/смерти/боя/таймера,
|
||||||
|
цели, вероятность, параметры и условия отдельного действия. Строки можно добавлять, удалять и переставлять.
|
||||||
|
- **Навыки** имеют перезарядку, последовательность и отдельные условия исполнителя и цели.
|
||||||
|
Поддержаны все семь серверных проверок: бой, расстояние до цели или игрока, наличие ауры,
|
||||||
|
модели, блокирование щитом и пассажир модели. Доступны инверсия, радиус, имя ауры, кость
|
||||||
|
и резервный навык `orElseCast`. Условия отдельного действия допускают проверку и инверсию;
|
||||||
|
резервный вызов задаётся у именованного навыка.
|
||||||
|
- **Связанные навыки** позволяет переходить к вызываемым определениям. Вложенный экран
|
||||||
|
сохраняется отдельно; несохранённый черновик родителя остаётся открытым.
|
||||||
|
- **ИИ и выбор цели** меняет поддержанные задачи и селекторы. Пустой список сохраняет
|
||||||
|
ванильное поведение, `clear` убирает ванильные задачи перед добавлением выбранных.
|
||||||
|
- **Лут** задаёт ванильный предмет, диапазон количества и вероятность. **Заменить ванильный лут**
|
||||||
|
определяет, дополняется ли обычный дроп или полностью заменяется.
|
||||||
|
|
||||||
|
Условия поведения проверяются перед действиями; они не создают природные правила спавна.
|
||||||
|
Сложные вложенные выражения сохраняются без преобразования и доступны через **Запись…**
|
||||||
|
или **Расширенный JSON**. Неизвестные поля остаются в документе. Обновление ванильного
|
||||||
|
типа сущности действует при следующем призыве. Назначение модели через событие `onSpawn`
|
||||||
|
тоже выполняется при новом призыве: сохранение не повторяет события призыва уже живущих мобов.
|
||||||
|
Мебель и блоки с собственными инвентарями пока не имеют отдельного редактора.
|
||||||
|
|
||||||
## Протокол и ограничения
|
## Протокол и ограничения
|
||||||
|
|
||||||
@@ -85,9 +118,12 @@
|
|||||||
Сервер является источником истины. Клиент передаёт ID и JSON, а не файловые пути.
|
Сервер является источником истины. Клиент передаёт ID и JSON, а не файловые пути.
|
||||||
Сохранение использует SHA-256 ревизию файла и блокирует ввод до ответа, чтобы поздний ответ
|
Сохранение использует SHA-256 ревизию файла и блокирует ввод до ответа, чтобы поздний ответ
|
||||||
не перезаписал более свежий локальный ввод. Серверные права проверяются при каждом запросе.
|
не перезаписал более свежий локальный ввод. Серверные права проверяются при каждом запросе.
|
||||||
Сетевой запрос ограничен 8192 символами, включая обёртку протокола. Большие определения
|
Один пакет ограничен 8192 символами. Большие документы передаются последовательностью
|
||||||
нужно редактировать непосредственно в файлах сервера. До получения ответа повторная
|
пакетов и собираются сервером как один запрос, с пределом 1 МиБ UTF-8. Ревизия проверяется
|
||||||
отправка сохранения недоступна.
|
перед применением полного документа. До получения ответа повторная отправка сохранения недоступна.
|
||||||
|
Большие ответы, включая полный выбранный клип модели, передаются частями с общим пределом
|
||||||
|
32 МиБ. Клиент проверяет порядок и принадлежность частей запросу. Незавершённая передача
|
||||||
|
очищается при отключении, после 15 секунд без прогресса или через 60 секунд от запроса.
|
||||||
|
|
||||||
## Сборка и проверки
|
## Сборка и проверки
|
||||||
|
|
||||||
@@ -100,7 +136,9 @@
|
|||||||
|
|
||||||
`build` собирает клиентский JAR и выполняет тесты наследования компонентов и сохранности черновиков: неизвестные
|
`build` собирает клиентский JAR и выполняет тесты наследования компонентов и сохранности черновиков: неизвестные
|
||||||
поля, защита от внешних мутаций, отрицательные component patches, ошибочные числа,
|
поля, защита от внешних мутаций, отрицательные component patches, ошибочные числа,
|
||||||
симметричные несовместимости, белый список и формат огнестойкости Minecraft 26.2.
|
симметричные несовместимости, белый список и формат огнестойкости Minecraft 26.2. Дополнительно
|
||||||
|
проверяются вложенные действия и условия мобов, сохранность идентификатора из серверного
|
||||||
|
ответа, передача больших документов UTF-8, иерархии моделей и ключевые кадры анимаций.
|
||||||
|
|
||||||
`runVerificationClient` запускает отдельный тестовый мод в `build/isolated-editor`,
|
`runVerificationClient` запускает отдельный тестовый мод в `build/isolated-editor`,
|
||||||
открывает реальные экраны Minecraft, проверяет границы виджетов, сохраняет PNG в
|
открывает реальные экраны Minecraft, проверяет границы виджетов, сохраняет PNG в
|
||||||
@@ -112,8 +150,14 @@
|
|||||||
`127.0.0.1:26700` в offline-режиме. `networkVerification` входит как `AstraEditVerify`
|
`127.0.0.1:26700` в offline-режиме. `networkVerification` входит как `AstraEditVerify`
|
||||||
(нужны права администратора), через реальный протокол проверяет каталог, список, чтение,
|
(нужны права администратора), через реальный протокол проверяет каталог, список, чтение,
|
||||||
создание предмета и блока, изменение, конфликт ревизий, выдачу предмета и сборку ZIP,
|
создание предмета и блока, изменение, конфликт ревизий, выдачу предмета и сборку ZIP,
|
||||||
получение свойств основы и сочетание еды, употребления и защиты от смерти на мече.
|
получение свойств основы и сочетание еды, употребления и защиты от смерти на мече. Затем
|
||||||
Проверка создаёт определения с уникальными ID `verification:client_*` только на тестовом сервере.
|
проверяются мобы и навыки: создание и изменение, семь видов условий, отклонение устаревших
|
||||||
|
и некорректных правок, большой документ, выдача яйца, явный призыв и настоящие кнопки GUI.
|
||||||
|
Проверка создаёт определения с уникальными ID `verification:client_*` и `verification:mob_*`
|
||||||
|
только на тестовом сервере. Для 3D проверки установите туда внешнюю модель с двумя или более
|
||||||
|
анимациями, а в `build/isolated-editor/resourcepacks` — её ресурспак и включите его в клиенте.
|
||||||
|
Сценарий сам выбирает подходящую модель, проверяет выбор всех клипов, два воспроизведения,
|
||||||
|
паузу, перезапуск, вращение, масштаб и исходную позу. В исходниках проверки нет имён внешних паков.
|
||||||
`runCompatibilityClient` входит как `AstraGuest` с одним тестовым модом и **без AstraPlusEditor**,
|
`runCompatibilityClient` входит как `AstraGuest` с одним тестовым модом и **без AstraPlusEditor**,
|
||||||
проверяет успешный вход и отсутствие редактора в списке модов. Это проверка NeoForge-клиента без
|
проверяет успешный вход и отсутствие редактора в списке модов. Это проверка NeoForge-клиента без
|
||||||
редактора; чистый ванильный клиент этим сценарием не запускается.
|
редактора; чистый ванильный клиент этим сценарием не запускается.
|
||||||
|
|||||||
+2
-1
@@ -4,7 +4,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
group = "online.astradev"
|
group = "online.astradev"
|
||||||
version = "0.2.0"
|
version = "0.3.0"
|
||||||
repositories { mavenCentral() }
|
repositories { mavenCentral() }
|
||||||
dependencies {
|
dependencies {
|
||||||
testImplementation("com.google.code.gson:gson:2.14.0")
|
testImplementation("com.google.code.gson:gson:2.14.0")
|
||||||
@@ -47,6 +47,7 @@ neoForge {
|
|||||||
gameDirectory.set(layout.buildDirectory.dir("isolated-editor"))
|
gameDirectory.set(layout.buildDirectory.dir("isolated-editor"))
|
||||||
systemProperty("astrapluseditor.isolatedVerification", "true")
|
systemProperty("astrapluseditor.isolatedVerification", "true")
|
||||||
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())
|
||||||
programArgument("--width"); programArgument("1280")
|
programArgument("--width"); programArgument("1280")
|
||||||
programArgument("--height"); programArgument("720")
|
programArgument("--height"); programArgument("720")
|
||||||
programArgument("--username"); programArgument("AstraEditVerify")
|
programArgument("--username"); programArgument("AstraEditVerify")
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ public final class AstraPlusEditor {
|
|||||||
var client = new EditorClient(connection);
|
var client = new EditorClient(connection);
|
||||||
modBus.addListener(connection::register);
|
modBus.addListener(connection::register);
|
||||||
modBus.addListener(client::registerKeys);
|
modBus.addListener(client::registerKeys);
|
||||||
|
modBus.addListener(online.astradev.plus.editor.client.preview.PreviewRenderer::register);
|
||||||
NeoForge.EVENT_BUS.addListener(client::registerCommands);
|
NeoForge.EVENT_BUS.addListener(client::registerCommands);
|
||||||
NeoForge.EVENT_BUS.addListener(client::tick);
|
NeoForge.EVENT_BUS.addListener(client::tick);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewModel.Frame;
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewModel.Vector;
|
||||||
|
|
||||||
|
/** Mirrors the server's numeric Blockbench interpolation without running server behavior. */
|
||||||
|
public final class PreviewAnimation {
|
||||||
|
private PreviewAnimation() {}
|
||||||
|
|
||||||
|
public static Vector sample(List<Frame> frames, float time, boolean loop, Vector fallback) {
|
||||||
|
if (frames.isEmpty()) return fallback;
|
||||||
|
if (time <= frames.getFirst().time()) return frames.getFirst().before();
|
||||||
|
for (int index = 0; index < frames.size() - 1; index++) {
|
||||||
|
Frame from = frames.get(index), to = frames.get(index + 1);
|
||||||
|
if (time > to.time()) continue;
|
||||||
|
if (time == to.time()) return to.before();
|
||||||
|
if (from.interpolation().equals("step")) return from.after();
|
||||||
|
float fraction = (time - from.time()) / (to.time() - from.time());
|
||||||
|
if (from.interpolation().equals("catmullrom") || to.interpolation().equals("catmullrom")) {
|
||||||
|
Vector before = index > 0 ? frames.get(index - 1).after()
|
||||||
|
: loop && frames.size() >= 3 ? frames.get(frames.size() - 2).after() : from.after();
|
||||||
|
Vector after = index + 2 < frames.size() ? frames.get(index + 2).before()
|
||||||
|
: loop && frames.size() >= 3 ? frames.get(1).before() : to.before();
|
||||||
|
return new Vector(cubic(before.x(), from.after().x(), to.before().x(), after.x(), fraction),
|
||||||
|
cubic(before.y(), from.after().y(), to.before().y(), after.y(), fraction),
|
||||||
|
cubic(before.z(), from.after().z(), to.before().z(), after.z(), fraction));
|
||||||
|
}
|
||||||
|
return new Vector(lerp(from.after().x(), to.before().x(), fraction),
|
||||||
|
lerp(from.after().y(), to.before().y(), fraction), lerp(from.after().z(), to.before().z(), fraction));
|
||||||
|
}
|
||||||
|
return frames.getLast().after();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float lerp(float from, float to, float fraction) { return from + (to - from) * fraction; }
|
||||||
|
private static float cubic(float p0, float p1, float p2, float p3, float time) {
|
||||||
|
return 0.5F * (2 * p1 + (-p0 + p2) * time + (2 * p0 - 5 * p1 + 4 * p2 - p3) * time * time
|
||||||
|
+ (-p0 + 3 * p1 - 3 * p2 + p3) * time * time * time);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
/** Bounded numeric model data received from the administrator endpoint. */
|
||||||
|
public record PreviewModel(String id, List<Bone> bones, List<String> animations, Animation animation,
|
||||||
|
String selectedAnimation) {
|
||||||
|
public PreviewModel { bones = List.copyOf(bones); animations = List.copyOf(animations); }
|
||||||
|
|
||||||
|
public static PreviewModel read(JsonObject value) {
|
||||||
|
if (value.has("preview")) value = value.getAsJsonObject("preview");
|
||||||
|
List<Bone> bones = new ArrayList<>();
|
||||||
|
JsonArray sourceBones = value.getAsJsonArray("bones");
|
||||||
|
if (sourceBones == null || sourceBones.isEmpty() || sourceBones.size() > 256)
|
||||||
|
throw new IllegalArgumentException("В модели должно быть от 1 до 256 частей.");
|
||||||
|
for (JsonElement element : sourceBones) {
|
||||||
|
JsonObject bone = element.getAsJsonObject(); int parent = bone.get("parent").getAsInt();
|
||||||
|
if (parent < -1 || parent >= bones.size()) throw new IllegalArgumentException("Неверная иерархия модели.");
|
||||||
|
float scale = number(bone.get("geometryScale"));
|
||||||
|
if (scale <= 0) throw new IllegalArgumentException("Неверный размер части модели.");
|
||||||
|
bones.add(new Bone(text(bone, "name"), parent, vector(bone.get("origin")), vector(bone.get("rotation")),
|
||||||
|
bone.has("itemModel") ? text(bone, "itemModel") : null, scale));
|
||||||
|
}
|
||||||
|
List<String> animations = new ArrayList<>();
|
||||||
|
JsonArray sourceAnimations = value.getAsJsonArray("animations");
|
||||||
|
if (sourceAnimations != null) for (JsonElement element : sourceAnimations) {
|
||||||
|
if (animations.size() >= 256) throw new IllegalArgumentException("Слишком много анимаций.");
|
||||||
|
animations.add(text(element.getAsJsonObject(), "name"));
|
||||||
|
}
|
||||||
|
Animation animation = null;
|
||||||
|
if (value.has("animation")) {
|
||||||
|
JsonObject source = value.getAsJsonObject("animation"); Map<Integer, Pose> poses = new HashMap<>();
|
||||||
|
int[] count = {0};
|
||||||
|
for (var entry : source.getAsJsonObject("bones").entrySet()) {
|
||||||
|
int index = Integer.parseInt(entry.getKey());
|
||||||
|
if (index < 0 || index >= bones.size()) throw new IllegalArgumentException("Анимация ссылается на неизвестную часть.");
|
||||||
|
JsonObject pose = entry.getValue().getAsJsonObject();
|
||||||
|
poses.put(index, new Pose(track(pose, "position", count), track(pose, "rotation", count), track(pose, "scale", count)));
|
||||||
|
}
|
||||||
|
float length = number(source.get("length"));
|
||||||
|
if (length < 0 || length > 3600) throw new IllegalArgumentException("Неверная продолжительность анимации.");
|
||||||
|
animation = new Animation(text(source, "name"), length, source.get("loop").getAsBoolean(), Map.copyOf(poses));
|
||||||
|
}
|
||||||
|
String selected = value.has("selectedAnimation") ? text(value, "selectedAnimation") : "";
|
||||||
|
if (!selected.isEmpty() && (animation == null || !animation.name().equals(selected)))
|
||||||
|
throw new IllegalArgumentException("Сервер не прислал выбранную анимацию целиком.");
|
||||||
|
return new PreviewModel(text(value, "id"), bones, animations, animation, selected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Frame> track(JsonObject pose, String name, int[] count) {
|
||||||
|
if (!pose.has(name)) return List.of();
|
||||||
|
List<Frame> frames = new ArrayList<>(); float previous = -1;
|
||||||
|
for (JsonElement element : pose.getAsJsonArray(name)) {
|
||||||
|
if (++count[0] > 100_000) throw new IllegalArgumentException("Слишком много ключевых кадров.");
|
||||||
|
JsonObject frame = element.getAsJsonObject(); float time = number(frame.get("time"));
|
||||||
|
String interpolation = text(frame, "interpolation");
|
||||||
|
if (time <= previous || time > 3600 || !Set.of("linear", "step", "catmullrom").contains(interpolation))
|
||||||
|
throw new IllegalArgumentException("Неверный ключевой кадр анимации.");
|
||||||
|
frames.add(new Frame(time, vector(frame.get("before")), vector(frame.get("after")), interpolation)); previous = time;
|
||||||
|
}
|
||||||
|
return List.copyOf(frames);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Vector vector(JsonElement element) {
|
||||||
|
JsonArray array = element.getAsJsonArray();
|
||||||
|
if (array.size() != 3) throw new IllegalArgumentException("Координаты должны содержать три числа.");
|
||||||
|
return new Vector(number(array.get(0)), number(array.get(1)), number(array.get(2)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float number(JsonElement value) {
|
||||||
|
float result = value.getAsFloat();
|
||||||
|
if (!Float.isFinite(result) || Math.abs(result) > 1_000_000) throw new IllegalArgumentException("Недопустимое число в модели.");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(JsonObject value, String name) {
|
||||||
|
String result = value.get(name).getAsString();
|
||||||
|
if (result.length() > 512) throw new IllegalArgumentException("Слишком длинное имя в модели.");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Vector(float x, float y, float z) {
|
||||||
|
public static final Vector ZERO = new Vector(0, 0, 0), ONE = new Vector(1, 1, 1);
|
||||||
|
public Vector add(Vector other) { return new Vector(x + other.x, y + other.y, z + other.z); }
|
||||||
|
public Vector subtract(Vector other) { return new Vector(x - other.x, y - other.y, z - other.z); }
|
||||||
|
}
|
||||||
|
public record Bone(String name, int parent, Vector origin, Vector rotation, String itemModel, float geometryScale) {}
|
||||||
|
public record Frame(float time, Vector before, Vector after, String interpolation) {}
|
||||||
|
public record Pose(List<Frame> position, List<Frame> rotation, List<Frame> scale) {}
|
||||||
|
public record Animation(String name, float length, boolean loop, Map<Integer, Pose> bones) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewModel.Vector;
|
||||||
|
import org.joml.Matrix4f;
|
||||||
|
|
||||||
|
/** Builds the same parent-relative transforms used by server item displays. */
|
||||||
|
public final class PreviewPose {
|
||||||
|
private static final float RADIANS = (float) (Math.PI / 180);
|
||||||
|
|
||||||
|
private PreviewPose() {}
|
||||||
|
|
||||||
|
public static Matrix4f[] matrices(PreviewModel model, float elapsed) {
|
||||||
|
Matrix4f[] result = new Matrix4f[model.bones().size()];
|
||||||
|
var animation = model.animation(); float time = elapsed;
|
||||||
|
if (animation != null) time = animation.loop() && animation.length() > 0
|
||||||
|
? time % animation.length() : Math.min(time, animation.length());
|
||||||
|
for (int index = 0; index < result.length; index++) {
|
||||||
|
var bone = model.bones().get(index);
|
||||||
|
Vector offset = bone.parent() < 0 ? bone.origin()
|
||||||
|
: bone.origin().subtract(model.bones().get(bone.parent()).origin());
|
||||||
|
Vector rotation = bone.rotation(), scale = Vector.ONE;
|
||||||
|
var pose = animation == null ? null : animation.bones().get(index);
|
||||||
|
if (pose != null) {
|
||||||
|
offset = offset.add(PreviewAnimation.sample(pose.position(), time, animation.loop(), Vector.ZERO));
|
||||||
|
rotation = rotation.add(PreviewAnimation.sample(pose.rotation(), time, animation.loop(), Vector.ZERO));
|
||||||
|
scale = PreviewAnimation.sample(pose.scale(), time, animation.loop(), Vector.ONE);
|
||||||
|
}
|
||||||
|
result[index] = new Matrix4f(bone.parent() < 0 ? new Matrix4f().scale(1 / 16F) : result[bone.parent()])
|
||||||
|
.translate(offset.x(), offset.y(), offset.z())
|
||||||
|
.rotateZYX(rotation.z() * RADIANS, rotation.y() * RADIANS, rotation.x() * RADIANS)
|
||||||
|
.scale(nonzero(scale.x()), nonzero(scale.y()), nonzero(scale.z()));
|
||||||
|
if (!result[index].isFinite()) throw new IllegalArgumentException("Преобразование части модели вышло за числовые пределы.");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float nonzero(float value) { return value == 0 ? 0.00001F : value; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import net.minecraft.client.gui.navigation.ScreenRectangle;
|
||||||
|
import net.minecraft.client.renderer.item.ItemStackRenderState;
|
||||||
|
import net.minecraft.client.renderer.state.gui.pip.PictureInPictureRenderState;
|
||||||
|
import org.joml.Matrix4fc;
|
||||||
|
import org.joml.Vector3fc;
|
||||||
|
|
||||||
|
/** One depth-buffered viewport for every bone, preserving occlusion between parts. */
|
||||||
|
public record PreviewRenderState(List<Part> parts, Vector3fc center, float yaw, float pitch,
|
||||||
|
int x0, int y0, int x1, int y1, float scale,
|
||||||
|
ScreenRectangle scissorArea) implements PictureInPictureRenderState {
|
||||||
|
public PreviewRenderState { parts = List.copyOf(parts); }
|
||||||
|
|
||||||
|
@Override public ScreenRectangle bounds() {
|
||||||
|
return PictureInPictureRenderState.getBounds(x0, y0, x1, y1, scissorArea);
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Part(ItemStackRenderState item, Matrix4fc transform) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import com.mojang.blaze3d.platform.Lighting;
|
||||||
|
import com.mojang.blaze3d.vertex.PoseStack;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.client.gui.render.pip.PictureInPictureRenderer;
|
||||||
|
import net.minecraft.client.renderer.SubmitNodeCollector;
|
||||||
|
import net.minecraft.client.renderer.texture.OverlayTexture;
|
||||||
|
import net.neoforged.neoforge.client.event.RegisterPictureInPictureRenderersEvent;
|
||||||
|
import org.joml.Matrix4f;
|
||||||
|
|
||||||
|
/** NeoForge's native GUI renderer; no world entities or extra game registries. */
|
||||||
|
public final class PreviewRenderer extends PictureInPictureRenderer<PreviewRenderState> {
|
||||||
|
public static void register(RegisterPictureInPictureRenderersEvent event) {
|
||||||
|
event.register(PreviewRenderState.class, PreviewRenderer::new);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public Class<PreviewRenderState> getRenderStateClass() { return PreviewRenderState.class; }
|
||||||
|
|
||||||
|
@Override protected void renderToTexture(PreviewRenderState state, PoseStack poses, SubmitNodeCollector collector) {
|
||||||
|
Minecraft.getInstance().gameRenderer.lighting().setupFor(Lighting.Entry.ENTITY_IN_UI);
|
||||||
|
poses.scale(1, -1, 1);
|
||||||
|
poses.mulPose(new Matrix4f().rotationX(state.pitch()).rotateY(state.yaw())
|
||||||
|
.translate(-state.center().x(), -state.center().y(), -state.center().z()));
|
||||||
|
for (var part : state.parts()) {
|
||||||
|
poses.pushPose(); poses.mulPose(part.transform());
|
||||||
|
part.item().submit(poses, collector, 15728880, OverlayTexture.NO_OVERLAY, 0);
|
||||||
|
poses.popPose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override protected float getTranslateY(int height, int guiScale) { return height / 2F; }
|
||||||
|
@Override protected String getTextureLabel() { return "AstraPlus model preview"; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.renderer.item.ItemStackRenderState;
|
||||||
|
import net.minecraft.core.component.DataComponents;
|
||||||
|
import net.minecraft.resources.Identifier;
|
||||||
|
import net.minecraft.world.item.ItemDisplayContext;
|
||||||
|
import net.minecraft.world.item.ItemStack;
|
||||||
|
import net.minecraft.world.item.Items;
|
||||||
|
import org.joml.Matrix4f;
|
||||||
|
import org.joml.Vector3f;
|
||||||
|
|
||||||
|
/** Resolves actual resource-pack items and fits their assembled geometry in the viewport. */
|
||||||
|
public final class PreviewScene {
|
||||||
|
private final PreviewModel model;
|
||||||
|
private final List<ItemStack> stacks = new ArrayList<>();
|
||||||
|
private final List<String> missing = new ArrayList<>();
|
||||||
|
private Vector3f center = new Vector3f();
|
||||||
|
private float radius = 1;
|
||||||
|
private boolean fitted;
|
||||||
|
|
||||||
|
public PreviewScene(PreviewModel model) {
|
||||||
|
this.model = model;
|
||||||
|
if (Minecraft.getInstance().level == null)
|
||||||
|
throw new IllegalStateException("Предпросмотр доступен после входа на сервер.");
|
||||||
|
var resources = Minecraft.getInstance().getResourceManager();
|
||||||
|
for (var bone : model.bones()) {
|
||||||
|
ItemStack stack = ItemStack.EMPTY;
|
||||||
|
if (bone.itemModel() != null) {
|
||||||
|
Identifier id = Identifier.tryParse(bone.itemModel());
|
||||||
|
if (id == null || resources.getResource(Identifier.fromNamespaceAndPath(id.getNamespace(), "items/" + id.getPath() + ".json")).isEmpty())
|
||||||
|
missing.add(bone.itemModel());
|
||||||
|
else {
|
||||||
|
stack = new ItemStack(Items.PAPER); stack.set(DataComponents.ITEM_MODEL, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stacks.add(stack);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public PreviewModel model() { return model; }
|
||||||
|
public List<String> missing() { return List.copyOf(missing); }
|
||||||
|
public boolean hasGeometry() { return stacks.stream().anyMatch(stack -> !stack.isEmpty()); }
|
||||||
|
|
||||||
|
public void extract(GuiGraphicsExtractor graphics, int x0, int y0, int x1, int y1,
|
||||||
|
float time, float yaw, float pitch, float zoom) {
|
||||||
|
if (x1 <= x0 || y1 <= y0 || !missing.isEmpty()) return;
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
Matrix4f[] transforms = PreviewPose.matrices(model, time);
|
||||||
|
List<PreviewRenderState.Part> parts = new ArrayList<>();
|
||||||
|
Vector3f minimum = new Vector3f(Float.POSITIVE_INFINITY), maximum = new Vector3f(Float.NEGATIVE_INFINITY);
|
||||||
|
for (int index = 0; index < stacks.size(); index++) {
|
||||||
|
if (stacks.get(index).isEmpty()) continue;
|
||||||
|
var item = new ItemStackRenderState();
|
||||||
|
minecraft.getItemModelResolver().updateForTopItem(item, stacks.get(index), ItemDisplayContext.NONE,
|
||||||
|
minecraft.level, minecraft.player, 0);
|
||||||
|
Matrix4f transform = new Matrix4f(transforms[index]).scale(model.bones().get(index).geometryScale() * 16);
|
||||||
|
if (!transform.isFinite()) throw new IllegalArgumentException("Недопустимый масштаб геометрии модели.");
|
||||||
|
if (!fitted) item.visitExtents(point -> {
|
||||||
|
Vector3f transformed = new Vector3f(point).mulPosition(transform);
|
||||||
|
minimum.min(transformed); maximum.max(transformed);
|
||||||
|
});
|
||||||
|
parts.add(new PreviewRenderState.Part(item, transform));
|
||||||
|
}
|
||||||
|
if (!fitted && Float.isFinite(minimum.x)) {
|
||||||
|
center = new Vector3f(minimum).add(maximum).mul(0.5F);
|
||||||
|
radius = Math.max(0.05F, minimum.distance(maximum) / 2);
|
||||||
|
if (!center.isFinite() || !Float.isFinite(radius))
|
||||||
|
throw new IllegalArgumentException("Геометрия модели слишком велика для предпросмотра.");
|
||||||
|
fitted = true;
|
||||||
|
}
|
||||||
|
float fit = Math.min(x1 - x0, y1 - y0) * 0.42F / radius * zoom;
|
||||||
|
graphics.submitPictureInPictureRenderState(new PreviewRenderState(parts, new Vector3f(center), yaw, pitch,
|
||||||
|
x0, y0, x1, y1, fit, graphics.peekScissorStack()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,6 +43,7 @@ public final class ContentDraft {
|
|||||||
public String revision() { return revision; }
|
public String revision() { return revision; }
|
||||||
public boolean dirty() { return fresh() || !document.equals(saved); }
|
public boolean dirty() { return fresh() || !document.equals(saved); }
|
||||||
public JsonObject document() { return document.deepCopy(); }
|
public JsonObject document() { return document.deepCopy(); }
|
||||||
|
public void replace(JsonObject document) { this.document = document.deepCopy(); }
|
||||||
|
|
||||||
public JsonElement get(String... path) {
|
public JsonElement get(String... path) {
|
||||||
JsonElement value = document;
|
JsonElement value = document;
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
/** Mob IDs belong to their file path and may be omitted from the stored JSON body. */
|
||||||
|
public final class MobDocuments {
|
||||||
|
private MobDocuments() {}
|
||||||
|
public static JsonObject document(JsonObject response) {
|
||||||
|
var document = response.getAsJsonObject("document").deepCopy();
|
||||||
|
document.addProperty("id", response.get("id").getAsString());
|
||||||
|
return document;
|
||||||
|
}
|
||||||
|
public static ContentDraft draft(JsonObject response) {
|
||||||
|
return new ContentDraft(document(response), response.get("revision").getAsString());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
|
||||||
|
/** Typed controls for supported server settings; untouched defaults remain inherited. */
|
||||||
|
public final class MobFields {
|
||||||
|
private MobFields() {}
|
||||||
|
public static List<FormField> basic(ContentDraft draft, EditorCatalog catalog, boolean skill) {
|
||||||
|
var result = new ArrayList<FormField>();
|
||||||
|
if (draft.fresh()) result.add(DataFields.text(draft, "Идентификатор", "namespace:путь, без пробелов", "", List.of(), "id"));
|
||||||
|
result.add(DataFields.text(draft, "Название", skill ? "Название в каталоге редактора" : "Имя моба в мире", "", List.of(), "name"));
|
||||||
|
if (skill) result.add(DataFields.number(draft, "Перезарядка, секунды", "Пауза перед следующим применением", "0", false, 0, 72000, "cooldown"));
|
||||||
|
else {
|
||||||
|
result.add(DataFields.text(draft, "Ванильная основа", "Определяет базовую физику и поведение", "minecraft:pig", catalog.values("mobEntities"), "entity"));
|
||||||
|
result.add(DataFields.number(draft, "Здоровье", "2 единицы = 1 сердце", "20", false, 0.01, 1000000, "health"));
|
||||||
|
result.add(DataFields.number(draft, "Урон атаки", "Базовое значение для обычной атаки", "0", false, 0, 1000000, "damage"));
|
||||||
|
result.add(DataFields.number(draft, "Броня", "Очки брони", "0", false, 0, 1000000, "armor"));
|
||||||
|
result.add(DataFields.text(draft, "Фракция", "Пусто: фракция не назначена", "", List.of(), "faction"));
|
||||||
|
}
|
||||||
|
result.add(FormField.text("sourceId", "Псевдоним ссылок", "Необязательно. Сохраняет ссылки существующих навыков", () -> draft.text("", "sourceId"),
|
||||||
|
value -> { if (value.isBlank()) draft.set(null, "sourceId"); else draft.string(value.trim(), "sourceId"); }));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FormField> options(ContentDraft local) {
|
||||||
|
return List.of(
|
||||||
|
optionalNumber(local, "Скорость движения", "Наследуется от ванильной основы", "MovementSpeed"),
|
||||||
|
optionalNumber(local, "Дальность преследования", "Наследуется от ванильной основы", "FollowRange"),
|
||||||
|
optionalNumber(local, "Сопротивление отбрасыванию", "Наследуется от ванильной основы", "KnockbackResistance"),
|
||||||
|
optionalNumber(local, "Неуязвимость после удара, тики", "По умолчанию: 10", "NoDamageTicks"),
|
||||||
|
optionalNumber(local, "Максимальная дистанция боя", "По умолчанию: 256 блоков", "MaxCombatDistance"),
|
||||||
|
DataFields.bool(local, "Без звуков", false, "options", "Silent"),
|
||||||
|
DataFields.bool(local, "Неуязвимость", false, "options", "Invincible"),
|
||||||
|
DataFields.bool(local, "Невидимость основы", false, "options", "Invisible"),
|
||||||
|
DataFields.bool(local, "Физические столкновения", true, "options", "Collidable"),
|
||||||
|
DataFields.bool(local, "Без гравитации", false, "options", "NoGravity"),
|
||||||
|
DataFields.bool(local, "Естественное исчезновение", true, "options", "Despawn"),
|
||||||
|
DataFields.bool(local, "Убрать случайную экипировку", false, "options", "PreventRandomEquipment"),
|
||||||
|
DataFields.bool(local, "Заменить ванильный лут", false, "options", "PreventOtherDrops"),
|
||||||
|
DataFields.bool(local, "Учитывать угрозу при выборе цели", false, "modules", "ThreatTable"),
|
||||||
|
DataFields.number(local, "Множитель урона от падения", "0 = иммунитет, 1 = обычный урон", "1", false, 0, 100, "damageModifiers", "FALL"),
|
||||||
|
DataFields.number(local, "Множитель урона от удушья", "0 = иммунитет, 1 = обычный урон", "1", false, 0, 100, "damageModifiers", "SUFFOCATION"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static FormField optionalNumber(ContentDraft local, String label, String hint, String key) {
|
||||||
|
return FormField.text("options/" + key, label, hint, () -> local.text("", "options", key),
|
||||||
|
value -> local.number(value, key.equals("NoDamageTicks"), 0, 72000, "options", key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<FormField> condition(ContentDraft local, EditorCatalog catalog, boolean inline) {
|
||||||
|
String name = local.text("incombat", "call", "name");
|
||||||
|
var result = new ArrayList<FormField>();
|
||||||
|
result.add(new FormField("mode", "Когда разрешить действие", "Все условия списка должны выполняться",
|
||||||
|
() -> switch (local.text("true", "mode")) { case "false" -> "Условие ложно"; case "fallback" -> "Иначе вызвать навык"; default -> "Условие истинно"; },
|
||||||
|
value -> local.string(switch (value) { case "Условие ложно" -> "false"; case "Иначе вызвать навык" -> "fallback"; default -> "true"; }, "mode"),
|
||||||
|
inline ? List.of("Условие истинно", "Условие ложно") : List.of("Условие истинно", "Условие ложно", "Иначе вызвать навык"), true));
|
||||||
|
if (name.equals("targetwithin") || name.equals("playerwithin")) {
|
||||||
|
String key = local.get("call", "arguments", "distance").isJsonNull() ? "d" : "distance";
|
||||||
|
result.add(DataFields.number(local, "Расстояние, блоки", "Радиус проверки от моба", "10", false, 0, 72000, "call", "arguments", key));
|
||||||
|
}
|
||||||
|
if (name.equals("hasaura")) {
|
||||||
|
String key = local.get("call", "arguments", "name").isJsonNull() ? "n" : "name";
|
||||||
|
result.add(DataFields.text(local, "Имя ауры", "Имя, указанное действием aura", "", List.of(), "call", "arguments", key));
|
||||||
|
}
|
||||||
|
if (name.equals("modelhaspassenger")) {
|
||||||
|
String key = local.get("call", "arguments", "part").isJsonNull() ? "p" : "part";
|
||||||
|
result.add(DataFields.text(local, "Кость модели", "Пусто: любое место пассажира", "", catalog.values("bones"), "call", "arguments", key));
|
||||||
|
}
|
||||||
|
if (!inline) result.add(DataFields.text(local, "Резервный навык", "Используется только в режиме «Иначе вызвать навык»", "", catalog.values("skills"), "fallback"));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String actionName(String name) {
|
||||||
|
return switch (name) {
|
||||||
|
case "skill" -> "Вызвать навык"; case "randomskill" -> "Случайный навык"; case "delay" -> "Пауза";
|
||||||
|
case "damage" -> "Нанести урон"; case "basedamage" -> "Базовый урон"; case "model" -> "Прикрепить модель";
|
||||||
|
case "state" -> "Запустить анимацию"; case "aura" -> "Аура"; case "potion" -> "Эффект зелья";
|
||||||
|
case "summon" -> "Призвать моба"; case "remove" -> "Удалить сущность"; case "sound" -> "Звук";
|
||||||
|
case "particles", "e:p" -> "Частицы"; case "javascript", "js" -> "JavaScript";
|
||||||
|
case "setai" -> "Управление ИИ"; case "settarget" -> "Назначить цель"; case "setspeed" -> "Скорость";
|
||||||
|
case "cancelevent" -> "Отменить событие"; case "setnodamageticks" -> "Пауза между повреждениями";
|
||||||
|
case "lockmodel" -> "Закрепить поворот модели"; case "mountmodel" -> "Посадить на модель";
|
||||||
|
case "dismountallmodel" -> "Высадить пассажиров"; case "velocity" -> "Скорость по осям";
|
||||||
|
case "teleport", "teleportto" -> "Телепортация"; case "lunge" -> "Рывок"; case "throw" -> "Отбросить";
|
||||||
|
case "missile" -> "Самонаводящийся снаряд"; case "projectile" -> "Снаряд"; case "totem" -> "Область действия";
|
||||||
|
default -> name;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String triggerName(String trigger) {
|
||||||
|
String lower = trigger.toLowerCase(java.util.Locale.ROOT);
|
||||||
|
if (lower.startsWith("ontimer:")) return "Каждые " + trigger.substring(8) + " тиков";
|
||||||
|
return switch (lower) {
|
||||||
|
case "onspawn" -> "При призыве"; case "onload" -> "При загрузке из мира"; case "onattack" -> "При атаке";
|
||||||
|
case "ondeath" -> "При смерти"; case "onentercombat" -> "При вступлении в бой"; case "" -> "В последовательности";
|
||||||
|
default -> trigger;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String actionSummary(String source) {
|
||||||
|
try {
|
||||||
|
var value = MobSyntax.action(source);
|
||||||
|
var action = value.getAsJsonObject("action");
|
||||||
|
String suffix = value.getAsJsonArray("conditions").isEmpty() ? "" : " Условия: " + value.getAsJsonArray("conditions").size();
|
||||||
|
return triggerName(value.get("trigger").getAsString()) + ": " + actionName(action.get("name").getAsString()) + suffix;
|
||||||
|
} catch (RuntimeException ignored) { return "Сложная запись: " + source; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
/** Lossless editing of nested action arguments; no script code is executed on the client. */
|
||||||
|
public final class MobSyntax {
|
||||||
|
private MobSyntax() {}
|
||||||
|
|
||||||
|
public static List<String> split(String text, char separator) {
|
||||||
|
var values = new ArrayList<String>();
|
||||||
|
int start = 0, depth = 0;
|
||||||
|
boolean quoted = false, escaped = false;
|
||||||
|
for (int i = 0; i < text.length(); i++) {
|
||||||
|
char c = text.charAt(i);
|
||||||
|
if (quoted) {
|
||||||
|
if (escaped) escaped = false;
|
||||||
|
else if (c == '\\') escaped = true;
|
||||||
|
else if (c == '"') quoted = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '"') { quoted = true; continue; }
|
||||||
|
if (c == '{' || c == '[' || c == '<') depth++;
|
||||||
|
if (c == '}' || c == ']' || c == '>') depth--;
|
||||||
|
if (depth < 0) throw new IllegalArgumentException("Нарушен порядок скобок.");
|
||||||
|
if (depth == 0 && c == separator) {
|
||||||
|
String part = text.substring(start, i).trim();
|
||||||
|
if (!part.isEmpty()) values.add(part);
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (depth != 0 || quoted) throw new IllegalArgumentException("Закройте скобки и кавычки.");
|
||||||
|
String last = text.substring(start).trim();
|
||||||
|
if (!last.isEmpty()) values.add(last);
|
||||||
|
return List.copyOf(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject call(String source) {
|
||||||
|
int open = source.indexOf('{');
|
||||||
|
var result = new JsonObject();
|
||||||
|
result.addProperty("name", (open < 0 ? source : source.substring(0, open)).trim().toLowerCase(Locale.ROOT));
|
||||||
|
var args = new JsonObject();
|
||||||
|
if (open >= 0) {
|
||||||
|
if (!source.endsWith("}")) throw new IllegalArgumentException("Закройте параметры действия.");
|
||||||
|
for (String part : split(source.substring(open + 1, source.length() - 1), ';')) {
|
||||||
|
int equals = part.indexOf('=');
|
||||||
|
if (equals < 1) throw new IllegalArgumentException("Параметр записывается как имя=значение.");
|
||||||
|
String key = part.substring(0, equals).trim();
|
||||||
|
if (args.has(key)) throw new IllegalArgumentException("Повтор параметра: " + key);
|
||||||
|
args.addProperty(key, part.substring(equals + 1).trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result.add("arguments", args);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String call(JsonObject value) {
|
||||||
|
String name = value.get("name").getAsString().trim();
|
||||||
|
if (name.isEmpty() || name.contains(" ")) throw new IllegalArgumentException("Укажите имя действия или условия.");
|
||||||
|
var args = value.getAsJsonObject("arguments");
|
||||||
|
if (args == null || args.isEmpty()) return name;
|
||||||
|
var fields = new ArrayList<String>();
|
||||||
|
args.entrySet().forEach(entry -> fields.add(entry.getKey() + "=" + (entry.getValue().isJsonPrimitive()
|
||||||
|
? entry.getValue().getAsString() : entry.getValue().toString())));
|
||||||
|
String result = name + "{" + String.join(";", fields) + "}";
|
||||||
|
split(result, ' ');
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject action(String source) {
|
||||||
|
String cleaned = source.trim();
|
||||||
|
if (cleaned.startsWith("- ")) cleaned = cleaned.substring(2).trim();
|
||||||
|
var words = split(cleaned, ' ');
|
||||||
|
if (words.isEmpty()) throw new IllegalArgumentException("Укажите действие.");
|
||||||
|
var result = new JsonObject();
|
||||||
|
result.add("action", call(words.getFirst()));
|
||||||
|
result.addProperty("trigger", "");
|
||||||
|
result.addProperty("target", "");
|
||||||
|
result.addProperty("chance", 1);
|
||||||
|
var conditions = new JsonArray();
|
||||||
|
for (int i = 1; i < words.size(); i++) {
|
||||||
|
String word = words.get(i);
|
||||||
|
if (word.startsWith("@")) result.addProperty("target", word.substring(1));
|
||||||
|
else if (word.startsWith("~")) result.addProperty("trigger", word.substring(1));
|
||||||
|
else if (word.startsWith("?!")) conditions.add(word.substring(2) + " false");
|
||||||
|
else if (word.startsWith("?")) conditions.add(word.substring(1) + " true");
|
||||||
|
else if (result.getAsJsonObject("action").get("name").getAsString().equals("delay"))
|
||||||
|
result.getAsJsonObject("action").getAsJsonObject("arguments").addProperty("ticks", word);
|
||||||
|
else result.addProperty("chance", Double.parseDouble(word));
|
||||||
|
}
|
||||||
|
result.add("conditions", conditions);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String action(JsonObject value) {
|
||||||
|
var parts = new ArrayList<String>();
|
||||||
|
parts.add(call(value.getAsJsonObject("action")));
|
||||||
|
String target = value.get("target").getAsString().trim(), trigger = value.get("trigger").getAsString().trim();
|
||||||
|
if (!target.isEmpty()) { call(target); parts.add("@" + target); }
|
||||||
|
if (!trigger.isEmpty()) parts.add("~" + trigger);
|
||||||
|
double chance = value.get("chance").getAsDouble();
|
||||||
|
if (!Double.isFinite(chance) || chance < 0 || chance > 1) throw new IllegalArgumentException("Вероятность должна быть от 0 до 1.");
|
||||||
|
if (chance != 1) parts.add(Double.toString(chance));
|
||||||
|
for (var condition : value.getAsJsonArray("conditions")) {
|
||||||
|
var parsed = condition(condition.getAsString());
|
||||||
|
String mode = parsed.get("mode").getAsString();
|
||||||
|
if (mode.equals("fallback")) throw new IllegalArgumentException("Резервный навык задаётся в условиях отдельного навыка.");
|
||||||
|
parts.add((mode.equals("false") ? "?!" : "?") + call(parsed.getAsJsonObject("call")));
|
||||||
|
}
|
||||||
|
return String.join(" ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static JsonObject condition(String source) {
|
||||||
|
var words = split(source.trim(), ' ');
|
||||||
|
if (words.isEmpty()) throw new IllegalArgumentException("Укажите условие.");
|
||||||
|
var result = new JsonObject();
|
||||||
|
result.add("call", call(words.getFirst()));
|
||||||
|
String mode = words.size() > 1 ? words.get(1) : "true";
|
||||||
|
if (!List.of("true", "false", "orelsecast").contains(mode.toLowerCase(Locale.ROOT)))
|
||||||
|
throw new IllegalArgumentException("Неизвестный режим условия: " + mode);
|
||||||
|
result.addProperty("mode", mode.equalsIgnoreCase("orElseCast") ? "fallback" : mode.toLowerCase(Locale.ROOT));
|
||||||
|
result.addProperty("fallback", words.size() > 2 ? words.get(2) : "");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String condition(JsonObject value) {
|
||||||
|
String mode = value.get("mode").getAsString();
|
||||||
|
String fallback = value.get("fallback").getAsString().trim();
|
||||||
|
if (mode.equals("fallback") && fallback.isEmpty()) throw new IllegalArgumentException("Выберите резервный навык.");
|
||||||
|
return call(value.getAsJsonObject("call")) + (mode.equals("fallback") ? " orElseCast " + fallback : " " + mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String conditionName(String id) {
|
||||||
|
return switch (id.toLowerCase(Locale.ROOT)) {
|
||||||
|
case "incombat" -> "Моб участвует в бою";
|
||||||
|
case "targetwithin" -> "Цель в радиусе";
|
||||||
|
case "playerwithin" -> "Игрок в радиусе";
|
||||||
|
case "hasaura" -> "Есть аура";
|
||||||
|
case "hasmodel" -> "Модель прикреплена";
|
||||||
|
case "isblocking" -> "Блокирует щитом";
|
||||||
|
case "modelhaspassenger" -> "На модели есть пассажир";
|
||||||
|
default -> id;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String conditionSummary(String source) {
|
||||||
|
try {
|
||||||
|
var value = condition(source);
|
||||||
|
var call = value.getAsJsonObject("call");
|
||||||
|
String name = conditionName(call.get("name").getAsString());
|
||||||
|
String mode = value.get("mode").getAsString();
|
||||||
|
if (mode.equals("false")) name = "Не выполняется: " + name;
|
||||||
|
if (!call.getAsJsonObject("arguments").isEmpty()) name += " " + call.getAsJsonObject("arguments").entrySet().stream()
|
||||||
|
.map(entry -> entry.getValue().getAsString()).collect(java.util.stream.Collectors.joining(", "));
|
||||||
|
if (mode.equals("fallback")) name += " Иначе: " + value.get("fallback").getAsString();
|
||||||
|
return name;
|
||||||
|
} catch (RuntimeException ignored) { return source; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
|||||||
public final class EditorConnection {
|
public final class EditorConnection {
|
||||||
public static final EditorConnection INSTANCE = new EditorConnection();
|
public static final EditorConnection INSTANCE = new EditorConnection();
|
||||||
private final Map<Integer, Pending> pending = new HashMap<>();
|
private final Map<Integer, Pending> pending = new HashMap<>();
|
||||||
|
private final Map<Integer, ResponseChunks> responses = new HashMap<>();
|
||||||
private ClientPacketListener connection;
|
private ClientPacketListener connection;
|
||||||
private int nextRequest;
|
private int nextRequest;
|
||||||
|
|
||||||
@@ -45,16 +46,15 @@ public final class EditorConnection {
|
|||||||
var request = body.deepCopy();
|
var request = body.deepCopy();
|
||||||
request.addProperty("requestId", requestId);
|
request.addProperty("requestId", requestId);
|
||||||
request.addProperty("action", action);
|
request.addProperty("action", action);
|
||||||
|
request.addProperty("responseChunks", true);
|
||||||
String json = request.toString();
|
String json = request.toString();
|
||||||
if (json.length() > EditorRequest.LIMIT) {
|
long started = System.nanoTime();
|
||||||
callback.accept(error("Документ превышает лимит сетевого редактора (8192 символа). Сократите данные или измените файл на сервере."));
|
pending.put(requestId, new Pending(started, started, callback));
|
||||||
return;
|
|
||||||
}
|
|
||||||
pending.put(requestId, new Pending(System.nanoTime(), callback));
|
|
||||||
try {
|
try {
|
||||||
ClientPacketDistributor.sendToServer(new EditorRequest(json));
|
for (String packet : RequestChunks.encode(json, requestId)) ClientPacketDistributor.sendToServer(new EditorRequest(packet));
|
||||||
} catch (RuntimeException failure) {
|
} catch (RuntimeException failure) {
|
||||||
pending.remove(requestId);
|
pending.remove(requestId);
|
||||||
|
responses.remove(requestId);
|
||||||
callback.accept(error("Не удалось отправить запрос: " + failure.getMessage()));
|
callback.accept(error("Не удалось отправить запрос: " + failure.getMessage()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,25 +64,42 @@ public final class EditorConnection {
|
|||||||
if (current != connection) {
|
if (current != connection) {
|
||||||
var abandoned = Map.copyOf(pending);
|
var abandoned = Map.copyOf(pending);
|
||||||
pending.clear();
|
pending.clear();
|
||||||
|
responses.clear();
|
||||||
connection = current;
|
connection = current;
|
||||||
abandoned.values().forEach(value -> value.callback.accept(error("Подключение изменилось. Черновик не сохранён.")));
|
abandoned.values().forEach(value -> value.callback.accept(error("Подключение изменилось. Черновик не сохранён.")));
|
||||||
}
|
}
|
||||||
long now = System.nanoTime();
|
long now = System.nanoTime();
|
||||||
var expired = pending.entrySet().stream()
|
var expired = pending.entrySet().stream()
|
||||||
.filter(entry -> now - entry.getValue().started > 15_000_000_000L).toList();
|
.filter(entry -> now - entry.getValue().progressed > 15_000_000_000L || now - entry.getValue().started > 60_000_000_000L).toList();
|
||||||
for (var entry : expired) {
|
for (var entry : expired) {
|
||||||
pending.remove(entry.getKey());
|
pending.remove(entry.getKey());
|
||||||
|
responses.remove(entry.getKey());
|
||||||
entry.getValue().callback.accept(error("Сервер не ответил. Перед повторным сохранением проверьте актуальную версию."));
|
entry.getValue().callback.accept(error("Сервер не ответил. Перед повторным сохранением проверьте актуальную версию."));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void receive(EditorResponse payload) {
|
private void receive(EditorResponse payload) {
|
||||||
|
Integer requestId = null;
|
||||||
try {
|
try {
|
||||||
var response = JsonParser.parseString(payload.json()).getAsJsonObject();
|
var response = JsonParser.parseString(payload.json()).getAsJsonObject();
|
||||||
var request = pending.remove(response.get("requestId").getAsInt());
|
requestId = response.get("requestId").getAsInt();
|
||||||
|
if (!pending.containsKey(requestId)) return;
|
||||||
|
if (response.has("action") && response.get("action").getAsString().equals("response_chunk")) {
|
||||||
|
response = responses.computeIfAbsent(requestId, ResponseChunks::new).accept(response);
|
||||||
|
if (response == null) {
|
||||||
|
var request = pending.get(requestId);
|
||||||
|
pending.put(requestId, new Pending(request.started, System.nanoTime(), request.callback));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (responses.containsKey(requestId)) throw new IllegalArgumentException("Сервер прервал последовательность ответа.");
|
||||||
|
responses.remove(requestId);
|
||||||
|
var request = pending.remove(requestId);
|
||||||
if (request != null) request.callback.accept(response);
|
if (request != null) request.callback.accept(response);
|
||||||
} catch (RuntimeException ignored) {
|
} catch (RuntimeException failure) {
|
||||||
// Malformed or unsolicited replies cannot update a document; pending requests expire normally.
|
if (requestId == null) return;
|
||||||
|
responses.remove(requestId);
|
||||||
|
var request = pending.remove(requestId);
|
||||||
|
if (request != null) request.callback.accept(error("Не удалось получить полный ответ сервера: " + failure.getMessage()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,5 +118,5 @@ public final class EditorConnection {
|
|||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
private record Pending(long started, Consumer<JsonObject> callback) {}
|
private record Pending(long started, long progressed, Consumer<JsonObject> callback) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package online.astradev.plus.editor.network;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
|
||||||
|
/** Large documents use bounded vanilla payloads with one logical request and one response. */
|
||||||
|
public final class RequestChunks {
|
||||||
|
private RequestChunks() {}
|
||||||
|
public static List<String> encode(String json, int requestId) {
|
||||||
|
if (json.length() <= 8192) return List.of(json);
|
||||||
|
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (bytes.length > 1048576) throw new IllegalArgumentException("Документ превышает 1 МиБ.");
|
||||||
|
String encoded = Base64.getEncoder().encodeToString(bytes);
|
||||||
|
int total = (encoded.length() + 5999) / 6000;
|
||||||
|
var packets = new ArrayList<String>(total);
|
||||||
|
for (int index = 0; index < total; index++) {
|
||||||
|
var chunk = new JsonObject(); chunk.addProperty("action", "request_chunk"); chunk.addProperty("requestId", requestId);
|
||||||
|
chunk.addProperty("index", index); chunk.addProperty("total", total);
|
||||||
|
chunk.addProperty("data", encoded.substring(index * 6000, Math.min(encoded.length(), (index + 1) * 6000)));
|
||||||
|
packets.add(chunk.toString());
|
||||||
|
}
|
||||||
|
return List.copyOf(packets);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package online.astradev.plus.editor.network;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.charset.CharacterCodingException;
|
||||||
|
import java.nio.charset.CodingErrorAction;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
|
||||||
|
/** One bounded response assembly, owned by a pending request and discarded with it. */
|
||||||
|
public final class ResponseChunks {
|
||||||
|
private static final int BYTE_LIMIT = 32 * 1024 * 1024;
|
||||||
|
private static final int TEXT_LIMIT = ((BYTE_LIMIT + 2) / 3) * 4;
|
||||||
|
private final int requestId;
|
||||||
|
private final StringBuilder data = new StringBuilder();
|
||||||
|
private int next, total = -1;
|
||||||
|
|
||||||
|
public ResponseChunks(int requestId) { this.requestId = requestId; }
|
||||||
|
|
||||||
|
public JsonObject accept(JsonObject chunk) {
|
||||||
|
int index = integer(chunk, "index"), receivedTotal = integer(chunk, "total");
|
||||||
|
if (integer(chunk, "requestId") != requestId || index != next || receivedTotal < 1 || receivedTotal > 256
|
||||||
|
|| total >= 0 && total != receivedTotal || index >= receivedTotal)
|
||||||
|
throw new IllegalArgumentException("Нарушен порядок частей ответа сервера.");
|
||||||
|
if (!chunk.has("data") || !chunk.get("data").isJsonPrimitive() || !chunk.getAsJsonPrimitive("data").isString())
|
||||||
|
throw new IllegalArgumentException("Некорректные данные части ответа.");
|
||||||
|
String part = chunk.get("data").getAsString();
|
||||||
|
if (part.isEmpty() || part.length() > 180000 || data.length() + part.length() > TEXT_LIMIT)
|
||||||
|
throw new IllegalArgumentException("Ответ сервера превышает допустимый размер.");
|
||||||
|
if (!part.matches("[A-Za-z0-9+/]*={0,2}")) throw new IllegalArgumentException("Некорректная кодировка части ответа.");
|
||||||
|
if (index + 1 < receivedTotal && part.indexOf('=') >= 0) throw new IllegalArgumentException("Кодировка ответа завершилась до последней части.");
|
||||||
|
total = receivedTotal; next++; data.append(part);
|
||||||
|
if (next < total) return null;
|
||||||
|
byte[] bytes = Base64.getDecoder().decode(data.toString());
|
||||||
|
if (bytes.length > BYTE_LIMIT) throw new IllegalArgumentException("Ответ сервера превышает 32 МиБ.");
|
||||||
|
try {
|
||||||
|
String json = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
|
||||||
|
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
|
||||||
|
var response = JsonParser.parseString(json).getAsJsonObject();
|
||||||
|
if (integer(response, "requestId") != requestId || response.has("action") && response.get("action").getAsString().equals("response_chunk"))
|
||||||
|
throw new IllegalArgumentException("Ответ сервера не соответствует запросу.");
|
||||||
|
return response;
|
||||||
|
} catch (CharacterCodingException error) { throw new IllegalArgumentException("Ответ сервера содержит некорректный UTF-8.", error); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int integer(JsonObject value, String key) {
|
||||||
|
if (!value.has(key) || !value.get(key).isJsonPrimitive() || !value.getAsJsonPrimitive(key).isNumber())
|
||||||
|
throw new IllegalArgumentException("Ответ сервера не содержит " + key + ".");
|
||||||
|
try { return value.get(key).getAsBigDecimal().intValueExact(); }
|
||||||
|
catch (ArithmeticException error) { throw new IllegalArgumentException("Некорректный номер части ответа.", error); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,12 +28,16 @@ public final class ContentBrowserScreen extends EditorScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override protected void init() {
|
@Override protected void init() {
|
||||||
var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск")));
|
int tab = (width - 40) / 3;
|
||||||
|
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)));
|
||||||
|
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"));
|
||||||
search.setValue(query);
|
search.setValue(query);
|
||||||
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
||||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 64, width - 24, Math.max(25, height - 165), this::load));
|
list = addRenderableWidget(new ChoiceList(minecraft, 12, 92, width - 24, Math.max(25, height - 193), this::load));
|
||||||
list.values(rows.keySet().stream().toList());
|
list.values(rows.keySet().stream().toList());
|
||||||
int row = height - 94;
|
int row = height - 94;
|
||||||
int part = Math.max(50, (width - 48) / 4);
|
int part = Math.max(50, (width - 48) / 4);
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ public final class JsonObjectScreen extends EditorScreen {
|
|||||||
@Override protected void init() {
|
@Override protected void init() {
|
||||||
var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(40).setShowDecorations(false)
|
var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(40).setShowDecorations(false)
|
||||||
.setPlaceholder(Component.literal("{}")).build(font, width - 24, Math.max(30, height - 113), Component.literal("Параметры JSON")));
|
.setPlaceholder(Component.literal("{}")).build(font, width - 24, Math.max(30, height - 113), Component.literal("Параметры JSON")));
|
||||||
input.setCharacterLimit(Math.max(8192, value.length()));
|
input.setCharacterLimit(Math.max(1048576, value.length()));
|
||||||
input.setValue(value); input.setValueListener(text -> value = text);
|
input.setValue(value); input.setValueListener(text -> value = text);
|
||||||
button("Назад", 12, height - 27, 110, this::onClose);
|
button("Назад", 12, height - 27, 110, this::onClose);
|
||||||
button("В форму", width - 132, height - 27, 120, () -> {
|
button("В форму", width - 132, height - 27, 120, () -> {
|
||||||
@@ -34,7 +34,7 @@ public final class JsonObjectScreen extends EditorScreen {
|
|||||||
changed.accept(parsed.getAsJsonObject()); minecraft.gui.setScreen(parent);
|
changed.accept(parsed.getAsJsonObject()); minecraft.gui.setScreen(parent);
|
||||||
} catch (RuntimeException error) { status("Ошибка JSON: " + error.getMessage(), true); }
|
} catch (RuntimeException error) { status("Ошибка JSON: " + error.getMessage(), true); }
|
||||||
});
|
});
|
||||||
if (status.isBlank()) status("Дополнительные параметры сценария. Их названия и смысл определяет автор скрипта.", false);
|
if (status.isBlank()) status("Расширенный JSON текущей формы. Неизвестные поля сохраняются; перед применением сервер проверит определение.", false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public void onClose() {
|
@Override public void onClose() {
|
||||||
|
|||||||
@@ -13,7 +13,10 @@ public final class MessageScreen extends EditorScreen {
|
|||||||
private final String message;
|
private final String message;
|
||||||
|
|
||||||
public MessageScreen(Screen parent, String message) {
|
public MessageScreen(Screen parent, String message) {
|
||||||
super("AstraPlus: полное сообщение");
|
this(parent, "AstraPlus: полное сообщение", message);
|
||||||
|
}
|
||||||
|
public MessageScreen(Screen parent, String title, String message) {
|
||||||
|
super(title);
|
||||||
this.parent = parent;
|
this.parent = parent;
|
||||||
this.message = message;
|
this.message = message;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
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.screens.Screen;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.DataFields;
|
||||||
|
import online.astradev.plus.editor.form.FormField;
|
||||||
|
import online.astradev.plus.editor.form.MobFields;
|
||||||
|
import online.astradev.plus.editor.form.MobSyntax;
|
||||||
|
|
||||||
|
/** Common action controls keep nested argument expressions intact until explicitly edited. */
|
||||||
|
public final class MobActionForms {
|
||||||
|
private MobActionForms() {}
|
||||||
|
public static void open(Screen parent, EditorCatalog catalog, String source, boolean mob, Consumer<String> changed) {
|
||||||
|
var initial = MobSyntax.action(source);
|
||||||
|
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Действие: " + MobFields.actionName(initial.getAsJsonObject("action").get("name").getAsString()), initial,
|
||||||
|
local -> fields(local, catalog, mob), accepted -> changed.accept(MobSyntax.action(accepted)), List.of(
|
||||||
|
new SettingsScreen.Action("Параметры действия", (screen, local) -> arguments(screen, local, catalog, "action")),
|
||||||
|
new SettingsScreen.Action("Условия выполнения", (screen, local) -> Minecraft.getInstance().gui.setScreen(new MobConditionsScreen(screen, catalog,
|
||||||
|
"Условия действия", local.get("conditions").getAsJsonArray(), true, values -> local.set(values, "conditions")))),
|
||||||
|
new SettingsScreen.Action("Параметры цели", (screen, local) -> target(screen, local, catalog))),
|
||||||
|
"Изменения попадут в определение после кнопки «В черновик». Вложенные выражения параметров сохраняются."));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<FormField> fields(ContentDraft local, EditorCatalog catalog, boolean mob) {
|
||||||
|
var result = new ArrayList<FormField>();
|
||||||
|
result.add(DataFields.text(local, "Действие", "Выберите действие, затем настройте его параметры", "skill", catalog.values("actions"), "action", "name"));
|
||||||
|
result.add(DataFields.text(local, "Цель", "Пусто: цель передаётся вызывающим навыком. Параметры: имя{ключ=значение}", "", catalog.values("targets"), "target"));
|
||||||
|
if (mob) {
|
||||||
|
result.add(new FormField("trigger", "Событие", "Когда моб выполняет действие", () -> MobFields.triggerName(local.text("", "trigger")), selected -> {
|
||||||
|
String trigger = switch (selected) {
|
||||||
|
case "При призыве" -> "onSpawn"; case "При загрузке из мира" -> "onLoad"; case "При атаке" -> "onAttack";
|
||||||
|
case "При смерти" -> "onDeath"; case "При вступлении в бой" -> "onEnterCombat"; case "По таймеру" -> "onTimer:20";
|
||||||
|
default -> "";
|
||||||
|
};
|
||||||
|
local.string(trigger, "trigger");
|
||||||
|
}, List.of("При призыве", "При загрузке из мира", "При атаке", "При смерти", "При вступлении в бой", "По таймеру"), true));
|
||||||
|
if (local.text("", "trigger").toLowerCase(java.util.Locale.ROOT).startsWith("ontimer:")) result.add(FormField.text("interval", "Интервал, тики", "20 тиков = 1 секунда",
|
||||||
|
() -> local.text("onTimer:20", "trigger").substring(8), value -> {
|
||||||
|
int interval = Integer.parseInt(value); if (interval < 1 || interval > 72000) throw new IllegalArgumentException("Допустимо от 1 до 72000 тиков.");
|
||||||
|
local.string("onTimer:" + interval, "trigger");
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
result.add(DataFields.number(local, "Вероятность", "От 0 до 1. 1 = каждый раз, 0.25 = 25%", "1", false, 0, 1, "chance"));
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void arguments(Screen parent, ContentDraft owner, EditorCatalog catalog, String key) {
|
||||||
|
String name = owner.text("skill", key, "name");
|
||||||
|
var args = owner.get(key, "arguments").getAsJsonObject();
|
||||||
|
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Параметры: " + MobFields.actionName(name), args,
|
||||||
|
local -> argumentFields(local, catalog, name), value -> owner.set(value, key, "arguments"), List.of(
|
||||||
|
new SettingsScreen.Action("Добавить параметр", (screen, local) -> Minecraft.getInstance().gui.setScreen(new ChoiceScreen(screen, "Параметр действия",
|
||||||
|
parameterNames(name), selected -> local.string("", selected)))),
|
||||||
|
new SettingsScreen.Action("Расширенный JSON параметров", (screen, local) -> Minecraft.getInstance().gui.setScreen(new JsonObjectScreen(screen,
|
||||||
|
"Параметры действия: расширенный режим", local.document(), value -> {
|
||||||
|
for (String old : local.document().keySet()) local.set(null, old);
|
||||||
|
value.entrySet().forEach(entry -> local.set(entry.getValue(), entry.getKey()));
|
||||||
|
})))), "Пустой параметр удаляется из действия. Вложенные последовательности доступны в расширенном режиме."));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<FormField> argumentFields(ContentDraft local, EditorCatalog catalog, String action) {
|
||||||
|
var result = new ArrayList<FormField>();
|
||||||
|
var keys = new java.util.LinkedHashSet<>(local.document().keySet());
|
||||||
|
for (String key : parameterNames(action)) if (keys.stream().noneMatch(existing -> aliases(key).contains(existing.toLowerCase(java.util.Locale.ROOT)))) keys.add(key);
|
||||||
|
for (String key : keys) {
|
||||||
|
List<String> choices = switch (key.toLowerCase(java.util.Locale.ROOT)) {
|
||||||
|
case "mid", "model" -> catalog.values("models");
|
||||||
|
case "script" -> catalog.values("scripts");
|
||||||
|
case "s", "skill" -> action.equals("skill") ? catalog.values("skills") : List.of();
|
||||||
|
case "pbone", "part" -> catalog.values("bones");
|
||||||
|
default -> List.of();
|
||||||
|
};
|
||||||
|
result.add(new FormField(key, parameterLabel(key), "Параметр " + key + ". Пустое значение удаляет настройку.",
|
||||||
|
() -> local.get(key).isJsonNull() ? "" : local.get(key).isJsonPrimitive() ? local.text("", key) : local.get(key).toString(), value -> {
|
||||||
|
if (value.isBlank()) local.set(null, key); else local.string(value, key);
|
||||||
|
}, choices, false));
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
private static List<String> aliases(String key) {
|
||||||
|
return switch (key) {
|
||||||
|
case "duration" -> List.of("duration", "d", "ticks", "md", "maxduration"); case "interval" -> List.of("interval", "i");
|
||||||
|
case "type" -> List.of("type", "t"); case "level" -> List.of("level", "l"); case "amount" -> List.of("amount", "a");
|
||||||
|
case "mid" -> List.of("mid", "model"); case "s" -> List.of("s", "skill", "state");
|
||||||
|
case "sound" -> List.of("sound", "s"); case "volume" -> List.of("volume", "v"); case "pitch" -> List.of("pitch", "p");
|
||||||
|
case "auraname" -> List.of("auraname", "n"); case "ontick" -> List.of("ontick", "ot", "ontickskill"); case "onhit" -> List.of("onhit", "oh");
|
||||||
|
case "refreshduration" -> List.of("refreshduration", "rd"); case "hitradius" -> List.of("hitradius", "hr");
|
||||||
|
case "verticalradius" -> List.of("verticalradius", "vr"); case "velocity" -> List.of("velocity", "v");
|
||||||
|
case "pbone" -> List.of("pbone", "p"); case "lock" -> List.of("lock", "l");
|
||||||
|
case "hs" -> List.of("hs", "hspread"); case "vs" -> List.of("vs", "vspread");
|
||||||
|
default -> List.of(key);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<String> parameterNames(String action) {
|
||||||
|
return switch (action) {
|
||||||
|
case "skill" -> List.of("s"); case "randomskill" -> List.of("skills"); case "delay" -> List.of("ticks");
|
||||||
|
case "damage" -> List.of("a", "preventknockback"); case "basedamage" -> List.of("multiplier", "preventknockback"); case "model" -> List.of("mid", "scale", "step");
|
||||||
|
case "state" -> List.of("s"); case "potion" -> List.of("type", "duration", "level");
|
||||||
|
case "javascript", "js" -> List.of("script", "parameters"); case "sound" -> List.of("sound", "volume", "pitch");
|
||||||
|
case "summon" -> List.of("type", "amount"); case "particles", "e:p" -> List.of("p", "amount", "hs", "vs", "speed", "color");
|
||||||
|
case "aura" -> List.of("auraname", "duration", "interval", "ontick", "refreshduration");
|
||||||
|
case "mountmodel", "dismountallmodel" -> List.of("pbone"); case "lockmodel" -> List.of("lock");
|
||||||
|
case "setai" -> List.of("ai"); case "setspeed" -> List.of("speed"); case "setnodamageticks" -> List.of("ticks");
|
||||||
|
case "velocity" -> List.of("x", "y", "z", "mode"); case "lunge" -> List.of("v"); case "throw" -> List.of("v", "vy");
|
||||||
|
case "teleportto" -> List.of("location");
|
||||||
|
case "missile", "projectile", "totem" -> List.of("ontick", "onhit", "duration", "interval", "velocity", "hitradius", "verticalradius", "origin", "syo", "sfo", "tyo", "vo", "inertia", "maxrange", "stopatblock", "hitplayers", "hitnonplayers", "charges", "stopatentity");
|
||||||
|
default -> List.of();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private static void target(Screen parent, ContentDraft owner, EditorCatalog catalog) {
|
||||||
|
String current = owner.text("", "target");
|
||||||
|
var parsed = MobSyntax.call(current.isBlank() ? "self" : current);
|
||||||
|
Minecraft.getInstance().gui.setScreen(new SettingsScreen(parent, "Выбор цели", parsed, local -> {
|
||||||
|
var fields = new ArrayList<FormField>();
|
||||||
|
fields.add(DataFields.text(local, "Тип цели", "Выберите способ поиска сущностей или позиции", "self", catalog.values("targets"), "name"));
|
||||||
|
String name = local.text("self", "name");
|
||||||
|
if (List.of("pir", "playersinradius", "livinginradius", "entitiesinring", "plir", "playerlocationsinradius", "rlnte", "randomlocationsneartargets", "randomlocationsnearcaster").contains(name)) {
|
||||||
|
String key = local.get("arguments", "radius").isJsonNull() ? "r" : "radius";
|
||||||
|
fields.add(DataFields.number(local, "Радиус, блоки", "От 0 до 256 блоков", "5", false, 0, 256, "arguments", key));
|
||||||
|
}
|
||||||
|
if (name.equals("modelpart") || name.equals("modelpassengers")) fields.add(DataFields.text(local, "Кость модели", "Имя кости", "", catalog.values("bones"), "arguments", "pid"));
|
||||||
|
if (name.equals("forward") || name.equals("projectileforward")) {
|
||||||
|
fields.add(DataFields.number(local, "Дистанция вперёд", "Блоков вдоль направления", "1", false, -256, 256, "arguments", "f"));
|
||||||
|
fields.add(DataFields.bool(local, "Только горизонтальное направление", false, "arguments", "lockpitch"));
|
||||||
|
}
|
||||||
|
return fields;
|
||||||
|
}, value -> owner.string(MobSyntax.call(value), "target"), List.of(), "Неизменённые дополнительные параметры цели сохраняются."));
|
||||||
|
}
|
||||||
|
private static String parameterLabel(String key) {
|
||||||
|
return switch (key.toLowerCase(java.util.Locale.ROOT)) {
|
||||||
|
case "s", "skill" -> "Навык, анимация или звук"; case "mid", "model" -> "Модель"; case "script" -> "Сценарий JavaScript";
|
||||||
|
case "scale" -> "Масштаб"; case "ticks" -> "Время, тики"; case "duration" -> "Длительность, тики";
|
||||||
|
case "interval" -> "Интервал, тики"; case "amount", "a" -> "Количество или сила"; case "radius" -> "Радиус";
|
||||||
|
case "type" -> "Тип"; case "name" -> "Имя"; case "pbone", "part" -> "Кость модели"; case "level" -> "Уровень эффекта";
|
||||||
|
case "speed", "velocity" -> "Скорость"; case "volume" -> "Громкость"; case "pitch" -> "Высота звука";
|
||||||
|
case "onstart" -> "Навык при начале"; case "ontick" -> "Периодический навык"; case "onhit" -> "Навык при попадании";
|
||||||
|
case "onend" -> "Навык при завершении"; case "parameters" -> "Параметры JavaScript, JSON";
|
||||||
|
default -> key;
|
||||||
|
} + " [" + key + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonPrimitive;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.MobFields;
|
||||||
|
|
||||||
|
public final class MobActionsScreen extends EditorScreen {
|
||||||
|
private final Screen parent;
|
||||||
|
private final ContentDraft draft;
|
||||||
|
private final EditorCatalog catalog;
|
||||||
|
private final boolean mob;
|
||||||
|
private int selected = -1;
|
||||||
|
private String pending;
|
||||||
|
public MobActionsScreen(Screen parent, ContentDraft draft, EditorCatalog catalog, boolean mob) {
|
||||||
|
super(mob ? "События и действия моба" : "Последовательность навыка");
|
||||||
|
this.parent = parent; this.draft = draft; this.catalog = catalog; this.mob = mob;
|
||||||
|
}
|
||||||
|
private JsonArray values() { var value = draft.get("skills"); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||||
|
@Override protected void init() {
|
||||||
|
var values = values();
|
||||||
|
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 166), label -> {
|
||||||
|
selected = Integer.parseInt(label.substring(0, label.indexOf('.'))) - 1; rebuildWidgets();
|
||||||
|
}));
|
||||||
|
var labels = new java.util.ArrayList<String>();
|
||||||
|
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + (i == selected ? "▶ " : "") + MobFields.actionSummary(values.get(i).getAsString()));
|
||||||
|
list.values(labels);
|
||||||
|
int part = (width - 40) / 3;
|
||||||
|
button("+ Действие", 12, height - 118, part, () -> minecraft.gui.setScreen(new ChoiceScreen(this, "Добавить действие",
|
||||||
|
catalog.values("actions").stream().map(id -> MobFields.actionName(id) + " [" + id + "]").toList(), choice -> pending = choice)));
|
||||||
|
button("Настроить", 20 + part, height - 118, part, this::edit).active = selected >= 0;
|
||||||
|
button("Удалить", 28 + part * 2, height - 118, part, () -> { values.remove(selected); draft.set(values, "skills"); selected = -1; rebuildWidgets(); }).active = selected >= 0;
|
||||||
|
button("Выше ↑", 12, height - 91, part, () -> move(-1)).active = selected > 0;
|
||||||
|
button("Ниже ↓", 20 + part, height - 91, part, () -> move(1)).active = selected >= 0 && selected + 1 < values.size();
|
||||||
|
button("Запись…", 28 + part * 2, height - 91, part, "Расширенный режим сохраняет сложные вложенные выражения.", this::raw).active = selected >= 0;
|
||||||
|
button("Готово", 12, height - 27, 110, this::onClose);
|
||||||
|
status(values.isEmpty() ? "Действий пока нет. Добавьте первое действие из каталога сервера." : "Выберите действие. Порядок, события, цели и условия сохраняются в черновике.", false);
|
||||||
|
}
|
||||||
|
@Override public void tick() {
|
||||||
|
if (pending == null) return;
|
||||||
|
String id = pending.substring(pending.lastIndexOf('[') + 1, pending.length() - 1); pending = null;
|
||||||
|
MobActionForms.open(this, catalog, id + (mob ? " ~onSpawn" : ""), mob, value -> { var values = values(); values.add(value); draft.set(values, "skills"); });
|
||||||
|
}
|
||||||
|
private void edit() {
|
||||||
|
try { MobActionForms.open(this, catalog, values().get(selected).getAsString(), mob, value -> replace(value)); }
|
||||||
|
catch (RuntimeException error) { status("Откройте «Запись…» для этой сложной последовательности: " + error.getMessage(), true); }
|
||||||
|
}
|
||||||
|
private void replace(String value) { var values = values(); values.set(selected, new JsonPrimitive(value)); draft.set(values, "skills"); }
|
||||||
|
private void move(int delta) {
|
||||||
|
var values = values(); var value = values.get(selected); values.set(selected, values.get(selected + delta)); selected += delta;
|
||||||
|
values.set(selected, value); draft.set(values, "skills"); rebuildWidgets();
|
||||||
|
}
|
||||||
|
private void raw() {
|
||||||
|
var initial = new JsonObject(); initial.addProperty("action", values().get(selected).getAsString());
|
||||||
|
minecraft.gui.setScreen(new JsonObjectScreen(this, "Действие: расширенная запись", initial, accepted -> {
|
||||||
|
if (!accepted.has("action") || !accepted.get("action").isJsonPrimitive()) throw new IllegalArgumentException("Нужна строка action.");
|
||||||
|
replace(accepted.get("action").getAsString());
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.gui.components.EditBox;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
|
||||||
|
/** A server-backed catalog; opening an entry never spawns a mob or modifies its file. */
|
||||||
|
public final class MobBrowserScreen extends EditorScreen {
|
||||||
|
private final EditorConnection connection;
|
||||||
|
private final EditorCatalog catalog = new EditorCatalog();
|
||||||
|
private final boolean skill;
|
||||||
|
private final Map<String, String> rows = new LinkedHashMap<>();
|
||||||
|
private ChoiceList list;
|
||||||
|
private net.minecraft.client.gui.components.Button previous, next;
|
||||||
|
private String query = "";
|
||||||
|
private int page, pages = 1, delay, generation;
|
||||||
|
public MobBrowserScreen(EditorConnection connection, boolean skill) {
|
||||||
|
super(skill ? "AstraPlus: навыки" : "AstraPlus: мобы"); this.connection = connection; this.skill = skill;
|
||||||
|
}
|
||||||
|
@Override protected void init() {
|
||||||
|
int part = (width - 40) / 3;
|
||||||
|
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;
|
||||||
|
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), row -> load(rows.get(row))));
|
||||||
|
list.values(rows.keySet().stream().toList());
|
||||||
|
button(skill ? "+ Навык" : "+ Моб", 12, height - 94, 130, this::create);
|
||||||
|
button("Обновить", width - 142, height - 94, 130, this::refresh);
|
||||||
|
previous = button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } }); previous.active = page > 0;
|
||||||
|
next = button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } }); next.active = page + 1 < pages;
|
||||||
|
button("Закрыть", width - 112, height - 27, 100, this::onClose);
|
||||||
|
connection.request("mob_catalog", new JsonObject(), response -> {
|
||||||
|
if (EditorConnection.success(response)) catalog.update(response); else reply(response);
|
||||||
|
});
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
@Override public void tick() { if (delay > 0 && --delay == 0) refresh(); }
|
||||||
|
private void refresh() {
|
||||||
|
int current = ++generation;
|
||||||
|
var request = new JsonObject(); request.addProperty("page", page); request.addProperty("query", query);
|
||||||
|
status("Загружается каталог…", false);
|
||||||
|
connection.request(skill ? "skill_list" : "mob_list", request, response -> {
|
||||||
|
if (current != generation) return;
|
||||||
|
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||||
|
rows.clear();
|
||||||
|
if (response.has("entries")) for (var element : response.getAsJsonArray("entries")) {
|
||||||
|
var entry = element.getAsJsonObject(); String id = entry.get("id").getAsString();
|
||||||
|
String label = entry.has("name") ? entry.get("name").getAsString() : id;
|
||||||
|
rows.put(label + " [" + id + "]" + (!skill && entry.has("entity") ? " " + entry.get("entity").getAsString() : ""), id);
|
||||||
|
}
|
||||||
|
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());
|
||||||
|
previous.active = page > 0; next.active = page + 1 < pages;
|
||||||
|
status("Страница " + (page + 1) + " / " + pages + ". " + (skill ? "Откройте навык, чтобы изучить действия и условия." : "Откройте моба, чтобы изучить модель, поведение и получить яйцо."), false);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private void load(String id) {
|
||||||
|
if (id == null) return;
|
||||||
|
var request = new JsonObject(); request.addProperty("id", id);
|
||||||
|
connection.request(skill ? "skill_get" : "mob_get", request, response -> {
|
||||||
|
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||||
|
if (minecraft.gui.screen() != this) return;
|
||||||
|
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog,
|
||||||
|
online.astradev.plus.editor.form.MobDocuments.draft(response), skill,
|
||||||
|
response.has("details") ? response.getAsJsonObject("details") : new JsonObject()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private void create() {
|
||||||
|
var initial = new JsonObject(); initial.addProperty("id", skill ? "astraplus:new_skill" : "astraplus:new_mob");
|
||||||
|
initial.addProperty("name", skill ? "Новый навык" : "Новый моб");
|
||||||
|
if (!skill) { initial.addProperty("entity", "minecraft:pig"); initial.addProperty("health", 20); }
|
||||||
|
initial.add("skills", new com.google.gson.JsonArray());
|
||||||
|
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog, new ContentDraft(initial, "new"), skill, new JsonObject()));
|
||||||
|
}
|
||||||
|
private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.MobFields;
|
||||||
|
import online.astradev.plus.editor.form.MobSyntax;
|
||||||
|
|
||||||
|
public final class MobConditionsScreen extends EditorScreen {
|
||||||
|
private final Screen parent;
|
||||||
|
private final EditorCatalog catalog;
|
||||||
|
private final JsonArray values;
|
||||||
|
private final boolean inline;
|
||||||
|
private final Consumer<JsonArray> changed;
|
||||||
|
private String pending;
|
||||||
|
|
||||||
|
public MobConditionsScreen(Screen parent, EditorCatalog catalog, String title, JsonArray initial, boolean inline, Consumer<JsonArray> changed) {
|
||||||
|
super(title); this.parent = parent; this.catalog = catalog; this.values = initial.deepCopy(); this.inline = inline; this.changed = changed;
|
||||||
|
}
|
||||||
|
@Override protected void init() {
|
||||||
|
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 137), row -> edit(Integer.parseInt(row.substring(0, row.indexOf('.'))) - 1)));
|
||||||
|
var labels = new java.util.ArrayList<String>();
|
||||||
|
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + MobSyntax.conditionSummary(values.get(i).getAsString()));
|
||||||
|
list.values(labels);
|
||||||
|
button("+ Условие", 12, height - 88, 130, () -> minecraft.gui.setScreen(new ChoiceScreen(this, "Добавить условие",
|
||||||
|
catalog.values("conditions").stream().map(id -> MobSyntax.conditionName(id) + " [" + id + "]").toList(), selected -> pending = selected)));
|
||||||
|
button("Готово", 12, height - 27, 110, this::onClose);
|
||||||
|
status(values.isEmpty() ? "Ограничений нет. Добавьте проверки, которые должны пройти перед действием."
|
||||||
|
: "Все проверки выполняются перед применением навыка. Нажмите строку для настройки.", false);
|
||||||
|
}
|
||||||
|
@Override public void tick() {
|
||||||
|
if (pending == null) return;
|
||||||
|
String id = pending.substring(pending.lastIndexOf('[') + 1, pending.length() - 1); pending = null;
|
||||||
|
open(-1, id + " true");
|
||||||
|
}
|
||||||
|
private void edit(int index) { open(index, values.get(index).getAsString()); }
|
||||||
|
private void open(int index, String source) {
|
||||||
|
try {
|
||||||
|
var value = MobSyntax.condition(source);
|
||||||
|
String title = MobSyntax.conditionName(value.getAsJsonObject("call").get("name").getAsString());
|
||||||
|
var actions = new java.util.ArrayList<SettingsScreen.Action>();
|
||||||
|
if (index >= 0) actions.add(new SettingsScreen.Action("Удалить условие", (screen, local) -> {
|
||||||
|
values.remove(index); changed.accept(values.deepCopy()); minecraft.gui.setScreen(this);
|
||||||
|
}));
|
||||||
|
minecraft.gui.setScreen(new SettingsScreen(this, title, value, local -> MobFields.condition(local, catalog, inline), accepted -> {
|
||||||
|
String encoded = MobSyntax.condition(accepted);
|
||||||
|
if (index < 0) values.add(encoded); else values.set(index, new com.google.gson.JsonPrimitive(encoded));
|
||||||
|
changed.accept(values.deepCopy());
|
||||||
|
}, List.copyOf(actions), "Проверка поведения. Эти условия не создают правила природного спавна."));
|
||||||
|
} catch (RuntimeException error) { status(error.getMessage() + " Исходную запись можно изменить в расширенном JSON определения.", true); }
|
||||||
|
}
|
||||||
|
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonPrimitive;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.DataFields;
|
||||||
|
|
||||||
|
public final class MobDropsScreen extends EditorScreen {
|
||||||
|
private final Screen parent;
|
||||||
|
private final ContentDraft draft;
|
||||||
|
private final EditorCatalog catalog;
|
||||||
|
public MobDropsScreen(Screen parent, ContentDraft draft, EditorCatalog catalog) {
|
||||||
|
super("Лут моба"); this.parent = parent; this.draft = draft; this.catalog = catalog;
|
||||||
|
}
|
||||||
|
private JsonArray values() { var value = draft.get("drops"); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||||
|
@Override protected void init() {
|
||||||
|
var values = values();
|
||||||
|
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 40, width - 24, Math.max(26, height - 139), row -> edit(Integer.parseInt(row.substring(0, row.indexOf('.'))) - 1)));
|
||||||
|
var labels = new java.util.ArrayList<String>();
|
||||||
|
for (int i = 0; i < values.size(); i++) labels.add((i + 1) + ". " + values.get(i).getAsString());
|
||||||
|
list.values(labels);
|
||||||
|
button("+ Предмет лута", 12, height - 90, 145, () -> edit(-1));
|
||||||
|
button("Готово", 12, height - 27, 110, this::onClose);
|
||||||
|
status("Лут поддерживает ванильные предметы, диапазон количества и вероятность. Замена обычного лута задаётся в свойствах моба.", false);
|
||||||
|
}
|
||||||
|
private void edit(int index) {
|
||||||
|
var initial = new JsonObject(); initial.addProperty("item", "minecraft:diamond"); initial.addProperty("minimum", 1); initial.addProperty("maximum", 1); initial.addProperty("chance", 1);
|
||||||
|
if (index >= 0) {
|
||||||
|
String[] parts = values().get(index).getAsString().trim().split("\\s+");
|
||||||
|
if (parts.length != 3) { status("Эта запись доступна через расширенный JSON определения.", true); return; }
|
||||||
|
String[] range = parts[1].split("-");
|
||||||
|
initial.addProperty("item", parts[0]); initial.addProperty("minimum", Integer.parseInt(range[0]));
|
||||||
|
initial.addProperty("maximum", Integer.parseInt(range.length > 1 ? range[1] : range[0])); initial.addProperty("chance", Double.parseDouble(parts[2]));
|
||||||
|
}
|
||||||
|
var actions = index < 0 ? List.<SettingsScreen.Action>of() : List.of(new SettingsScreen.Action("Удалить запись лута", (screen, local) -> {
|
||||||
|
var values = values(); values.remove(index); draft.set(values, "drops"); minecraft.gui.setScreen(this);
|
||||||
|
}));
|
||||||
|
minecraft.gui.setScreen(new SettingsScreen(this, "Предмет лута", initial, local -> List.of(
|
||||||
|
DataFields.text(local, "Предмет", "Ванильный идентификатор предмета", "minecraft:diamond", catalog.values("items"), "item"),
|
||||||
|
DataFields.number(local, "Минимум", "Количество при успешном выпадении", "1", true, 0, 2304, "minimum"),
|
||||||
|
DataFields.number(local, "Максимум", "Случайное количество между минимумом и максимумом", "1", true, 0, 2304, "maximum"),
|
||||||
|
DataFields.number(local, "Вероятность", "От 0 до 1, где 1 = 100%", "1", false, 0, 1, "chance")), accepted -> {
|
||||||
|
int minimum = accepted.get("minimum").getAsInt(), maximum = accepted.get("maximum").getAsInt();
|
||||||
|
if (maximum < minimum) throw new IllegalArgumentException("Максимум должен быть не меньше минимума.");
|
||||||
|
String value = accepted.get("item").getAsString() + " " + minimum + (minimum == maximum ? "" : "-" + maximum) + " " + accepted.get("chance").getAsString();
|
||||||
|
var values = values(); if (index < 0) values.add(value); else values.set(index, new JsonPrimitive(value)); draft.set(values, "drops");
|
||||||
|
}, actions, "Ни один предмет не выдаётся до сохранения определения и смерти моба."));
|
||||||
|
}
|
||||||
|
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.gui.components.AbstractWidget;
|
||||||
|
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.DataFields;
|
||||||
|
import online.astradev.plus.editor.form.MobFields;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
|
||||||
|
/** Mob and skill detail cards share optimistic revisions and explicit saves. */
|
||||||
|
public final class MobEditorScreen extends EditorScreen {
|
||||||
|
private final Screen parent;
|
||||||
|
private final EditorConnection connection;
|
||||||
|
private final EditorCatalog catalog;
|
||||||
|
private final ContentDraft draft;
|
||||||
|
private final boolean skill;
|
||||||
|
private JsonObject details;
|
||||||
|
private boolean saving;
|
||||||
|
private int sectionPage;
|
||||||
|
private String pendingSkill, pendingModel;
|
||||||
|
|
||||||
|
public MobEditorScreen(Screen parent, EditorConnection connection, EditorCatalog catalog, ContentDraft draft, boolean skill, JsonObject details) {
|
||||||
|
super(skill ? "AstraPlus: навык" : "AstraPlus: моб"); this.parent = parent; this.connection = connection; this.catalog = catalog;
|
||||||
|
this.draft = draft; this.skill = skill; this.details = details.deepCopy();
|
||||||
|
}
|
||||||
|
@Override protected void init() {
|
||||||
|
int columns = 2, part = (width - 36) / columns;
|
||||||
|
var sections = new ArrayList<Section>();
|
||||||
|
sections.add(new Section("Основное", this::basic));
|
||||||
|
if (!skill) sections.add(new Section("Свойства и защита", this::options));
|
||||||
|
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))));
|
||||||
|
sections.add(new Section("Связанные навыки", this::skills));
|
||||||
|
sections.add(new Section("Расширенный JSON", () -> minecraft.gui.setScreen(new JsonObjectScreen(this, "Определение: расширенный режим", draft.document(), draft::replace))));
|
||||||
|
if (!skill) sections.add(new Section("Модели и анимации", this::models));
|
||||||
|
if (!draft.fresh()) sections.add(new Section("Источник и сведения", this::information));
|
||||||
|
if (!skill && !draft.fresh() && height < 330) sections.add(new Section("Призвать рядом", () -> action("mob_spawn")));
|
||||||
|
int perPage = Math.max(1, (height - 200) / 28) * columns;
|
||||||
|
int pages = Math.max(1, (sections.size() + perPage - 1) / perPage);
|
||||||
|
sectionPage = Math.min(sectionPage, pages - 1);
|
||||||
|
for (int index = sectionPage * perPage; index < Math.min(sections.size(), (sectionPage + 1) * perPage); index++) {
|
||||||
|
int relative = index - sectionPage * perPage;
|
||||||
|
var section = sections.get(index);
|
||||||
|
button(section.name, 12 + relative % columns * (part + 12), 102 + relative / columns * 28, part, section.action);
|
||||||
|
}
|
||||||
|
if (pages > 1) {
|
||||||
|
button("←", 12, height - 91, 30, () -> { sectionPage--; rebuildWidgets(); }).active = sectionPage > 0;
|
||||||
|
button("→", 48, height - 91, 30, () -> { sectionPage++; rebuildWidgets(); }).active = sectionPage + 1 < pages;
|
||||||
|
}
|
||||||
|
int size = (width - 40) / 3;
|
||||||
|
button("Назад", 12, height - 27, size, this::onClose);
|
||||||
|
button("Сохранить", 20 + size, height - 27, size, this::save);
|
||||||
|
if (!skill) button("Яйцо призыва", 28 + size * 2, height - 27, size, "Выдаётся яйцо сохранённой серверной версии моба.", () -> action("mob_egg")).active = !draft.fresh();
|
||||||
|
if (!skill && height >= 330) button("Призвать рядом", width - 156, height - 91, 144,
|
||||||
|
"Создаёт настоящего моба рядом с вами. Для изучения модели используйте предпросмотр.", () -> action("mob_spawn")).active = !draft.fresh();
|
||||||
|
if (saving) for (var child : children()) if (child instanceof AbstractWidget widget) widget.active = false;
|
||||||
|
if (status.isBlank()) status(draft.fresh() ? "Новое определение. Настройте его и сохраните на сервере."
|
||||||
|
: "Редактируется локальный черновик. Сервер изменится после «Сохранить».", false);
|
||||||
|
}
|
||||||
|
private void basic() {
|
||||||
|
minecraft.gui.setScreen(new SettingsScreen(this, "Основные настройки", draft.document(), local -> {
|
||||||
|
var fields = new ArrayList<>(MobFields.basic(local, catalog, skill));
|
||||||
|
if (draft.fresh()) fields.addFirst(DataFields.text(local, "Идентификатор", "namespace:путь, без пробелов", draft.id(), List.of(), "id"));
|
||||||
|
return fields;
|
||||||
|
}, draft::replace, List.of(), "Основа задаёт ванильный тип сущности. Пользовательская модель подключается действием model."));
|
||||||
|
}
|
||||||
|
private void options() { minecraft.gui.setScreen(new SettingsScreen(this, "Свойства моба", draft.document(), MobFields::options, draft::replace,
|
||||||
|
List.of(), "Пустые числовые поля наследуются от основы или значения сервера, указанного в подсказке.")); }
|
||||||
|
private void ai() {
|
||||||
|
minecraft.gui.setScreen(new SettingsScreen(this, "Поведение и выбор цели", draft.document(), local -> List.of(
|
||||||
|
DataFields.bool(local, "Учитывать накопленную угрозу", false, "modules", "ThreatTable")), draft::replace, List.of(
|
||||||
|
new SettingsScreen.Action("Действия ИИ", (screen, local) -> minecraft.gui.setScreen(new IdentifierListScreen(screen, "Действия ИИ",
|
||||||
|
array(local, "goals"), List.of("clear", "meleeattack", "gotoplayer", "movetowardstarget", "randomstroll"), 16, false, values -> local.set(values, "goals")))),
|
||||||
|
new SettingsScreen.Action("Выбор цели", (screen, local) -> minecraft.gui.setScreen(new IdentifierListScreen(screen, "Цели моба",
|
||||||
|
array(local, "targets"), List.of("clear", "players", "attacker", "otherfaction", "otherfactionmonsters"), 16, false, values -> local.set(values, "targets"))))),
|
||||||
|
"Пустые списки сохраняют ванильный ИИ. clear удаляет ванильные задачи или цели перед добавлением ваших."));
|
||||||
|
}
|
||||||
|
private void information() {
|
||||||
|
var text = new StringBuilder("Определение: ").append(draft.id()).append("\nФайл сервера: ")
|
||||||
|
.append(details.has("file") ? details.get("file").getAsString() : "Не передан сервером");
|
||||||
|
if (details.has("models")) for (var element : details.getAsJsonArray("models")) {
|
||||||
|
var model = element.getAsJsonObject(); text.append("\n\nМодель: ").append(model.get("id").getAsString());
|
||||||
|
text.append("\nКостей: ").append(model.get("bones").getAsInt());
|
||||||
|
if (model.has("width") && model.has("height")) text.append("\nГабариты: ").append(model.get("width").getAsString())
|
||||||
|
.append(" × ").append(model.get("height").getAsString()).append(" блока");
|
||||||
|
if (model.has("animations")) {
|
||||||
|
var names = new ArrayList<String>(); model.getAsJsonArray("animations").forEach(value -> names.add(value.getAsString()));
|
||||||
|
text.append("\nАнимации: ").append(names.isEmpty() ? "Нет" : String.join(", ", names));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text.append("\n\nУсловия навыков управляют действиями. Природный спавн отдельно не настроен этим экраном.");
|
||||||
|
minecraft.gui.setScreen(new MessageScreen(this, "AstraPlus: сведения об определении", text.toString()));
|
||||||
|
}
|
||||||
|
private void conditions(String key, String title) { minecraft.gui.setScreen(new MobConditionsScreen(this, catalog, title, array(draft, key), false, values -> draft.set(values, key))); }
|
||||||
|
private static JsonArray array(ContentDraft draft, String key) { var value = draft.get(key); return value.isJsonArray() ? value.getAsJsonArray() : new JsonArray(); }
|
||||||
|
private void skills() {
|
||||||
|
var ids = new ArrayList<String>();
|
||||||
|
if (details.has("referencedSkills")) details.getAsJsonArray("referencedSkills").forEach(value -> ids.add(value.getAsString()));
|
||||||
|
if (ids.isEmpty()) ids.addAll(catalog.values("skills"));
|
||||||
|
minecraft.gui.setScreen(new ChoiceScreen(this, "Открыть связанный навык", ids, id -> pendingSkill = id));
|
||||||
|
}
|
||||||
|
private void models() {
|
||||||
|
var ids = new ArrayList<String>();
|
||||||
|
if (details.has("models")) details.getAsJsonArray("models").forEach(value -> ids.add(value.getAsJsonObject().get("id").getAsString()));
|
||||||
|
if (ids.isEmpty()) ids.addAll(catalog.values("models"));
|
||||||
|
minecraft.gui.setScreen(new ChoiceScreen(this, "Модели: предпросмотр и анимации", ids, id -> pendingModel = id));
|
||||||
|
}
|
||||||
|
@Override public void tick() {
|
||||||
|
if (pendingSkill != null) {
|
||||||
|
String id = pendingSkill; pendingSkill = null;
|
||||||
|
var request = new JsonObject(); request.addProperty("id", id);
|
||||||
|
connection.request("skill_get", request, response -> {
|
||||||
|
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||||
|
if (minecraft.gui.screen() != this) return;
|
||||||
|
minecraft.gui.setScreen(new MobEditorScreen(this, connection, catalog, online.astradev.plus.editor.form.MobDocuments.draft(response),
|
||||||
|
true, response.has("details") ? response.getAsJsonObject("details") : new JsonObject()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (pendingModel != null) {
|
||||||
|
String id = pendingModel; pendingModel = null;
|
||||||
|
var request = new JsonObject(); request.addProperty("id", id);
|
||||||
|
status("Загружается модель…", false);
|
||||||
|
connection.request("model_preview", request, response -> {
|
||||||
|
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||||
|
if (minecraft.gui.screen() == this) minecraft.gui.setScreen(new MobPreviewScreen(this, draft.text(draft.id(), "name"), response));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void save() {
|
||||||
|
if (saving) return;
|
||||||
|
var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("revision", draft.revision()); request.add("document", draft.document());
|
||||||
|
saving = true; rebuildWidgets(); status("Сервер проверяет ссылки, условия и сохраняет определение…", false);
|
||||||
|
connection.request(skill ? "skill_save" : "mob_save", request, response -> {
|
||||||
|
saving = false;
|
||||||
|
if (EditorConnection.success(response)) {
|
||||||
|
draft.saved(response.has("document") ? online.astradev.plus.editor.form.MobDocuments.document(response) : request.getAsJsonObject("document"), response.get("revision").getAsString());
|
||||||
|
if (response.has("details")) details = response.getAsJsonObject("details").deepCopy();
|
||||||
|
}
|
||||||
|
reply(response); if (minecraft.gui.screen() == this) rebuildWidgets();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private void action(String action) {
|
||||||
|
var request = new JsonObject(); request.addProperty("id", draft.id()); request.addProperty("count", 1);
|
||||||
|
connection.request(action, request, this::reply);
|
||||||
|
}
|
||||||
|
private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); }
|
||||||
|
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||||
|
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||||
|
graphics.fill(12, 37, width - 12, 91, 0xFF1B3038);
|
||||||
|
graphics.text(font, font.plainSubstrByWidth(draft.text(draft.id(), "name") + (draft.dirty() ? " Черновик" : " Сохранено"), width - 42), 21, 44, 0xFFE0F4F4);
|
||||||
|
graphics.text(font, font.plainSubstrByWidth(draft.id(), width - 42), 21, 59, 0xFF88B7C4);
|
||||||
|
String summary = skill ? "Действий: " + array(draft, "skills").size() + " Перезарядка: " + draft.text("0", "cooldown") + " с"
|
||||||
|
: "Основа: " + Component.translatable("entity." + draft.text("minecraft:pig", "entity").replace(':', '.')).getString()
|
||||||
|
+ " Здоровье: " + draft.text("20", "health") + " Урон: " + draft.text("0", "damage");
|
||||||
|
graphics.text(font, font.plainSubstrByWidth(summary, width - 42), 21, 76, 0xFFB3CED4);
|
||||||
|
}
|
||||||
|
@Override public void onClose() {
|
||||||
|
if (saving) { status("Дождитесь завершения сохранения.", true); return; }
|
||||||
|
if (draft.dirty()) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||||
|
Component.literal("Закрыть без сохранения?"), Component.literal("Локальные изменения определения будут потеряны."), Component.literal("Не сохранять"), Component.literal("Продолжить")));
|
||||||
|
else minecraft.gui.setScreen(parent);
|
||||||
|
}
|
||||||
|
private record Section(String name, Runnable action) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package online.astradev.plus.editor.screen;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||||
|
import net.minecraft.client.gui.components.Button;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import net.minecraft.client.input.MouseButtonEvent;
|
||||||
|
import net.minecraft.network.chat.Component;
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewModel;
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewScene;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
|
||||||
|
/** Interactive, local-only model inspection with the same skeleton and pack as live mobs. */
|
||||||
|
public final class MobPreviewScreen extends EditorScreen {
|
||||||
|
private static final String REST_POSE = "Исходная поза";
|
||||||
|
private final Screen parent;
|
||||||
|
private PreviewScene scene;
|
||||||
|
private float yaw = 0.65F, pitch = -0.15F, zoom = 1;
|
||||||
|
private float elapsed;
|
||||||
|
private long lastFrame = System.nanoTime();
|
||||||
|
private boolean paused, dragging, loading;
|
||||||
|
private Button play;
|
||||||
|
|
||||||
|
public MobPreviewScreen(Screen parent, String name, JsonObject descriptor) {
|
||||||
|
super("Модель: " + name); this.parent = parent;
|
||||||
|
try { scene = new PreviewScene(PreviewModel.read(descriptor)); }
|
||||||
|
catch (RuntimeException error) { status("Не удалось открыть модель: " + error.getMessage(), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public String selectedAnimation() { return scene == null ? "" : scene.model().selectedAnimation(); }
|
||||||
|
public float animationTime() { return elapsed; }
|
||||||
|
public boolean isPlaying() { return scene != null && scene.model().animation() != null && !paused; }
|
||||||
|
|
||||||
|
@Override protected void init() {
|
||||||
|
button("Назад", 12, height - 27, 90, this::onClose);
|
||||||
|
int available = Math.max(180, width - 24), gap = 6;
|
||||||
|
int control = Math.max(55, (available - gap * 3) / 4);
|
||||||
|
button("Анимация…", 12, 38, control, this::chooseAnimation).active = scene != null && !scene.model().animations().isEmpty();
|
||||||
|
play = button(paused ? "Продолжить" : "Пауза", 12 + control + gap, 38, control, () -> {
|
||||||
|
paused = !paused; play.setMessage(Component.literal(paused ? "Продолжить" : "Пауза"));
|
||||||
|
});
|
||||||
|
play.active = scene != null && scene.model().animation() != null;
|
||||||
|
button("Сначала", 12 + (control + gap) * 2, 38, control, () -> elapsed = 0);
|
||||||
|
button("Сброс вида", 12 + (control + gap) * 3, 38, control, () -> { yaw = 0.65F; pitch = -0.15F; zoom = 1; });
|
||||||
|
if (scene != null) {
|
||||||
|
if (loading) status("Загрузка анимации…", false);
|
||||||
|
else if (!scene.missing().isEmpty()) status("Для просмотра загрузите актуальный ресурспак сервера. Отсутствуют модели частей: "
|
||||||
|
+ scene.missing().size() + ". Например, " + scene.missing().getFirst(), true);
|
||||||
|
else if (!scene.hasGeometry()) status("У модели нет видимых частей. Проверьте видимость и экспорт геометрии.", true);
|
||||||
|
else status("Перетаскивайте модель для вращения. Колесо мыши меняет масштаб.", false);
|
||||||
|
}
|
||||||
|
lastFrame = System.nanoTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void chooseAnimation() {
|
||||||
|
if (scene == null || loading) return;
|
||||||
|
var choices = new ArrayList<String>(); choices.add(REST_POSE);
|
||||||
|
scene.model().animations().forEach(name -> choices.add("Анимация: " + name));
|
||||||
|
minecraft.gui.setScreen(new ChoiceScreen(this, "Анимации модели", choices, selection -> {
|
||||||
|
JsonObject body = new JsonObject(); body.addProperty("id", scene.model().id());
|
||||||
|
body.addProperty("animation", selection.equals(REST_POSE) ? "" : selection.substring("Анимация: ".length()));
|
||||||
|
loading = true; status("Загрузка анимации…", false);
|
||||||
|
EditorConnection.INSTANCE.request("model_preview", body, response -> {
|
||||||
|
loading = false;
|
||||||
|
if (!EditorConnection.success(response)) { status(EditorConnection.message(response), true); return; }
|
||||||
|
try {
|
||||||
|
scene = new PreviewScene(PreviewModel.read(response)); elapsed = 0; lastFrame = System.nanoTime();
|
||||||
|
if (minecraft.gui.screen() == this) rebuildWidgets();
|
||||||
|
} catch (RuntimeException error) { status("Не удалось прочитать анимацию: " + error.getMessage(), true); }
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float partialTick) {
|
||||||
|
super.extractRenderState(graphics, mouseX, mouseY, partialTick);
|
||||||
|
int bottom = Math.max(95, height - 82);
|
||||||
|
graphics.fill(12, 65, width - 12, bottom, 0xFF0C141A);
|
||||||
|
for (int x = 28; x < width - 12; x += 24) graphics.fill(x, 65, x + 1, bottom, 0xFF17242B);
|
||||||
|
for (int y = 77; y < bottom; y += 24) graphics.fill(12, y, width - 12, y + 1, 0xFF17242B);
|
||||||
|
long now = System.nanoTime();
|
||||||
|
if (!paused && minecraft.gui.screen() == this) elapsed += Math.min(0.1F, (now - lastFrame) / 1_000_000_000F);
|
||||||
|
lastFrame = now;
|
||||||
|
if (scene == null) return;
|
||||||
|
try { scene.extract(graphics, 13, 66, width - 13, bottom - 1, elapsed, yaw, pitch, zoom); }
|
||||||
|
catch (RuntimeException error) { scene = null; status("Предпросмотр остановлен: " + error.getMessage(), true); return; }
|
||||||
|
graphics.text(font, font.plainSubstrByWidth(scene.model().id(), width - 36), 18, 71, 0xFF88B7C4);
|
||||||
|
String animation = scene.model().selectedAnimation().isEmpty()
|
||||||
|
? REST_POSE : scene.model().selectedAnimation();
|
||||||
|
String info = animation + " | " + Math.round(zoom * 100) + "%";
|
||||||
|
graphics.text(font, font.plainSubstrByWidth(info, width - 36), 18, bottom - 14, 0xFFBDD1D9);
|
||||||
|
if (!scene.missing().isEmpty()) graphics.text(font, "Требуется ресурспак", Math.max(20, (width - font.width("Требуется ресурспак")) / 2),
|
||||||
|
(65 + bottom) / 2, 0xFFFFC69A);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean inside(double x, double y) { return x >= 12 && x < width - 12 && y >= 65 && y < height - 82; }
|
||||||
|
|
||||||
|
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||||
|
if (event.button() == 0 && inside(event.x(), event.y())) { dragging = true; return true; }
|
||||||
|
return super.mouseClicked(event, doubleClick);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public boolean mouseDragged(MouseButtonEvent event, double dx, double dy) {
|
||||||
|
if (dragging && event.button() == 0) {
|
||||||
|
yaw += (float) dx * 0.012F; pitch = Math.clamp(pitch + (float) dy * 0.012F, -1.5F, 1.5F); return true;
|
||||||
|
}
|
||||||
|
return super.mouseDragged(event, dx, dy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public boolean mouseReleased(MouseButtonEvent event) {
|
||||||
|
if (dragging && event.button() == 0) { dragging = false; return true; }
|
||||||
|
return super.mouseReleased(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public boolean mouseScrolled(double x, double y, double horizontal, double vertical) {
|
||||||
|
if (inside(x, y)) { zoom = Math.clamp(zoom * (float) Math.pow(1.12, vertical), 0.2F, 5F); return true; }
|
||||||
|
return super.mouseScrolled(x, y, horizontal, vertical);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||||
|
}
|
||||||
@@ -46,8 +46,8 @@ public final class SettingsScreen extends EditorScreen {
|
|||||||
labels.clear();
|
labels.clear();
|
||||||
var fields = this.fields.apply(local);
|
var fields = this.fields.apply(local);
|
||||||
if (fields.isEmpty()) {
|
if (fields.isEmpty()) {
|
||||||
labels.add(new Label("Свойство включится после добавления в черновик.", 18, 53, width - 36));
|
labels.add(new Label("У этой формы нет отдельных полей.", 18, 53, width - 36));
|
||||||
labels.add(new Label(actions.isEmpty() ? "Дополнительных параметров у него нет." : "Состав эффектов задаётся кнопкой ниже.", 18, 73, width - 36));
|
labels.add(new Label(actions.isEmpty() ? "Примените её кнопкой «В черновик»." : "Дополнительные настройки открываются кнопкой ниже.", 18, 73, width - 36));
|
||||||
}
|
}
|
||||||
int columns = width >= 570 ? 2 : 1;
|
int columns = width >= 570 ? 2 : 1;
|
||||||
int rows = Math.max(1, (height - 140) / 48);
|
int rows = Math.max(1, (height - 140) / 48);
|
||||||
@@ -91,8 +91,8 @@ public final class SettingsScreen extends EditorScreen {
|
|||||||
button("Назад", 18, height - 27, 110, this::onClose);
|
button("Назад", 18, height - 27, 110, this::onClose);
|
||||||
button("В черновик", width - 148, height - 27, 130, () -> {
|
button("В черновик", width - 148, height - 27, 130, () -> {
|
||||||
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
|
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
|
||||||
apply.accept(local.document());
|
try { apply.accept(local.document()); minecraft.gui.setScreen(parent); }
|
||||||
minecraft.gui.setScreen(parent);
|
catch (IllegalArgumentException error) { status(error.getMessage(), true); }
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package online.astradev.plus.editor.client.preview;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class PreviewModelTest {
|
||||||
|
@Test void acceptsStaticModels() {
|
||||||
|
JsonObject value = model();
|
||||||
|
var parsed = PreviewModel.read(value);
|
||||||
|
assertEquals(1, parsed.bones().size());
|
||||||
|
assertNull(parsed.animation());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rejectsIncompleteSelectedAnimation() {
|
||||||
|
JsonObject value = model(); value.addProperty("selectedAnimation", "idle");
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> PreviewModel.read(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rejectsForwardAndCyclicParentReferences() {
|
||||||
|
JsonObject value = model(); value.getAsJsonArray("bones").get(0).getAsJsonObject().addProperty("parent", 0);
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> PreviewModel.read(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void rejectsAnimationReferencesOutsideSkeleton() {
|
||||||
|
JsonObject value = model();
|
||||||
|
value.add("animation", JsonParser.parseString("""
|
||||||
|
{"name":"idle","length":1,"loop":true,"bones":{"8":{"position":[]}}}
|
||||||
|
"""));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> PreviewModel.read(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test void preservesSplitKeyframesAndSteps() {
|
||||||
|
var zero = PreviewModel.Vector.ZERO;
|
||||||
|
var before = new PreviewModel.Vector(2, 0, 0);
|
||||||
|
var after = new PreviewModel.Vector(7, 0, 0);
|
||||||
|
var frames = List.of(new PreviewModel.Frame(0, zero, before, "step"),
|
||||||
|
new PreviewModel.Frame(1, after, zero, "linear"));
|
||||||
|
assertEquals(before, PreviewAnimation.sample(frames, 0.5F, false, zero));
|
||||||
|
assertEquals(after, PreviewAnimation.sample(frames, 1, false, zero));
|
||||||
|
assertEquals(zero, PreviewAnimation.sample(frames, 2, false, before));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonObject model() {
|
||||||
|
return JsonParser.parseString("""
|
||||||
|
{"id":"example:creature","bones":[{"name":"body","parent":-1,
|
||||||
|
"origin":[0,8,0],"rotation":[0,0,0],"itemModel":"minecraft:stone","geometryScale":1}],"animations":[]}
|
||||||
|
""").getAsJsonObject();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package online.astradev.plus.editor.form;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class MobSyntaxTest {
|
||||||
|
@Test void editingChancePreservesNestedScriptsTargetsAndInlineConditions() {
|
||||||
|
String source = "skill{s=[ - javascript{script=example:action;parameters={\"text\":\"a ; b\"}} @self - delay 5 ]} @playersinradius{r=8} ~onTimer:20 ?incombat ?!hasaura{n=busy} 0.5";
|
||||||
|
var value = MobSyntax.action(source);
|
||||||
|
value.addProperty("chance", 0.75);
|
||||||
|
var reparsed = MobSyntax.action(MobSyntax.action(value));
|
||||||
|
assertEquals(value, reparsed);
|
||||||
|
assertTrue(reparsed.getAsJsonObject("action").getAsJsonObject("arguments").get("s").getAsString().contains("a ; b"));
|
||||||
|
assertEquals(2, reparsed.getAsJsonArray("conditions").size());
|
||||||
|
}
|
||||||
|
@Test void supportsEveryConditionAndFallbackWithoutDiscardingArguments() {
|
||||||
|
for (String condition : List.of("incombat true", "targetwithin{d=8;custom=retained} false", "playerwithin{distance=12} true",
|
||||||
|
"hasaura{name=wet} false", "hasmodel true", "isblocking true", "modelhaspassenger{part=seat} orElseCast example:fallback")) {
|
||||||
|
assertEquals(MobSyntax.condition(condition), MobSyntax.condition(MobSyntax.condition(MobSyntax.condition(condition))));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Test void rejectsBrokenBracketsAndUnsupportedInlineFallback() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> MobSyntax.action("skill{s=[ - delay 1}"));
|
||||||
|
var action = MobSyntax.action("damage @target ~onAttack");
|
||||||
|
action.getAsJsonArray("conditions").add("incombat orElseCast example:fallback");
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> MobSyntax.action(action));
|
||||||
|
}
|
||||||
|
@Test void localFormReplacementPreservesUnsavedStateAndUnknownDefinitionFields() {
|
||||||
|
var draft = new ContentDraft(JsonParser.parseString("{\"id\":\"example:mob\",\"health\":20,\"extension\":{\"unknown\":true}}").getAsJsonObject(), "revision");
|
||||||
|
var document = draft.document(); document.addProperty("health", 40); draft.replace(document);
|
||||||
|
assertTrue(draft.dirty()); assertTrue(draft.get("extension", "unknown").getAsBoolean()); assertEquals("revision", draft.revision());
|
||||||
|
}
|
||||||
|
@Test void restoresPathIdentityWhenServerDocumentOmitsId() {
|
||||||
|
var response = JsonParser.parseString("{\"id\":\"example:creature\",\"revision\":\"stored\",\"document\":{\"name\":\"Creature\"}}").getAsJsonObject();
|
||||||
|
var draft = MobDocuments.draft(response);
|
||||||
|
assertEquals("example:creature", draft.id()); assertFalse(draft.dirty());
|
||||||
|
assertFalse(response.getAsJsonObject("document").has("id"));
|
||||||
|
}
|
||||||
|
@Test void acceptsStructuredJavascriptParametersFromAdvancedForm() {
|
||||||
|
var call = JsonParser.parseString("{\"name\":\"javascript\",\"arguments\":{\"script\":\"example:test\",\"parameters\":{\"power\":6}}}").getAsJsonObject();
|
||||||
|
assertEquals("javascript{script=example:test;parameters={\"power\":6}}", MobSyntax.call(call));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package online.astradev.plus.editor.network;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class RequestChunksTest {
|
||||||
|
@Test void carriesLargeUnicodeDocumentInBoundedPacketsWithOneRequestId() {
|
||||||
|
String original = "{\"text\":\"" + "Модель 🌊".repeat(8000) + "\"}";
|
||||||
|
var packets = RequestChunks.encode(original, 51);
|
||||||
|
var encoded = new StringBuilder();
|
||||||
|
for (int index = 0; index < packets.size(); index++) {
|
||||||
|
assertTrue(packets.get(index).length() < 8192);
|
||||||
|
var chunk = JsonParser.parseString(packets.get(index)).getAsJsonObject();
|
||||||
|
assertEquals(51, chunk.get("requestId").getAsInt()); assertEquals(index, chunk.get("index").getAsInt());
|
||||||
|
assertEquals(packets.size(), chunk.get("total").getAsInt()); encoded.append(chunk.get("data").getAsString());
|
||||||
|
}
|
||||||
|
assertEquals(original, new String(Base64.getDecoder().decode(encoded.toString()), StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
@Test void preservesSmallRequestsAndRejectsOversizedDocuments() {
|
||||||
|
assertEquals(java.util.List.of("{}"), RequestChunks.encode("{}", 1));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> RequestChunks.encode("Я".repeat(600000), 2));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package online.astradev.plus.editor.network;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Base64;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class ResponseChunksTest {
|
||||||
|
@Test void assemblesLargeUnicodeResponseWithoutLosingRevision() {
|
||||||
|
var expected = new JsonObject(); expected.addProperty("requestId", 17); expected.addProperty("ok", true);
|
||||||
|
expected.addProperty("revision", "saved"); expected.addProperty("text", "モデル 🐟".repeat(40000));
|
||||||
|
String encoded = Base64.getEncoder().encodeToString(expected.toString().getBytes(StandardCharsets.UTF_8));
|
||||||
|
int total = (encoded.length() + 179999) / 180000;
|
||||||
|
var assembly = new ResponseChunks(17); JsonObject result = null;
|
||||||
|
for (int index = 0; index < total; index++) {
|
||||||
|
result = assembly.accept(chunk(index, total, encoded.substring(index * 180000, Math.min(encoded.length(), (index + 1) * 180000))));
|
||||||
|
if (index + 1 < total) assertNull(result);
|
||||||
|
}
|
||||||
|
assertEquals(expected, result);
|
||||||
|
}
|
||||||
|
@Test void rejectsOrderTotalIdentityAndNestedChunks() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ResponseChunks(17).accept(chunk(1, 2, "e30=")));
|
||||||
|
var assembly = new ResponseChunks(17); assertNull(assembly.accept(chunk(0, 2, "eyJy")));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> assembly.accept(chunk(1, 3, "e30=")));
|
||||||
|
String nested = Base64.getEncoder().encodeToString("{\"requestId\":17,\"action\":\"response_chunk\"}".getBytes(StandardCharsets.UTF_8));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ResponseChunks(17).accept(chunk(0, 1, nested)));
|
||||||
|
var wrong = chunk(0, 1, "e30="); wrong.addProperty("requestId", 18);
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ResponseChunks(17).accept(wrong));
|
||||||
|
}
|
||||||
|
@Test void rejectsOversizedPartsAndInvalidUtf8() {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ResponseChunks(17).accept(chunk(0, 1, "a".repeat(180001))));
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new ResponseChunks(17).accept(chunk(0, 1, Base64.getEncoder().encodeToString(new byte[]{(byte) 0xFF}))));
|
||||||
|
}
|
||||||
|
private JsonObject chunk(int index, int total, String data) {
|
||||||
|
var result = new JsonObject(); result.addProperty("requestId", 17); result.addProperty("index", index);
|
||||||
|
result.addProperty("total", total); result.addProperty("data", data); return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
-3
@@ -39,6 +39,8 @@ public final class EditorVerification {
|
|||||||
private ContentBrowserScreen browser;
|
private ContentBrowserScreen browser;
|
||||||
private ContentDraft draft;
|
private ContentDraft draft;
|
||||||
private EditorCatalog catalog;
|
private EditorCatalog catalog;
|
||||||
|
private ContentDraft mobDraft;
|
||||||
|
private online.astradev.plus.editor.screen.MobEditorScreen mobEditor;
|
||||||
private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null;
|
private final NetworkVerification network = Boolean.getBoolean("astrapluseditor.networkVerification") ? new NetworkVerification() : null;
|
||||||
|
|
||||||
public EditorVerification() {
|
public EditorVerification() {
|
||||||
@@ -83,6 +85,19 @@ public final class EditorVerification {
|
|||||||
draft.removeComponent("minecraft:repair_cost", true);
|
draft.removeComponent("minecraft:repair_cost", true);
|
||||||
item = new ContentEditorScreen(browser, connection, catalog, draft);
|
item = new ContentEditorScreen(browser, connection, catalog, draft);
|
||||||
block = new ContentEditorScreen(browser, connection, catalog, ContentDraft.create(true));
|
block = new ContentEditorScreen(browser, connection, catalog, ContentDraft.create(true));
|
||||||
|
var mobCatalog = new EditorCatalog();
|
||||||
|
mobCatalog.update(JsonParser.parseString("""
|
||||||
|
{"catalogs":{"mobEntities":["minecraft:zombie","minecraft:pig"],"models":["example:creature"],
|
||||||
|
"skills":["example:attack","example:fallback"],"conditions":["incombat","targetwithin","playerwithin","hasaura","hasmodel","isblocking","modelhaspassenger"],
|
||||||
|
"actions":["skill","damage","model","state","javascript"],"targets":["self","target","playersinradius"],"bones":["body","seat"]}}
|
||||||
|
""").getAsJsonObject());
|
||||||
|
mobDraft = new ContentDraft(JsonParser.parseString("""
|
||||||
|
{"id":"example:guardian","name":"Хранитель руин","entity":"minecraft:zombie","health":120,"damage":6,
|
||||||
|
"skills":["skill{s=example:attack} @target ~onAttack ?incombat ?!hasaura{n=stunned}","model{mid=example:creature} @self ~onSpawn"],
|
||||||
|
"options":{"MovementSpeed":0.2,"PreventOtherDrops":true},"drops":["minecraft:emerald 1-3 0.5"]}
|
||||||
|
""").getAsJsonObject(), "revision");
|
||||||
|
mobEditor = new online.astradev.plus.editor.screen.MobEditorScreen(browser, connection, mobCatalog, mobDraft, false, new com.google.gson.JsonObject());
|
||||||
|
mobVerificationCatalog = mobCatalog;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
switch (++tick) {
|
switch (++tick) {
|
||||||
@@ -130,9 +145,30 @@ public final class EditorVerification {
|
|||||||
case 305 -> show(new ScriptBindingsScreen(item, draft, catalog, () -> {}));
|
case 305 -> show(new ScriptBindingsScreen(item, draft, catalog, () -> {}));
|
||||||
case 325 -> { click("+ Добавить"); }
|
case 325 -> { click("+ Добавить"); }
|
||||||
case 345 -> capture("13-script-binding-small.png");
|
case 345 -> capture("13-script-binding-small.png");
|
||||||
case 350 -> {
|
case 350 -> { minecraft.options.guiScale().set(2); minecraft.resizeGui(); show(mobEditor); }
|
||||||
if (screenshots < 13) throw new IllegalStateException("Only " + screenshots + " screenshots completed.");
|
case 370 -> capture("16-mob-overview.png");
|
||||||
Files.writeString(minecraft.gameDirectory.toPath().resolve("verification-result.txt"), "PASS: 13 actual GUI screenshots; property inheritance, typed forms, effects, behaviors, conditions, scripts; widget bounds; optional connection.");
|
case 375 -> show(new online.astradev.plus.editor.screen.MobActionsScreen(mobEditor, mobDraft, mobVerificationCatalog, true));
|
||||||
|
case 395 -> capture("17-mob-actions.png");
|
||||||
|
case 400 -> show(new online.astradev.plus.editor.screen.MobConditionsScreen(mobEditor, mobVerificationCatalog, "Условия навыка",
|
||||||
|
JsonParser.parseString("[\"incombat true\",\"targetwithin{d=8} true\",\"hasaura{n=stunned} false\",\"modelhaspassenger{p=seat} orElseCast example:fallback\"]").getAsJsonArray(), false, ignored -> {}));
|
||||||
|
case 420 -> capture("18-mob-conditions.png");
|
||||||
|
case 425 -> show(new online.astradev.plus.editor.screen.SettingsScreen(mobEditor, "На модели есть пассажир",
|
||||||
|
online.astradev.plus.editor.form.MobSyntax.condition("modelhaspassenger{p=seat} orElseCast example:fallback"),
|
||||||
|
local -> online.astradev.plus.editor.form.MobFields.condition(local, mobVerificationCatalog, false), ignored -> {}, java.util.List.of(), "Если проверка не пройдёт, будет вызван резервный навык."));
|
||||||
|
case 445 -> capture("19-mob-condition-form.png");
|
||||||
|
case 450 -> { minecraft.options.guiScale().set(3); minecraft.resizeGui(); show(mobEditor); }
|
||||||
|
case 470 -> capture("20-mob-overview-small.png");
|
||||||
|
case 475 -> {
|
||||||
|
minecraft.options.guiScale().set(2); minecraft.resizeGui();
|
||||||
|
show(new online.astradev.plus.editor.screen.MobPreviewScreen(mobEditor, "Учебная модель", JsonParser.parseString("""
|
||||||
|
{"id":"example:creature","bones":[{"name":"body","parent":-1,"origin":[0,8,0],"rotation":[0,0,0],
|
||||||
|
"itemModel":"minecraft:stone","geometryScale":1}],"animations":[]}
|
||||||
|
""").getAsJsonObject()));
|
||||||
|
}
|
||||||
|
case 500 -> capture("21-native-model-preview.png");
|
||||||
|
case 505 -> {
|
||||||
|
if (screenshots < 19) throw new IllegalStateException("Only " + screenshots + " screenshots completed.");
|
||||||
|
Files.writeString(minecraft.gameDirectory.toPath().resolve("verification-result.txt"), "PASS: 19 actual GUI screenshots; items/blocks; mob overview and small layout; action sequence; condition controls; preview unavailable without world; widget bounds.");
|
||||||
minecraft.stop();
|
minecraft.stop();
|
||||||
}
|
}
|
||||||
default -> {}
|
default -> {}
|
||||||
@@ -144,6 +180,7 @@ public final class EditorVerification {
|
|||||||
throw new IllegalStateException("Editor verification failed", failure);
|
throw new IllegalStateException("Editor verification failed", failure);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private EditorCatalog mobVerificationCatalog;
|
||||||
|
|
||||||
private void show(Screen screen) { Minecraft.getInstance().gui.setScreen(screen); }
|
private void show(Screen screen) { Minecraft.getInstance().gui.setScreen(screen); }
|
||||||
|
|
||||||
|
|||||||
+144
@@ -0,0 +1,144 @@
|
|||||||
|
package online.astradev.plus.editor.verification;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.client.Screenshot;
|
||||||
|
import net.minecraft.core.component.DataComponents;
|
||||||
|
import net.minecraft.world.item.component.CustomData;
|
||||||
|
import online.astradev.plus.editor.client.EditorCatalog;
|
||||||
|
import online.astradev.plus.editor.form.ContentDraft;
|
||||||
|
import online.astradev.plus.editor.form.MobDocuments;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
import online.astradev.plus.editor.screen.MobBrowserScreen;
|
||||||
|
import online.astradev.plus.editor.screen.MobEditorScreen;
|
||||||
|
|
||||||
|
/** Generic fixture names keep real pack imports outside the deliverable project. */
|
||||||
|
final class MobNetworkVerification {
|
||||||
|
private final EditorConnection connection;
|
||||||
|
private final Runnable complete;
|
||||||
|
private final Consumer<String> failure;
|
||||||
|
private final String id = "verification:mob_" + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
private final EditorCatalog catalog = new EditorCatalog();
|
||||||
|
private int stage, tick, next;
|
||||||
|
private boolean waiting;
|
||||||
|
private String revision, skillRevision;
|
||||||
|
private JsonObject mob, skill;
|
||||||
|
private MobEditorScreen screen;
|
||||||
|
private ContentDraft guiDraft;
|
||||||
|
private int eggCount;
|
||||||
|
MobNetworkVerification(EditorConnection connection, Runnable complete, Consumer<String> failure) {
|
||||||
|
this.connection = connection; this.complete = complete; this.failure = failure;
|
||||||
|
}
|
||||||
|
void tick() {
|
||||||
|
if (++tick > 1600) { failure.accept("Mob verification timeout in stage " + stage); return; }
|
||||||
|
if (waiting || tick < next) return;
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
try {
|
||||||
|
switch (stage) {
|
||||||
|
case 0 -> request("mob_catalog", new JsonObject(), true, response -> {
|
||||||
|
catalog.update(response);
|
||||||
|
if (catalog.values("conditions").size() != 7 || catalog.values("mobEntities").isEmpty()) throw new IllegalStateException("Incomplete mob catalog");
|
||||||
|
});
|
||||||
|
case 1 -> {
|
||||||
|
var fallback = JsonParser.parseString("{\"skills\":[\"delay 1\"]}").getAsJsonObject(); fallback.addProperty("id", id + "_fallback");
|
||||||
|
request("skill_save", save(fallback, "new"), true, response -> {});
|
||||||
|
}
|
||||||
|
case 2 -> {
|
||||||
|
skill = JsonParser.parseString("""
|
||||||
|
{"cooldown":1,"conditions":["incombat false","targetwithin{d=5} false","playerwithin{d=12} true",
|
||||||
|
"hasaura{n=sample} false","hasmodel false","isblocking false"],"targetConditions":["isblocking false"],"skills":["delay 1"]}
|
||||||
|
""").getAsJsonObject();
|
||||||
|
skill.addProperty("id", id + "_skill");
|
||||||
|
skill.getAsJsonArray("conditions").add("modelhaspassenger{p=seat} orElseCast " + id + "_fallback");
|
||||||
|
request("skill_save", save(skill, "new"), true, response -> skillRevision = response.get("revision").getAsString());
|
||||||
|
}
|
||||||
|
case 3 -> {
|
||||||
|
mob = JsonParser.parseString("{\"name\":\"Проверка меню моба\",\"entity\":\"minecraft:pig\",\"health\":60,\"damage\":3,\"options\":{\"NoGravity\":true},\"skills\":[],\"drops\":[\"minecraft:emerald 1-2 0.5\"]}").getAsJsonObject();
|
||||||
|
mob.addProperty("id", id); mob.addProperty("extensionPreserved", "Модель 🐟 ".repeat(1800) + "x".repeat(300000));
|
||||||
|
mob.getAsJsonArray("skills").add("skill{s=" + id + "_skill} @self ~onSpawn ?!hasaura{n=sample}");
|
||||||
|
request("mob_save", save(mob, "new"), true, response -> revision = response.get("revision").getAsString());
|
||||||
|
}
|
||||||
|
case 4 -> request("mob_get", id(id), true, response -> {
|
||||||
|
if (!response.getAsJsonObject("document").get("extensionPreserved").equals(mob.get("extensionPreserved"))) throw new IllegalStateException("Chunked Unicode document changed");
|
||||||
|
if (response.getAsJsonObject("details").getAsJsonArray("referencedSkills").isEmpty()) throw new IllegalStateException("Missing referenced skill details");
|
||||||
|
});
|
||||||
|
case 5 -> { mob.addProperty("health", 80); request("mob_save", save(mob, revision), true, response -> {}); }
|
||||||
|
case 6 -> request("mob_save", save(mob, revision), false, response -> {});
|
||||||
|
case 7 -> {
|
||||||
|
var invalid = skill.deepCopy(); invalid.getAsJsonArray("conditions").add("not_a_condition true");
|
||||||
|
request("skill_save", save(invalid, skillRevision), false, response -> {});
|
||||||
|
}
|
||||||
|
case 8 -> request("skill_get", id(id + "_skill"), true, response -> {
|
||||||
|
if (!response.get("revision").getAsString().equals(skillRevision)) throw new IllegalStateException("Rejected skill changed file");
|
||||||
|
});
|
||||||
|
case 9 -> request("mob_egg", id(id), true, response -> {});
|
||||||
|
case 10 -> {
|
||||||
|
boolean found = false;
|
||||||
|
var inventory = minecraft.player.getInventory();
|
||||||
|
for (int index = 0; index < inventory.getContainerSize(); index++) {
|
||||||
|
var tag = inventory.getItem(index).getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
|
||||||
|
if (tag.getString("astraplus:mob_egg").orElse("").equals(id)) found = true;
|
||||||
|
}
|
||||||
|
if (!found) throw new IllegalStateException("Mob egg inventory sync missing");
|
||||||
|
stage++;
|
||||||
|
}
|
||||||
|
case 11 -> request("mob_spawn", id(id), true, response -> {});
|
||||||
|
case 12 -> request("mob_get", id(id), true, response -> {
|
||||||
|
guiDraft = MobDocuments.draft(response);
|
||||||
|
screen = new MobEditorScreen(new MobBrowserScreen(connection, false), connection, catalog, guiDraft, false, response.getAsJsonObject("details"));
|
||||||
|
minecraft.gui.setScreen(screen);
|
||||||
|
});
|
||||||
|
case 13 -> {
|
||||||
|
waiting = true;
|
||||||
|
Screenshot.grab(minecraft.gameDirectory, "22-network-mob-editor.png", minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> { waiting = false; stage++; });
|
||||||
|
}
|
||||||
|
case 14 -> request("skill_get", id(id + "_skill"), true, response -> minecraft.gui.setScreen(new MobEditorScreen(screen, connection, catalog,
|
||||||
|
MobDocuments.draft(response), true, response.getAsJsonObject("details"))));
|
||||||
|
case 15 -> {
|
||||||
|
waiting = true;
|
||||||
|
Screenshot.grab(minecraft.gameDirectory, "23-network-skill-editor.png", minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> { waiting = false; stage++; });
|
||||||
|
}
|
||||||
|
case 16 -> { minecraft.gui.setScreen(screen); eggCount = eggs(); click("Яйцо призыва"); stage++; next = tick + 12; }
|
||||||
|
case 17 -> { if (eggs() != eggCount + 1) throw new IllegalStateException("Actual GUI egg button did not issue correct mob egg"); stage++; }
|
||||||
|
case 18 -> { guiDraft.number("95", false, 1, 1000000, "health"); click("Сохранить"); stage++; next = tick + 12; }
|
||||||
|
case 19 -> { if (guiDraft.dirty()) return; stage++; }
|
||||||
|
case 20 -> request("mob_get", id(id), true, response -> {
|
||||||
|
if (response.getAsJsonObject("document").get("health").getAsInt() != 95) throw new IllegalStateException("Actual GUI save button did not persist mob health");
|
||||||
|
});
|
||||||
|
case 21 -> { waiting = true; complete.run(); }
|
||||||
|
default -> throw new IllegalStateException("Unknown mob stage " + stage);
|
||||||
|
}
|
||||||
|
} catch (Exception error) { failure.accept("Mob stage " + stage + ": " + error); }
|
||||||
|
}
|
||||||
|
private void click(String name) {
|
||||||
|
for (var child : Minecraft.getInstance().gui.screen().children()) if (child instanceof net.minecraft.client.gui.components.Button button && button.getMessage().getString().equals(name)) {
|
||||||
|
if (!button.active) throw new IllegalStateException("Disabled GUI control: " + name);
|
||||||
|
button.onPress(new net.minecraft.client.input.KeyEvent(org.lwjgl.glfw.GLFW.GLFW_KEY_ENTER, 0, 0)); return;
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Missing GUI control: " + name);
|
||||||
|
}
|
||||||
|
private int eggs() {
|
||||||
|
int count = 0; var inventory = Minecraft.getInstance().player.getInventory();
|
||||||
|
for (int index = 0; index < inventory.getContainerSize(); index++) {
|
||||||
|
var stack = inventory.getItem(index); var tag = stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag();
|
||||||
|
if (tag.getString("astraplus:mob_egg").orElse("").equals(id)) count += stack.getCount();
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
private void request(String action, JsonObject body, boolean expected, Consumer<JsonObject> check) {
|
||||||
|
waiting = true;
|
||||||
|
connection.request(action, body, response -> {
|
||||||
|
try {
|
||||||
|
if (EditorConnection.success(response) != expected) throw new IllegalStateException(action + ": " + EditorConnection.message(response));
|
||||||
|
check.accept(response); stage++; next = tick + 10; waiting = false;
|
||||||
|
} catch (Exception error) { failure.accept("Mob stage " + stage + ": " + error); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private JsonObject save(JsonObject document, String revision) {
|
||||||
|
var request = id(document.get("id").getAsString()); request.addProperty("revision", revision); request.add("document", document); return request;
|
||||||
|
}
|
||||||
|
private JsonObject id(String value) { var request = new JsonObject(); request.addProperty("id", value); return request; }
|
||||||
|
}
|
||||||
+17
-2
@@ -33,12 +33,16 @@ final class NetworkVerification {
|
|||||||
private final online.astradev.plus.editor.client.EditorCatalog catalog = new online.astradev.plus.editor.client.EditorCatalog();
|
private final online.astradev.plus.editor.client.EditorCatalog catalog = new online.astradev.plus.editor.client.EditorCatalog();
|
||||||
private online.astradev.plus.editor.screen.ContentEditorScreen editor;
|
private online.astradev.plus.editor.screen.ContentEditorScreen editor;
|
||||||
private ContentDraft preview;
|
private ContentDraft preview;
|
||||||
|
private MobNetworkVerification mobs;
|
||||||
|
private PreviewVerification models;
|
||||||
|
|
||||||
public void tick() {
|
public void tick() {
|
||||||
if (finished) return;
|
if (finished) return;
|
||||||
var minecraft = Minecraft.getInstance();
|
var minecraft = Minecraft.getInstance();
|
||||||
try {
|
try {
|
||||||
if (++tick > 2400) throw new IllegalStateException("Network verification timed out in stage " + stage);
|
if (++tick > 4000) throw new IllegalStateException("Network verification timed out in stage " + stage);
|
||||||
|
if (models != null) { models.tick(); return; }
|
||||||
|
if (mobs != null) { mobs.tick(); return; }
|
||||||
if (!connecting) {
|
if (!connecting) {
|
||||||
if (minecraft.gui.overlay() != null || !minecraft.isGameLoadFinished()) return;
|
if (minecraft.gui.overlay() != null || !minecraft.isGameLoadFinished()) return;
|
||||||
connecting = true;
|
connecting = true;
|
||||||
@@ -49,6 +53,12 @@ final class NetworkVerification {
|
|||||||
}
|
}
|
||||||
if (minecraft.gui.screen() instanceof DisconnectedScreen) throw new IllegalStateException("Disconnected before stage " + stage);
|
if (minecraft.gui.screen() instanceof DisconnectedScreen) throw new IllegalStateException("Disconnected before stage " + stage);
|
||||||
if (minecraft.player == null || !connection.available() || waiting || tick < nextTick) return;
|
if (minecraft.player == null || !connection.available() || waiting || tick < nextTick) return;
|
||||||
|
if (Boolean.getBoolean("astrapluseditor.mobTransportVerification")) {
|
||||||
|
mobs = new MobNetworkVerification(connection,
|
||||||
|
() -> finish("PASS: large Unicode mob request/response chunks; mob/skill CRUD; seven conditions; invalid/stale rejection; GUI egg and save controls."),
|
||||||
|
message -> finish("FAIL mob transport: " + message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
switch (stage) {
|
switch (stage) {
|
||||||
case 0 -> request("catalog", new JsonObject(), true, response -> {
|
case 0 -> request("catalog", new JsonObject(), true, response -> {
|
||||||
catalog.update(response);
|
catalog.update(response);
|
||||||
@@ -153,7 +163,12 @@ final class NetworkVerification {
|
|||||||
case 18 -> {
|
case 18 -> {
|
||||||
waiting = true;
|
waiting = true;
|
||||||
net.minecraft.client.Screenshot.grab(minecraft.gameDirectory, "15-network-properties-preview.png",
|
net.minecraft.client.Screenshot.grab(minecraft.gameDirectory, "15-network-properties-preview.png",
|
||||||
minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> finish("PASS: real client; optional channels; catalog/list/get/material; create item/block; stale edit rejected; inventory/build; food+consumable+death protection on sword; custom-block behavior condition; live item preview screenshots."));
|
minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> {
|
||||||
|
waiting = false;
|
||||||
|
mobs = new MobNetworkVerification(connection, () -> {
|
||||||
|
models = new PreviewVerification(connection, () -> finish("PASS: real client; item/block CRUD and component combination; mob/skill CRUD; all 7 conditions; large Unicode chunked save; stale/invalid rejection; egg inventory; explicit spawn; model clips and screenshots."), message -> finish("FAIL preview: " + message));
|
||||||
|
}, message -> finish("FAIL mob: " + message));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
default -> throw new IllegalStateException("Unknown stage " + stage);
|
default -> throw new IllegalStateException("Unknown stage " + stage);
|
||||||
}
|
}
|
||||||
|
|||||||
+139
@@ -0,0 +1,139 @@
|
|||||||
|
package online.astradev.plus.editor.verification;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.function.Consumer;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import net.minecraft.client.Minecraft;
|
||||||
|
import net.minecraft.client.Screenshot;
|
||||||
|
import net.minecraft.client.gui.components.Button;
|
||||||
|
import net.minecraft.client.gui.screens.Screen;
|
||||||
|
import net.minecraft.client.input.KeyEvent;
|
||||||
|
import net.minecraft.client.input.MouseButtonEvent;
|
||||||
|
import net.minecraft.client.input.MouseButtonInfo;
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewModel;
|
||||||
|
import online.astradev.plus.editor.client.preview.PreviewScene;
|
||||||
|
import online.astradev.plus.editor.network.EditorConnection;
|
||||||
|
import online.astradev.plus.editor.screen.ChoiceList;
|
||||||
|
import online.astradev.plus.editor.screen.MobPreviewScreen;
|
||||||
|
import org.lwjgl.glfw.GLFW;
|
||||||
|
|
||||||
|
/** Uses whichever server model has multiple clips; no pack-specific fixtures or world spawning. */
|
||||||
|
final class PreviewVerification {
|
||||||
|
private final EditorConnection connection;
|
||||||
|
private final Runnable success;
|
||||||
|
private final Consumer<String> failure;
|
||||||
|
private final List<String> models = new ArrayList<>();
|
||||||
|
private List<String> clips = List.of();
|
||||||
|
private MobPreviewScreen screen;
|
||||||
|
private Screen parent;
|
||||||
|
private int tick, nextTick, stage, candidate;
|
||||||
|
private volatile int completedScreenshots;
|
||||||
|
private boolean waiting, finished;
|
||||||
|
private float pausedTime;
|
||||||
|
|
||||||
|
PreviewVerification(EditorConnection connection, Runnable success, Consumer<String> failure) {
|
||||||
|
this.connection = connection; this.success = success; this.failure = failure;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tick() {
|
||||||
|
if (finished) return;
|
||||||
|
try {
|
||||||
|
if (++tick > 1200) throw new IllegalStateException("Model preview timed out in stage " + stage);
|
||||||
|
if (waiting || tick < nextTick) return;
|
||||||
|
switch (stage) {
|
||||||
|
case 0 -> request("mob_catalog", new JsonObject(), response -> {
|
||||||
|
response.getAsJsonObject("catalogs").getAsJsonArray("models").forEach(value -> models.add(value.getAsString()));
|
||||||
|
if (models.isEmpty()) throw new IllegalStateException("No external model is installed for preview verification");
|
||||||
|
parent = Minecraft.getInstance().gui.screen(); stage = 1;
|
||||||
|
});
|
||||||
|
case 1 -> {
|
||||||
|
if (candidate >= models.size()) throw new IllegalStateException("No installed model has two animations");
|
||||||
|
JsonObject body = new JsonObject(); body.addProperty("id", models.get(candidate++));
|
||||||
|
request("model_preview", body, response -> {
|
||||||
|
PreviewModel model = PreviewModel.read(response);
|
||||||
|
if (model.animations().size() < 2) return;
|
||||||
|
PreviewScene scene = new PreviewScene(model);
|
||||||
|
if (!scene.missing().isEmpty() || !scene.hasGeometry())
|
||||||
|
throw new IllegalStateException("Resource-pack geometry missing for " + model.id() + ": " + scene.missing());
|
||||||
|
clips = model.animations(); screen = new MobPreviewScreen(parent, model.id(), response);
|
||||||
|
Minecraft.getInstance().gui.setScreen(screen); stage = 2;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
case 2 -> { choose("Анимация: " + clips.get(0)); stage = 3; nextTick = tick + 15; }
|
||||||
|
case 3 -> {
|
||||||
|
if (!screen.selectedAnimation().equals(clips.get(0))) return;
|
||||||
|
capture("23-model-first-animation.png"); click("Пауза");
|
||||||
|
if (screen.isPlaying()) throw new IllegalStateException("Animation pause did not apply");
|
||||||
|
pausedTime = screen.animationTime(); stage = 4; nextTick = tick + 12;
|
||||||
|
}
|
||||||
|
case 4 -> {
|
||||||
|
if (screen.animationTime() != pausedTime) throw new IllegalStateException("Paused timeline kept advancing");
|
||||||
|
click("Сначала");
|
||||||
|
if (screen.animationTime() != 0) throw new IllegalStateException("Animation restart did not seek to zero");
|
||||||
|
click("Продолжить"); choose("Анимация: " + clips.get(1)); stage = 5; nextTick = tick + 15;
|
||||||
|
}
|
||||||
|
case 5 -> {
|
||||||
|
if (!screen.selectedAnimation().equals(clips.get(1))) return;
|
||||||
|
if (!screen.isPlaying()) throw new IllegalStateException("Second animation did not resume");
|
||||||
|
int x = screen.width / 2, y = screen.height / 2;
|
||||||
|
var mouse = new MouseButtonEvent(x, y, new MouseButtonInfo(0, 0));
|
||||||
|
screen.mouseClicked(mouse, false); screen.mouseDragged(mouse, 35, -12); screen.mouseReleased(mouse);
|
||||||
|
screen.mouseScrolled(x, y, 0, 2);
|
||||||
|
stage = 6; nextTick = tick + 12;
|
||||||
|
}
|
||||||
|
case 6 -> { capture("24-model-second-animation.png"); choose("Исходная поза"); stage = 7; nextTick = tick + 15; }
|
||||||
|
case 7 -> {
|
||||||
|
if (!screen.selectedAnimation().isEmpty()) return;
|
||||||
|
if (screen.isPlaying()) throw new IllegalStateException("Rest pose still plays a clip");
|
||||||
|
click("Сброс вида"); stage = 8; nextTick = tick + 12;
|
||||||
|
}
|
||||||
|
case 8 -> { capture("25-model-rest-pose.png"); stage = 9; nextTick = tick + 5; }
|
||||||
|
case 9 -> {
|
||||||
|
if (completedScreenshots < 3) return;
|
||||||
|
finished = true; Minecraft.getInstance().gui.setScreen(parent); success.run();
|
||||||
|
}
|
||||||
|
default -> throw new IllegalStateException("Unknown preview stage " + stage);
|
||||||
|
}
|
||||||
|
} catch (Exception error) { fail(error); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private void choose(String name) {
|
||||||
|
click("Анимация…");
|
||||||
|
for (var child : Minecraft.getInstance().gui.screen().children()) if (child instanceof ChoiceList list) {
|
||||||
|
if (list.children().size() != clips.size() + 1) throw new IllegalStateException("Animation chooser omitted registered clips");
|
||||||
|
for (var row : list.children()) if (row.getNarration().getString().equals(name)) {
|
||||||
|
row.mouseClicked(new MouseButtonEvent(20, 70, new MouseButtonInfo(0, 0)), false); return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Missing animation choice: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void click(String name) {
|
||||||
|
for (var child : Minecraft.getInstance().gui.screen().children())
|
||||||
|
if (child instanceof Button button && button.getMessage().getString().equals(name)) {
|
||||||
|
if (!button.active) throw new IllegalStateException("Disabled preview control: " + name);
|
||||||
|
button.onPress(new KeyEvent(GLFW.GLFW_KEY_ENTER, 0, 0)); return;
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Missing preview control: " + name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void request(String action, JsonObject body, Consumer<JsonObject> ready) {
|
||||||
|
waiting = true;
|
||||||
|
connection.request(action, body, response -> {
|
||||||
|
if (finished) return;
|
||||||
|
try {
|
||||||
|
if (!EditorConnection.success(response)) throw new IllegalStateException(EditorConnection.message(response));
|
||||||
|
ready.accept(response); waiting = false; nextTick = tick + 10;
|
||||||
|
} catch (Exception error) { fail(error); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void capture(String filename) {
|
||||||
|
var minecraft = Minecraft.getInstance();
|
||||||
|
Screenshot.grab(minecraft.gameDirectory, filename, minecraft.gameRenderer.mainRenderTarget(), 1, ignored -> completedScreenshots++);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fail(Exception error) { finished = true; failure.accept("Model preview stage " + stage + ": " + error); }
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user