From 0afbbc948f60cfd1c9f17d098ef375be111c2b21 Mon Sep 17 00:00:00 2001 From: ScarPC Date: Sun, 20 Sep 2026 07:23:54 +0300 Subject: [PATCH] Move cauldron gameplay into declarative AstraPlus mixing policies --- README.md | 40 +- build.gradle.kts | 13 - .../verification/SoupVerification.java | 713 ------------------ .../resources/META-INF/neoforge.mods.toml | 13 - src/integrationTest/run.ps1 | 55 -- .../astradev/cauldron/AstraCauldron.java | 217 +----- .../astradev/cauldron/CauldronAnimation.java | 29 - .../astradev/cauldron/CauldronHeat.java | 59 -- .../astradev/cauldron/CombinationRules.java | 42 -- .../astradev/cauldron/IngredientColors.java | 38 - .../online/astradev/cauldron/Ingredients.java | 306 -------- .../online/astradev/cauldron/LiquidPots.java | 444 ----------- .../astradev/cauldron/RegisteredRecipes.java | 79 -- .../online/astradev/cauldron/SoupConfig.java | 147 ---- .../online/astradev/cauldron/SoupDisplay.java | 53 -- .../online/astradev/cauldron/SoupFiles.java | 48 -- .../online/astradev/cauldron/SoupPots.java | 521 ------------- .../online/astradev/cauldron/SoupText.java | 19 - .../cauldron/mixin/CampfireHeatMixin.java | 28 - .../cauldron/mixin/CauldronWeatherMixin.java | 34 - .../cauldron/mixin/LayeredCauldronMixin.java | 20 - .../cauldron/mixin/SoupStackMixin.java | 34 - .../resources/META-INF/neoforge.mods.toml | 2 - src/main/resources/astracauldron.mixins.json | 7 - .../editor/combination-compatibility.json | 13 + .../editor/combination-defaults.json | 153 ++++ .../resources/editor/combination-schema.json | 710 +++++++++++++++++ .../cauldron/CauldronAnimationTest.java | 73 -- .../cauldron/CombinationRulesTest.java | 64 -- .../cauldron/ConfigurationPolicyTest.java | 44 -- .../cauldron/IngredientUpdateTest.java | 27 - .../astradev/cauldron/SoupConfigTest.java | 51 -- .../astradev/cauldron/SoupTextTest.java | 18 - 33 files changed, 913 insertions(+), 3201 deletions(-) delete mode 100644 src/integrationTest/java/online/astradev/cauldron/verification/SoupVerification.java delete mode 100644 src/integrationTest/resources/META-INF/neoforge.mods.toml delete mode 100644 src/integrationTest/run.ps1 delete mode 100644 src/main/java/online/astradev/cauldron/CauldronAnimation.java delete mode 100644 src/main/java/online/astradev/cauldron/CauldronHeat.java delete mode 100644 src/main/java/online/astradev/cauldron/CombinationRules.java delete mode 100644 src/main/java/online/astradev/cauldron/IngredientColors.java delete mode 100644 src/main/java/online/astradev/cauldron/Ingredients.java delete mode 100644 src/main/java/online/astradev/cauldron/LiquidPots.java delete mode 100644 src/main/java/online/astradev/cauldron/RegisteredRecipes.java delete mode 100644 src/main/java/online/astradev/cauldron/SoupConfig.java delete mode 100644 src/main/java/online/astradev/cauldron/SoupDisplay.java delete mode 100644 src/main/java/online/astradev/cauldron/SoupFiles.java delete mode 100644 src/main/java/online/astradev/cauldron/SoupPots.java delete mode 100644 src/main/java/online/astradev/cauldron/SoupText.java delete mode 100644 src/main/java/online/astradev/cauldron/mixin/CampfireHeatMixin.java delete mode 100644 src/main/java/online/astradev/cauldron/mixin/CauldronWeatherMixin.java delete mode 100644 src/main/java/online/astradev/cauldron/mixin/LayeredCauldronMixin.java delete mode 100644 src/main/java/online/astradev/cauldron/mixin/SoupStackMixin.java delete mode 100644 src/main/resources/astracauldron.mixins.json create mode 100644 src/main/resources/editor/combination-compatibility.json create mode 100644 src/main/resources/editor/combination-defaults.json create mode 100644 src/main/resources/editor/combination-schema.json delete mode 100644 src/test/java/online/astradev/cauldron/CauldronAnimationTest.java delete mode 100644 src/test/java/online/astradev/cauldron/CombinationRulesTest.java delete mode 100644 src/test/java/online/astradev/cauldron/ConfigurationPolicyTest.java delete mode 100644 src/test/java/online/astradev/cauldron/IngredientUpdateTest.java delete mode 100644 src/test/java/online/astradev/cauldron/SoupConfigTest.java delete mode 100644 src/test/java/online/astradev/cauldron/SoupTextTest.java diff --git a/README.md b/README.md index f82f77b..844d372 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # AstraCauldron -Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**. -Требуется **AstraPlus 0.9.9+**. +Исходные данные стартового набора смешивания для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**. +Runtime находится в общем capability `mixing` **AstraPlus 0.9.9+**; отдельный AstraCauldron +содержит только совместимую идентичность мода и не добавляет обработчиков или mixin. Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks. Модели супа зарегистрированы через AstraPlus и берутся из JAR. Пользовательские замены можно положить в `astraplus/resources/assets/astradev_soups`; мод не переписывает их. @@ -157,18 +158,39 @@ Minecraft и мода не является общей транзакцией с другими модами действия уважаются. Внешняя замена блока очищает состояние при проверке. ```powershell -.\gradlew.bat build -.\gradlew.bat integrationTest +cd ../AstraPlus +.\gradlew.bat build mixingTestJar +pwsh -File src/mixingTest/run.ps1 ``` -Перед сборкой нужен JAR соседнего AstraPlus; серверные тесты запускаются через PowerShell 7. Серверные тесты из src/integrationTest -используют отдельные миры в build и проверяют игровой процесс и сохранение после -перезапуска. На рабочий сервер устанавливается только основной JAR из build/libs. +Unit- и серверные тесты перенесены в AstraPlus. Изолированный сервер загружает только основной +AstraPlus и тестовый JAR, использует отдельные миры в build и проверяет игровой процесс и +сохранение после перезапуска. Тестовый JAR запрещено устанавливать на рабочий сервер. ## Настройки -Файл config/astracauldron.json применяется через `/astracauldron reload`. +Файл `config/astracauldron.json` применяется через `/cauldron reload` или через +карточку механики `astracauldron:combination_rules` в Astra Studio. Веб-редактор сохраняет +именно этот файл и сразу публикует проверенные настройки в работающую механику: отдельной +копии правил внутри редактора нет. Сохранение требует действующей сессии записи и текущей +ревизии; конфликт или ошибка проверки не изменяют файл и рабочую конфигурацию. Отсутствующие поля получают значения по умолчанию; существующий файл не перезаписывается. +Значения по умолчанию, включая питание торта и палитру ингредиентов, находятся в +`src/main/resources/editor/combination-defaults.json`; схема формы — рядом. Неизвестные +ключи сохраняются при веб-редактировании. Сочетания, ингредиенты, эффекты, цвета и замены +сообщений редактируются отдельными строками без ввода JSON. Дополнительные компоненты +сохранённых образцов предметов не редактируются в этой форме и сохраняются без изменений. + +Раздел `engine` определяет реальные предмет-носитель, модель, возвращаемый предмет, источники +нагрева и типы контейнеров, нормализуемые предметы, лимиты, геометрию отображения, звуки, +частицы и интервалы обновления. Эти параметры читаются общим runtime, а не дублируют +константы старого мода. Новый раздел подставляется для прежних конфигураций только в памяти. +Неизменяемые пути старого сохранения, теги предметов и команды находятся отдельно в +`combination-compatibility.json`; они обеспечивают чтение существующего мира без миграции. +Ограничения нативного протокола сохраняются: слоистый контейнер имеет не более трёх уровней, +цвет — RGB24, допустимые частицы не требуют дополнительных параметров. Runtime не является +произвольным языком скриптов: последовательность наполнения/варки/выдачи остаётся общим +алгоритмом capability, а существующие значения и правила управляются данными. | Настройка | По умолчанию | Назначение | |---|---|---| @@ -187,5 +209,7 @@ Minecraft и мода не является общей транзакцией с | blockedIngredients / incompatible / customIngredients | пустые | Запреты, несовместимость, свои ингредиенты | | messageOverrides | {} | Замена полного текста сообщений | | soupName / defaultColor | Комбинированный суп / #B77A36 | Имя и цвет | +| cakeNutrition / cakeSaturation | 14 / 2.8 | Питание и насыщение целого торта | +| ingredientColors | встроенная палитра | Цвета материалов ингредиентов в формате #RRGGBB | Свойства готового супа сохраняются. Новые настройки рецептуры действуют на следующую варку. diff --git a/build.gradle.kts b/build.gradle.kts index f1ab594..907c670 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -39,16 +39,3 @@ sourceSets.test { compileClasspath += sourceSets.main.get().compileClasspath runtimeClasspath += sourceSets.main.get().compileClasspath } -val integrationTest = sourceSets.create("integrationTest") { - compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath - runtimeClasspath += output + compileClasspath -} -tasks.register("integrationTestJar") { - from(integrationTest.output) - archiveClassifier.set("integration-tests") -} - -tasks.register("integrationTest") { - dependsOn("build", "integrationTestJar") - commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/run.ps1") -} diff --git a/src/integrationTest/java/online/astradev/cauldron/verification/SoupVerification.java b/src/integrationTest/java/online/astradev/cauldron/verification/SoupVerification.java deleted file mode 100644 index 4e2eb7e..0000000 --- a/src/integrationTest/java/online/astradev/cauldron/verification/SoupVerification.java +++ /dev/null @@ -1,713 +0,0 @@ -package online.astradev.cauldron.verification; - -import com.google.gson.*; - -import net.minecraft.core.*; -import net.minecraft.core.component.DataComponents; -import net.minecraft.resources.Identifier; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.*; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.effect.*; -import net.minecraft.world.entity.Display; -import net.minecraft.world.item.*; -import net.minecraft.world.item.alchemy.*; -import net.minecraft.world.item.component.*; -import net.minecraft.world.item.consume_effects.*; -import net.minecraft.world.level.GameType; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.storage.LevelResource; -import net.minecraft.world.phys.*; -import net.neoforged.api.distmarker.Dist; -import net.neoforged.fml.common.Mod; -import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.common.util.FakePlayerFactory; -import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; -import net.neoforged.neoforge.event.level.block.BreakBlockEvent; -import net.neoforged.neoforge.event.tick.ServerTickEvent; - -import online.astradev.cauldron.*; -import online.astradev.plus.api.*; - -import java.nio.file.*; -import java.util.*; -import java.util.zip.ZipFile; - -/** - * Requires a fresh isolated world. Writes fixtures and stops this server. Never install in - * production. - */ -@Mod(value = "astracauldron_verify", dist = Dist.DEDICATED_SERVER) -public final class SoupVerification { - private static final BlockPos READY = new BlockPos(8, 100, 8), - RAW = new BlockPos(10, 100, 8), - BREW = new BlockPos(12, 100, 8); - private final List passed = new ArrayList<>(); - private int tick; - private boolean finished, restart; - private ServerPlayer player; - - public SoupVerification() { - if (!Boolean.getBoolean("astracauldron.isolatedVerification")) - throw new IllegalStateException("Isolated verification flag required"); - NeoForge.EVENT_BUS.addListener(this::tick); - } - - private void tick(ServerTickEvent.Post event) { - if (finished) return; - var server = event.getServer(); - var level = server.overworld(); - try { - tick++; - if (tick == 1) { - restart = Files.exists(Path.of("first-pass.txt")); - server.getCommands() - .performPrefixedCommand( - server.createCommandSourceStack(), "forceload add 0 0 31 15"); - level.getChunk(0, 0); - level.getChunk(1, 0); - player = FakePlayerFactory.getMinecraft(level); - player.setGameMode(GameType.SURVIVAL); - player.setPos(8, 101, 8); - } - if (restart) { - if (tick == 10) { - require( - AstraCauldron.pots().get(level, READY).servings() == 2, - "ready servings restored"); - require( - AstraCauldron.pots().get(level, RAW).items().size() == 1, - "raw ingredient restored"); - require( - AstraCauldron.pots().get(level, BREW).brewTicks() > 0, - "unfinished brew restarts its timer"); - require( - water().find(level, READY).isPresent(), - "AstraPlus water restored by soup owner"); - require( - displays(level, READY).size() == 1, - "single colored water display after restart"); - var storedPotion = AstraCauldron.liquids().get(level, new BlockPos(24, 100, 8)); - require( - storedPotion.levels() == 2 - && storedPotion - .potion() - .contents() - .is(Potions.LONG_NIGHT_VISION), - "potion contents and volume survive restart"); - require( - AstraCauldron.liquids().get(level, new BlockPos(26, 100, 8)).levels() - == 2, - "dyed water volume survives restart"); - } - if (tick == 110) { - require( - AstraCauldron.pots().get(level, BREW).brewTicks() == 0, - "restored brew finishes"); - use(READY, new ItemStack(Items.BOWL)); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY) == null - && water().find(level, READY).isEmpty(), - "last serving clears saved pot and water API"); - finish(server, "restart"); - } - return; - } - if (tick == 10) { - checkIngredients(server, level); - checkWater(level); - checkInteractions(server, level); - checkLiquids(level); - fill(level, READY); - for (int i = 0; i < 4; i++) use(READY, new ItemStack(Items.CARROT)); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY).soup().isEmpty(), - "cannot brew without campfire; ingredients preserved"); - level.setBlock( - READY.below(), - Blocks.CAMPFIRE - .defaultBlockState() - .setValue(net.minecraft.world.level.block.CampfireBlock.LIT, false), - 3); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY).soup().isEmpty(), - "unlit campfire cannot start soup"); - level.setBlock(READY.below(), Blocks.CAMPFIRE.defaultBlockState(), 3); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY).brewTicks() > 0, - "four ingredients start timed brew"); - level.setBlock(READY.below(), Blocks.AIR.defaultBlockState(), 3); - for (int i = 0; i < 100; i++) AstraCauldron.pots().tick(); - require( - AstraCauldron.pots().get(level, READY).brewTicks() > 0, - "removing fire pauses cooking beyond full duration"); - level.setBlock(READY.below(), Blocks.SOUL_CAMPFIRE.defaultBlockState(), 3); - require( - online.astradev.cauldron.CauldronHeat.heated(level, READY), - "soul campfire resumes heating"); - require( - displays(level, READY).size() == 4, - "four ingredient displays while brewing"); - require( - displays(level, READY).stream().noneMatch(Display::shouldBeSaved), - "ingredient displays never persist as entities"); - } - if (tick == 100) { - require( - AstraCauldron.pots().get(level, READY).brewTicks() == 0, - "brew finishes after 80 ticks"); - require(displays(level, READY).size() == 1, "AstraPlus owns single liquid display"); - require( - displays(level, READY) - .getFirst() - .entityTags() - .contains("astraplus:colored_water"), - "liquid belongs to AstraPlus"); - var id = displays(level, READY).getFirst().getUUID(); - float height = water().find(level, READY).orElseThrow().height(); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY).servings() == 3 - && water().find(level, READY).orElseThrow().height() < height, - "portion lowers water API height"); - require( - displays(level, READY).getFirst().getUUID().equals(id), - "portion interpolates same display"); - use(READY, new ItemStack(Items.BOWL)); - require( - AstraCauldron.pots().get(level, READY).servings() == 2, - "two saved servings remain"); - checkSaveFailure(server, level); - fill(level, RAW); - use(RAW, new ItemStack(Items.APPLE)); - fill(level, BREW); - level.setBlock(BREW.below(), Blocks.CAMPFIRE.defaultBlockState(), 3); - for (int i = 0; i < 4; i++) use(BREW, new ItemStack(Items.BREAD)); - use(BREW, new ItemStack(Items.BOWL)); - try (var zip = new ZipFile("astraplus/output/AstraPlus.zip")) { - require( - zip.getEntry("assets/astraplus/items/colored_water.json") != null, - "AstraPlus packs its own water resource"); - require( - zip.getEntry("assets/astradev_soups/items/combined_soup.json") != null, - "AstraCauldron bowl exported before AstraPlus pack build"); - } - Files.writeString(Path.of("first-pass.txt"), "passed"); - finish(server, "gameplay"); - } - } catch (Throwable e) { - finished = true; - e.printStackTrace(); - try { - Files.writeString( - Path.of("verification-result.txt"), - "FAIL at tick " + tick + ": " + e + "\n" + String.join("\n", passed)); - } catch (Exception ignored) { - } - server.halt(false); - } - } - - private void checkIngredients(MinecraftServer server, ServerLevel level) throws Exception { - var ingredients = AstraCauldron.pots().ingredients(); - for (var item : - List.of( - Items.MUSHROOM_STEW, - Items.RABBIT_STEW, - Items.BEETROOT_SOUP, - Items.SUSPICIOUS_STEW)) - require(new ItemStack(item).getMaxStackSize() == 16, "native per-stack size " + item); - require( - ingredients.read(new ItemStack(Items.CAKE)).nutrition() == 14, - "whole cake nutrition"); - require(ingredients.read(new ItemStack(Items.TIPPED_ARROW)) == null, "arrows rejected"); - var potion = new ItemStack(Items.POTION); - potion.set(DataComponents.POTION_CONTENTS, new PotionContents(Potions.LONG_NIGHT_VISION)); - var recipe = - List.of( - potion, - new ItemStack(Items.COOKED_BEEF), - new ItemStack(Items.GLOW_BERRIES), - new ItemStack(Items.GOLDEN_APPLE)); - var soup = ingredients.brew(recipe); - require(soup.get(DataComponents.FOOD).nutrition() == 14, "summed native food nutrition"); - require(soup.get(DataComponents.FOOD).canAlwaysEat(), "soup consumable at full hunger"); - var reversed = new ArrayList<>(recipe); - Collections.reverse(reversed); - require( - ItemStack.isSameItemSameComponents(soup, ingredients.brew(reversed)), - "recipe order independent stacking"); - require( - ItemStack.isSameItemSameComponents( - soup, - decode(encode(soup, server.registryAccess()), server.registryAccess())), - "native item codec preserves full soup"); - var applied = - soup.get(DataComponents.CONSUMABLE).onConsumeEffects().stream() - .filter(e -> e instanceof ApplyStatusEffectsConsumeEffect) - .map(e -> (ApplyStatusEffectsConsumeEffect) e) - .flatMap(e -> e.effects().stream()) - .toList(); - require( - applied.stream() - .anyMatch( - e -> - e.getEffect().equals(MobEffects.NIGHT_VISION) - && e.getDuration() == 9600), - "potion full duration preserved"); - require( - applied.stream().anyMatch(e -> e.getEffect().equals(MobEffects.REGENERATION)), - "golden apple effects preserved"); - player.getInventory().clearContent(); - player.getFoodData().setFoodLevel(1); - player.removeAllEffects(); - var eaten = soup.copyWithCount(2); - eaten.finishUsingItem(level, player); - require( - eaten.getCount() == 1 - && player.getFoodData().getFoodLevel() == 15 - && player.hasEffect(MobEffects.NIGHT_VISION), - "native consumption feeds and applies effects"); - require( - player.getInventory().countItem(Items.BOWL) == 1, - "native stacked consumption returns bowl"); - require( - ingredients.read(new ItemStack(Items.CHORUS_FRUIT)).effects().stream() - .anyMatch(e -> e instanceof TeleportRandomlyConsumeEffect), - "chorus teleport retained"); - require( - ingredients.read(new ItemStack(Items.POISONOUS_POTATO)).effects().stream() - .anyMatch( - e -> - e instanceof ApplyStatusEffectsConsumeEffect a - && a.probability() < 1), - "probabilistic effects retained"); - var api = AstraPlusApi.current().orElseThrow(); - var id = Identifier.parse("verify:soup_food"); - api.save( - id, - AstraPlusApi.NEW_REVISION, - JsonParser.parseString( - """ - {"name":"Test food","material":"minecraft:paper","texture":"minecraft:item/paper", - "components":{"minecraft:food":{"nutrition":7,"saturation":4.5,"can_always_eat":true},"minecraft:consumable":{}}} - """) - .getAsJsonObject()); - var food = api.create(id, 1); - require( - ingredients.read(food).nutrition() == 7 - && ingredients.read(food).tags().contains("astraplus:verify:soup_food"), - "AstraPlus identity and native food read via public API"); - require( - ingredients.read(new ItemStack(Items.PAPER)) == null, - "ordinary carrier is not custom food"); - player.setItemInHand(InteractionHand.MAIN_HAND, food); - AstraCauldron.pots().register("plus_food", player, 9, 6); - require( - AstraCauldron.pots().ingredients().read(food).nutrition() == 9, - "custom AstraPlus registration overrides nutrition"); - var c = api.find(id).orElseThrow(); - var doc = c.document(); - doc.addProperty("name", "Changed name"); - api.save(id, c.revision(), doc); - require( - AstraCauldron.pots().ingredients().read(api.create(id, 1)).nutrition() == 9, - "registration survives AstraPlus definition edits"); - String original = Files.readString(Path.of("config/astracauldron.json")); - Files.writeString(Path.of("config/astracauldron.json"), "{\"brewSeconds\":-1}"); - try { - AstraCauldron.pots().reload(); - throw new AssertionError("invalid config accepted"); - } catch (IllegalArgumentException expected) { - require(true, "invalid reload rejected"); - } finally { - Files.writeString(Path.of("config/astracauldron.json"), original); - } - require( - AstraCauldron.pots().ingredients().read(api.create(id, 1)).nutrition() == 9, - "invalid reload leaves previous runtime intact"); - } - - private void checkWater(ServerLevel level) throws Exception { - var pos = new BlockPos(22, 100, 8); - level.setBlock(pos, Blocks.CAULDRON.defaultBlockState(), 3); - var owner = Identifier.parse("verify:water"); - var other = Identifier.parse("verify:other"); - var water = water(); - require( - water.show(level, pos, new ColoredWaterApi.Surface(owner, 0xFF0000, .8f)), - "independent water API creates surface without soup"); - var display = displays(level, pos).getFirst(); - require( - display.getSlot(0) - .get() - .get(DataComponents.ITEM_MODEL) - .equals(Identifier.parse("astraplus:colored_water")), - "AstraPlus generic water model"); - require( - !water.show(level, pos, new ColoredWaterApi.Surface(other, 0, .5f)) - && !water.remove(level, pos, other), - "water owner isolation"); - require( - water.show(level, pos, new ColoredWaterApi.Surface(owner, 0x00FF00, .6f)), - "color and height update"); - require( - displays(level, pos).getFirst().getUUID().equals(display.getUUID()), - "API update reuses entity"); - display.discard(); - water.show(level, pos, new ColoredWaterApi.Surface(owner, 0x00FF00, .6f)); - require( - displays(level, pos).size() == 1 - && !displays(level, pos).getFirst().getUUID().equals(display.getUUID()), - "removed entity recreated once"); - require( - !water.show( - level, - new BlockPos(100000, 100, 100000), - new ColoredWaterApi.Surface(owner, 0, .5f)), - "API never loads chunks"); - // API JAR intentionally does not expose the concrete service; tested through the live API - // below. - water.removeAll(owner); - require( - displays(level, pos).isEmpty() && water.find(level, pos).isEmpty(), - "owner cleanup removes surface"); - try { - new ColoredWaterApi.Surface(owner, 0x1000000, .5f); - throw new AssertionError("invalid RGB"); - } catch (IllegalArgumentException expected) { - require(true, "API validates RGB"); - } - try { - new ColoredWaterApi.Surface(owner, 0, Float.NaN); - throw new AssertionError("invalid height"); - } catch (IllegalArgumentException expected) { - require(true, "API validates finite height"); - } - } - - private void checkInteractions(MinecraftServer server, ServerLevel level) { - var pos = new BlockPos(4, 100, 8); - fill(level, pos); - player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.APPLE, 2)); - var denied = click(pos); - denied.setCanceled(true); - NeoForge.EVENT_BUS.post(denied); - require( - AstraCauldron.pots().get(level, pos) == null - && player.getMainHandItem().getCount() == 2, - "cancelled interaction is respected"); - NeoForge.EVENT_BUS.post(click(pos)); - require( - AstraCauldron.pots().get(level, pos).items().size() == 1 - && player.getMainHandItem().getCount() == 1, - "event insertion consumes one"); - LayeredCauldronBlock.lowerFillLevel(level.getBlockState(pos), level, pos); - require( - level.getBlockState(pos).getValue(LayeredCauldronBlock.LEVEL) == 3, - "vanilla level mutation blocked for occupied pot"); - var blockedBreak = new BreakBlockEvent(level, pos, level.getBlockState(pos), player); - blockedBreak.setCanceled(true); - NeoForge.EVENT_BUS.post(blockedBreak); - require( - AstraCauldron.pots().get(level, pos) != null, - "cancelled breaking preserves ingredients"); - use(pos, ItemStack.EMPTY); - require( - AstraCauldron.pots().get(level, pos) == null, - "empty hand returns ingredient and removes pot"); - LayeredCauldronBlock.lowerFillLevel(level.getBlockState(pos), level, pos); - require( - level.getBlockState(pos).getValue(LayeredCauldronBlock.LEVEL) == 2, - "ordinary cauldron retains vanilla behavior"); - use(pos, new ItemStack(Items.APPLE)); - require(AstraCauldron.pots().get(level, pos) == null, "full water required"); - } - - private void checkSaveFailure(MinecraftServer server, ServerLevel level) throws Exception { - Path file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json"); - Path backup = file.resolveSibling("cauldrons.saved.json"); - Files.move(file, backup); - Files.createDirectory(file); - try { - use(READY, new ItemStack(Items.BOWL, 2)); - require( - AstraCauldron.pots().get(level, READY).servings() == 2 - && player.getMainHandItem().getCount() == 2, - "failed save rolls back pot and consumes no bowl"); - } finally { - Files.delete(file); - Files.move(backup, file); - } - } - - private void checkLiquids(ServerLevel level) throws Exception { - var api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow(); - var plain = new BlockPos(20, 100, 8); - level.setBlock(plain, Blocks.CAULDRON.defaultBlockState(), 3); - for (var type : List.of(Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION)) - use(plain, PotionContents.createItemStack(type, Potions.WATER)); - require( - level.getBlockState(plain).is(Blocks.WATER_CAULDRON) - && level.getBlockState(plain).getValue(LayeredCauldronBlock.LEVEL) == 3 - && !AstraCauldron.liquids().contains(level, plain), - "all water bottle kinds fill vanilla water, never become soup"); - var dye = new ItemStack(Items.DYE.pick(DyeColor.RED)); - int red = api.mixDye(OptionalInt.empty(), dye).orElseThrow(); - checkDyedBlocks(level, api); - var pos = new BlockPos(18, 100, 8); - for (var armor : - List.of( - Items.LEATHER_HELMET, - Items.LEATHER_CHESTPLATE, - Items.LEATHER_LEGGINGS, - Items.LEATHER_BOOTS, - Items.LEATHER_HORSE_ARMOR, - Items.WOLF_ARMOR)) { - AstraCauldron.liquids().breakPot(level, pos); - fill(level, pos); - use(pos, dye.copyWithCount(2)); - require( - player.getMainHandItem().getCount() == 1 - && AstraCauldron.liquids().get(level, pos).levels() == 3, - "dye consumes one, keeps water volume: " + armor); - var stack = new ItemStack(armor); - stack.set( - DataComponents.CUSTOM_NAME, - net.minecraft.network.chat.Component.literal("Keep name")); - if (stack.isDamageableItem()) stack.setDamageValue(3); - use(pos, stack); - var result = player.getMainHandItem(); - require( - result.is(armor) - && result.get(DataComponents.DYED_COLOR).rgb() == red - && result.get(DataComponents.CUSTOM_NAME) - .getString() - .equals("Keep name"), - "armor dyed with metadata preserved: " + armor); - require( - AstraCauldron.liquids().get(level, pos).levels() == 2, - "armor costs one water level: " + armor); - if (result.isDamageableItem()) - require(result.getDamageValue() == 3, "armor damage preserved: " + armor); - } - use(pos, new ItemStack(Items.DYE.pick(DyeColor.BLUE))); - require( - AstraCauldron.liquids().get(level, pos).rgb() != red, - "second dye mixes water color"); - var originalArmor = new ItemStack(Items.LEATHER_HELMET); - var transformedArmor = api.dyeArmor(originalArmor, red).orElseThrow(); - require( - !originalArmor.has(DataComponents.DYED_COLOR) - && transformedArmor.has(DataComponents.DYED_COLOR), - "AstraPlus armor API never mutates input"); - use(pos, new ItemStack(Items.IRON_CHESTPLATE)); - require( - !player.getMainHandItem().has(DataComponents.DYED_COLOR) - && AstraCauldron.liquids().get(level, pos).levels() == 2, - "non-leather armor rejected without water loss"); - AstraCauldron.liquids().breakPot(level, pos); - level.setBlock(pos, Blocks.CAULDRON.defaultBlockState(), 3); - player.getInventory().clearContent(); - for (var type : List.of(Items.POTION, Items.SPLASH_POTION, Items.LINGERING_POTION)) { - use(pos, PotionContents.createItemStack(type, Potions.LONG_NIGHT_VISION)); - } - require( - AstraCauldron.liquids().get(level, pos).levels() == 3 - && player.getInventory().countItem(Items.GLASS_BOTTLE) == 3, - "all three potion bottle kinds fill same potion, return glass"); - var different = PotionContents.createItemStack(Items.POTION, Potions.STRONG_STRENGTH); - use(pos, different); - require( - player.getMainHandItem().getCount() == 1 - && AstraCauldron.liquids().get(level, pos).levels() == 3, - "different potion rejected without item loss"); - player.getInventory().clearContent(); - use(pos, new ItemStack(Items.ARROW, 17)); - require( - player.getInventory().countItem(Items.TIPPED_ARROW) == 17 - && AstraCauldron.liquids().get(level, pos).levels() == 1, - "17 tipped arrows cost two levels"); - use(pos, new ItemStack(Items.ARROW, 32)); - require( - player.getMainHandItem().getCount() == 16 - && player.getInventory().countItem(Items.TIPPED_ARROW) == 33 - && !AstraCauldron.liquids().contains(level, pos), - "partial arrow conversion respects remaining potion volume"); - for (int i = 0; i < 3; i++) - use(pos, PotionContents.createItemStack(Items.POTION, Potions.LONG_NIGHT_VISION)); - player.getInventory().clearContent(); - use(pos, new ItemStack(Items.ARROW, 64)); - require( - player.getInventory().countItem(Items.TIPPED_ARROW) == 64 - && !AstraCauldron.liquids().contains(level, pos), - "full potion cauldron tips entire 64 arrow stack"); - var arrow = player.getInventory().getItem(0); - if (!arrow.is(Items.TIPPED_ARROW)) - for (int i = 0; i < player.getInventory().getContainerSize(); i++) - if (player.getInventory().getItem(i).is(Items.TIPPED_ARROW)) - arrow = player.getInventory().getItem(i); - require( - arrow.get(DataComponents.POTION_CONTENTS).is(Potions.LONG_NIGHT_VISION) - && arrow.get(DataComponents.POTION_DURATION_SCALE) == .125f, - "arrows preserve effects with vanilla duration multiplier"); - use(pos, PotionContents.createItemStack(Items.SPLASH_POTION, Potions.LONG_NIGHT_VISION)); - player.getInventory().clearContent(); - use(pos, new ItemStack(Items.GLASS_BOTTLE)); - require( - player.getInventory().countItem(Items.POTION) == 1 - && !AstraCauldron.liquids().contains(level, pos), - "potion storage drains back into drinkable bottle"); - var savedPotion = new BlockPos(24, 100, 8); - level.setBlock(savedPotion, Blocks.CAULDRON.defaultBlockState(), 3); - for (int i = 0; i < 2; i++) - use( - savedPotion, - PotionContents.createItemStack(Items.POTION, Potions.LONG_NIGHT_VISION)); - var savedDye = new BlockPos(26, 100, 8); - fill(level, savedDye); - use(savedDye, dye.copy()); - use(savedDye, new ItemStack(Items.LEATHER_HELMET)); - } - - private void checkDyedBlocks(ServerLevel level, online.astradev.plus.api.CauldronApi api) - throws Exception { - var pos = new BlockPos(30, 100, 8); - for (var family : List.of(Items.WOOL, Items.CARPET)) { - for (var color : DyeColor.values()) { - var source = family.pick(color == DyeColor.WHITE ? DyeColor.BLACK : DyeColor.WHITE); - int rgb = - api.mixDye(OptionalInt.empty(), new ItemStack(Items.DYE.pick(color))) - .orElseThrow(); - var named = new ItemStack(source, 64); - named.set( - DataComponents.CUSTOM_NAME, - net.minecraft.network.chat.Component.literal("Keep textile name")); - var batch = api.dyeBlocks(named, rgb, 3).orElseThrow(); - require( - batch.result().is(family.pick(color)) - && batch.result().getCount() == 64 - && batch.result() - .getHoverName() - .getString() - .equals("Keep textile name") - && named.is(source) - && named.getCount() == 64, - "textile palette and metadata: " + family.pick(color)); - } - for (int water = 1; water <= 3; water++) - for (int count : new int[] {1, 16, 17, 32, 33, 64}) { - AstraCauldron.liquids().breakPot(level, pos); - level.setBlock( - pos, - Blocks.WATER_CAULDRON - .defaultBlockState() - .setValue(LayeredCauldronBlock.LEVEL, water), - 3); - player.getInventory().clearContent(); - use(pos, new ItemStack(Items.DYE.pick(DyeColor.RED))); - use(pos, new ItemStack(family.pick(DyeColor.WHITE), count)); - int converted = Math.min(count, water == 3 ? 64 : water * 16); - int cost = converted <= 16 ? 1 : converted <= 32 ? 2 : 3; - var remaining = AstraCauldron.liquids().get(level, pos); - require( - player.getInventory().countItem(family.pick(DyeColor.RED)) == converted - && player.getInventory().countItem(family.pick(DyeColor.WHITE)) - == count - converted - && (remaining == null - ? water == cost - : remaining.levels() == water - cost), - "textile batch/inventory/water: " - + family.pick(DyeColor.WHITE) - + " count=" - + count - + " levels=" - + water); - } - } - int red = - api.mixDye(OptionalInt.empty(), new ItemStack(Items.DYE.pick(DyeColor.RED))) - .orElseThrow(); - require( - api.dyeBlocks(new ItemStack(Items.WOOL.pick(DyeColor.RED)), red, 3).isEmpty() - && api.dyeBlocks(new ItemStack(Items.STONE), red, 3).isEmpty(), - "matching colors and unsupported blocks rejected"); - AstraCauldron.liquids().breakPot(level, pos); - } - - private static JsonElement encode( - ItemStack stack, net.minecraft.core.HolderLookup.Provider registries) { - return ItemStack.CODEC - .encodeStart( - net.minecraft.resources.RegistryOps.create( - com.mojang.serialization.JsonOps.INSTANCE, registries), - stack) - .getOrThrow(); - } - - private static ItemStack decode( - JsonElement json, net.minecraft.core.HolderLookup.Provider registries) { - return ItemStack.CODEC - .parse( - net.minecraft.resources.RegistryOps.create( - com.mojang.serialization.JsonOps.INSTANCE, registries), - json) - .getOrThrow(); - } - - private void use(BlockPos pos, ItemStack item) { - var previous = player.getMainHandItem(); - player.setItemInHand(InteractionHand.MAIN_HAND, item); - // Simulate selecting another slot without deleting a returned bottle from the old hand - // slot. - if (!previous.isEmpty()) { - for (int slot = 9; slot < 36; slot++) - if (player.getInventory().getItem(slot).isEmpty()) { - player.getInventory().setItem(slot, previous); - break; - } - } - NeoForge.EVENT_BUS.post(click(pos)); - } - - private PlayerInteractEvent.RightClickBlock click(BlockPos pos) { - return new PlayerInteractEvent.RightClickBlock( - player, - InteractionHand.MAIN_HAND, - pos, - new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false)); - } - - private static void fill(ServerLevel level, BlockPos pos) { - level.setBlock( - pos, - Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL, 3), - 3); - } - - private static ColoredWaterApi water() { - return AstraPlusApi.current().flatMap(AstraPlusApi::coloredWater).orElseThrow(); - } - - private static List displays(ServerLevel level, BlockPos pos) { - return level.getEntitiesOfClass( - Display.class, new AABB(pos).inflate(.05), e -> !e.isRemoved()); - } - - private void require(boolean condition, String label) { - if (!condition) throw new AssertionError(label); - passed.add("PASS " + label); - } - - private void finish(MinecraftServer server, String phase) throws Exception { - finished = true; - Files.writeString( - Path.of("verification-result.txt"), - String.join("\n", passed) + "\nPASS " + phase + ": " + passed.size()); - server.halt(false); - } -} diff --git a/src/integrationTest/resources/META-INF/neoforge.mods.toml b/src/integrationTest/resources/META-INF/neoforge.mods.toml deleted file mode 100644 index bbefd73..0000000 --- a/src/integrationTest/resources/META-INF/neoforge.mods.toml +++ /dev/null @@ -1,13 +0,0 @@ -modLoader="javafml" -loaderVersion="[11,)" -license="All Rights Reserved" -[[mods]] -modId="astracauldron_verify" -version="1.0.0" -displayName="AstraCauldron isolated verification" -[[dependencies.astracauldron_verify]] -modId="astracauldron" -type="required" -versionRange="[0.2.0,)" -ordering="AFTER" -side="SERVER" diff --git a/src/integrationTest/run.ps1 b/src/integrationTest/run.ps1 deleted file mode 100644 index 841ef0d..0000000 --- a/src/integrationTest/run.ps1 +++ /dev/null @@ -1,55 +0,0 @@ -param( - [string]$ServerDirectory = 'C:/Users/ScarPC/Documents/NeoForge Server 26.2', - [string]$Java = 'java', - [int]$Port = 25639, - [string]$PlusDirectory = '' -) -$ErrorActionPreference = 'Stop' -if ($Java -eq 'java' -and $env:JAVA_HOME) { $Java = Join-Path $env:JAVA_HOME 'bin/java.exe' } -$repo = (Resolve-Path "$PSScriptRoot/../..").Path -$plus = Join-Path (Split-Path $repo -Parent) 'AstraPlus' -if ($PlusDirectory) { $plus = (Resolve-Path -LiteralPath $PlusDirectory).Path } -$run = Join-Path $repo ('build/verification-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0,6)) -New-Item -ItemType Directory -Path (Join-Path $run 'mods') -Force | Out-Null -$plusVersion = [regex]::Match((Get-Content "$plus/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value -$cauldronVersion = [regex]::Match((Get-Content "$repo/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value -foreach ($jar in @("$plus/build/libs/AstraPlus-$plusVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion.jar", "$repo/build/libs/AstraCauldron-$cauldronVersion-integration-tests.jar")) { - Copy-Item -LiteralPath $jar -Destination (Join-Path $run 'mods') -} -$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/') -$argsLines = Get-Content -LiteralPath "$ServerDirectory/libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt" -$argsText = (@(foreach ($line in $argsLines) { - if ($line -eq '-DlibraryDirectory=libraries') { '"-DlibraryDirectory=' + $serverRoot + '/libraries"' } - elseif ($line.StartsWith('libraries/')) { '"' + $line.Replace('libraries/', "$serverRoot/libraries/") + '"' } - else { $line } -}) -join "`n") -[IO.File]::WriteAllText((Join-Path $run 'server-args.txt'), $argsText, [Text.UTF8Encoding]::new($false)) -[IO.File]::WriteAllText((Join-Path $run 'eula.txt'), 'eula=true') -$properties = @" -server-ip=127.0.0.1 -server-port=$Port -online-mode=false -level-type=minecraft:flat -generator-settings={"layers":[{"block":"minecraft:bedrock","height":1},{"block":"minecraft:dirt","height":2},{"block":"minecraft:grass_block","height":1}],"biome":"minecraft:plains"} -generate-structures=false -spawn-protection=0 -view-distance=2 -simulation-distance=2 -max-tick-time=90000 -use-native-transport=false -motd=AstraCauldron isolated verification -"@ -[IO.File]::WriteAllText((Join-Path $run 'server.properties'), $properties) -Set-Content -LiteralPath "$repo/build/active-verification.txt" -Value $run -Push-Location $run -try { - foreach ($phase in @('gameplay','restart')) { - & $Java '-Xms256M' '-Xmx1G' '-Dastracauldron.isolatedVerification=true' '@server-args.txt' nogui *> "$phase.log" - if ($LASTEXITCODE -ne 0) { throw "Server failed: $run/$phase.log" } - $result = Get-Content -LiteralPath 'verification-result.txt' -Raw - if ($result -match '(?m)^FAIL' -or $result -notmatch "PASS ${phase}:") { throw "Verification failed: $run/verification-result.txt" } - Copy-Item -LiteralPath 'verification-result.txt' -Destination "$phase-result.txt" - Write-Output (($result -split "`n")[-1]) - } -} finally { Pop-Location } -Write-Output "Verified both launches: $run" diff --git a/src/main/java/online/astradev/cauldron/AstraCauldron.java b/src/main/java/online/astradev/cauldron/AstraCauldron.java index d5c8542..a48e4c7 100644 --- a/src/main/java/online/astradev/cauldron/AstraCauldron.java +++ b/src/main/java/online/astradev/cauldron/AstraCauldron.java @@ -1,220 +1,13 @@ package online.astradev.cauldron; -import com.mojang.brigadier.arguments.*; -import com.mojang.brigadier.context.CommandContext; - -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.TriState; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.level.Level; import net.neoforged.api.distmarker.Dist; -import net.neoforged.bus.api.EventPriority; import net.neoforged.fml.common.Mod; -import net.neoforged.fml.loading.FMLPaths; -import net.neoforged.neoforge.common.NeoForge; -import net.neoforged.neoforge.event.RegisterCommandsEvent; -import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; -import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; -import net.neoforged.neoforge.event.level.*; -import net.neoforged.neoforge.event.level.block.BreakBlockEvent; -import net.neoforged.neoforge.event.server.*; -import net.neoforged.neoforge.event.tick.ServerTickEvent; - -import online.astradev.plus.api.AstraPlusApi; - -import org.slf4j.*; +/** + * Legacy mod identity only. Authored starter resources are assembled into AstraPlus; + * the generic mixing capability owns all runtime listeners, persistence and mixins. + */ @Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER) public final class AstraCauldron { - static final Logger LOG = LoggerFactory.getLogger("AstraCauldron"); - private static SoupPots pots; - private static final SoupConfig DEFAULT_CONFIG = new SoupConfig(); - private static LiquidPots liquids; - - public AstraCauldron() { - NeoForge.EVENT_BUS.addListener(this::start); - NeoForge.EVENT_BUS.addListener(this::stop); - NeoForge.EVENT_BUS.addListener(this::tick); - NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::interact); - NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::breakBlock); - NeoForge.EVENT_BUS.addListener(this::explosion); - NeoForge.EVENT_BUS.addListener(this::piston); - NeoForge.EVENT_BUS.addListener(this::unload); - NeoForge.EVENT_BUS.addListener(this::join); - NeoForge.EVENT_BUS.addListener(this::commands); - } - - private void start(ServerStartedEvent event) { - try { - AstraPlusApi.current() - .orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable")); - pots = - new SoupPots( - event.getServer(), - FMLPaths.CONFIGDIR.get().resolve("astracauldron.json")); - liquids = new LiquidPots(event.getServer()); - LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API"); - } catch (Exception e) { - throw new IllegalStateException( - "Cannot initialize AstraCauldron; existing data preserved", e); - } - } - - private void stop(ServerStoppingEvent event) { - if (pots != null) pots.close(); - if (liquids != null) liquids.close(); - pots = null; - liquids = null; - } - - private void tick(ServerTickEvent.Post event) { - if (pots != null) pots.tick(); - if (liquids != null) liquids.tick(); - } - - public static SoupPots pots() { - return pots; - } - - public static SoupConfig config() { - return pots == null ? DEFAULT_CONFIG : pots.config(); - } - - public static LiquidPots liquids() { - return liquids; - } - - public static boolean occupied(Level level, BlockPos pos) { - if (!(level instanceof ServerLevel serverLevel)) return false; - if (pots != null && pots.contains(serverLevel, pos)) return true; - return liquids != null && liquids.contains(serverLevel, pos); - } - - private void interact(PlayerInteractEvent.RightClickBlock event) { - if (pots == null - || event.isCanceled() - || event.getUseBlock() == TriState.FALSE - || event.getUseItem() == TriState.FALSE) return; - if (!(event.getEntity() instanceof ServerPlayer player)) return; - var pos = event.getPos(); - var hand = event.getHand(); - boolean handled = RegisteredRecipes.interact(player, pos, hand); - if (!handled && !pots.contains(player.level(), pos) && liquids != null) - handled = liquids.interact(player, pos, hand); - if (!handled) handled = pots.interact(player, pos, hand); - if (!handled) return; - event.setCanceled(true); - event.setCancellationResult(InteractionResult.SUCCESS); - } - - private void breakBlock(BreakBlockEvent event) { - if (event.isCanceled() || pots == null) return; - if (!(event.getLevel() instanceof ServerLevel level)) return; - boolean removed = pots.breakPot(level, event.getPos()); - if (removed && liquids != null) removed = liquids.breakPot(level, event.getPos()); - if (removed) return; - event.setCanceled(true); - event.setNotifyClient(true); - } - - private void explosion(ExplosionEvent.Detonate event) { - if (pots != null && event.getLevel() instanceof ServerLevel level) - event.getAffectedBlocks().removeIf(pos -> occupied(level, pos)); - } - - private void piston(PistonEvent.Pre event) { - if (pots == null || event.isCanceled() || !(event.getLevel() instanceof ServerLevel level)) - return; - var resolver = event.getStructureHelper(); - if (resolver == null || !resolver.resolve()) return; - boolean movesCauldron = resolver.getToPush().stream().anyMatch(pos -> occupied(level, pos)); - boolean breaksCauldron = - resolver.getToDestroy().stream().anyMatch(pos -> occupied(level, pos)); - if (movesCauldron || breaksCauldron) event.setCanceled(true); - } - - private void unload(ChunkEvent.Unload event) { - if (pots != null && event.getLevel() instanceof ServerLevel level) - pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z()); - } - - private void join(EntityJoinLevelEvent event) { - if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG)) - event.setCanceled(true); - else if (event.getEntity() instanceof ItemEntity item) - Ingredients.normalize(item.getItem()); - } - - private void commands(RegisterCommandsEvent event) { - var command = Commands.literal("cauldron").executes(this::help); - command.then( - Commands.literal("reload") - .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) - .executes(this::reload)); - var saturation = - Commands.argument("saturation", FloatArgumentType.floatArg(0)) - .executes(this::registerIngredient); - var nutrition = - Commands.argument("nutrition", IntegerArgumentType.integer(0)).then(saturation); - var id = Commands.argument("id", StringArgumentType.word()).then(nutrition); - command.then( - Commands.literal("register") - .requires(Commands.hasPermission(Commands.LEVEL_ADMINS)) - .then(id)); - var root = event.getDispatcher().register(command); - event.getDispatcher() - .register(Commands.literal("soups").redirect(root).executes(root.getCommand())); - } - - private int help(CommandContext context) { - var message = - Component.literal( - "Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и" - + " стрелы с эффектом. Еда/зелья + полный котёл воды: 4 ингредиента" - + " супа, Shift+ПКМ — варка, миска — порция."); - context.getSource().sendSuccess(() -> message, false); - return 1; - } - - private int reload(CommandContext context) { - try { - requirePots().reload(); - context.getSource() - .sendSuccess( - () -> Component.literal("AstraCauldron: настройки применены."), true); - return 1; - } catch (Exception error) { - String message = "Ошибка: " + error.getMessage() + ". Прежние настройки сохранены."; - context.getSource().sendFailure(Component.literal(message)); - return 0; - } - } - - private int registerIngredient(CommandContext context) { - try { - String id = StringArgumentType.getString(context, "id"); - var player = context.getSource().getPlayerOrException(); - int nutrition = IntegerArgumentType.getInteger(context, "nutrition"); - float saturation = FloatArgumentType.getFloat(context, "saturation"); - requirePots().register(id, player, nutrition, saturation); - context.getSource() - .sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true); - return 1; - } catch (Exception error) { - context.getSource() - .sendFailure(Component.literal("Ошибка регистрации: " + error.getMessage())); - return 0; - } - } - - private static SoupPots requirePots() { - if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен"); - return pots; - } + public AstraCauldron() {} } diff --git a/src/main/java/online/astradev/cauldron/CauldronAnimation.java b/src/main/java/online/astradev/cauldron/CauldronAnimation.java deleted file mode 100644 index 35fe0f2..0000000 --- a/src/main/java/online/astradev/cauldron/CauldronAnimation.java +++ /dev/null @@ -1,29 +0,0 @@ -package online.astradev.cauldron; - -/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */ -public final class CauldronAnimation { - private CauldronAnimation() {} - - public record Offset(double x, double y, double z) {} - - public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) { - double[] phases = {-3 * Math.PI / 4, -Math.PI / 4, 3 * Math.PI / 4, Math.PI / 4}; - double angle = phases[slot] + (duration > 0 ? elapsed * .1 : 0); - double radius = .23; - double surface = .375 + .1875 * waterLevel; - double bob = Math.sin(tick * .04 + slot) * .004; - return new Offset( - .5 + Math.cos(angle) * radius, surface - .055 + bob, .5 + Math.sin(angle) * radius); - } - - public static double liquidHeight(int servings, int capacity) { - return .25 + .6875 * Math.clamp((double) servings / capacity, 0, 1); - } - - public static int waterLevel(int servings, int capacity) { - double height = liquidHeight(servings, capacity); - int level = 0; - for (int i = 1; i <= 3; i++) if (.375 + .1875 * i <= height + .00001) level = i; - return level; - } -} diff --git a/src/main/java/online/astradev/cauldron/CauldronHeat.java b/src/main/java/online/astradev/cauldron/CauldronHeat.java deleted file mode 100644 index c8bd173..0000000 --- a/src/main/java/online/astradev/cauldron/CauldronHeat.java +++ /dev/null @@ -1,59 +0,0 @@ -package online.astradev.cauldron; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.CampfireBlock; -import net.minecraft.world.level.block.LayeredCauldronBlock; - -/** Uses the existing campfire ticker; no scanning worlds or spawning persistent effects. */ -public final class CauldronHeat { - private CauldronHeat() {} - - public static boolean heated(LevelReader level, BlockPos cauldron) { - var below = cauldron.below(); - if (!level.hasChunkAt(below)) return false; - var state = level.getBlockState(below); - return state.getBlock() instanceof CampfireBlock && state.getValue(CampfireBlock.LIT); - } - - public static void tick(ServerLevel level, BlockPos campfire) { - if (!AstraCauldron.config().particles) return; - var pos = campfire.above(); - if ((level.getGameTime() + pos.asLong()) % 10 != 0 || !heated(level, pos)) return; - var state = level.getBlockState(pos); - double surface; - if (state.is(Blocks.WATER_CAULDRON)) - surface = .375 + .1875 * state.getValue(LayeredCauldronBlock.LEVEL); - else { - var pot = AstraCauldron.pots() == null ? null : AstraCauldron.pots().get(level, pos); - if (!state.is(Blocks.CAULDRON) - || pot == null - || pot.soup().isEmpty() - || pot.brewTicks() > 0) return; - surface = CauldronAnimation.liquidHeight(pot.servings(), pot.capacity()); - } - level.sendParticles( - ParticleTypes.BUBBLE_POP, - pos.getX() + .5, - pos.getY() + surface + .01, - pos.getZ() + .5, - 4, - .18, - .015, - .18, - 0); - level.sendParticles( - ParticleTypes.SPLASH, - pos.getX() + .5, - pos.getY() + surface + .02, - pos.getZ() + .5, - 2, - .16, - 0, - .16, - 0); - } -} diff --git a/src/main/java/online/astradev/cauldron/CombinationRules.java b/src/main/java/online/astradev/cauldron/CombinationRules.java deleted file mode 100644 index 99cfd9b..0000000 --- a/src/main/java/online/astradev/cauldron/CombinationRules.java +++ /dev/null @@ -1,42 +0,0 @@ -package online.astradev.cauldron; - -import java.util.List; -import java.util.Locale; -import java.util.Set; - -public final class CombinationRules { - private CombinationRules() {} - - public static boolean matches(Set tags, String selector) { - return selector.equals("*") || tags.contains(selector.toLowerCase(Locale.ROOT)); - } - - public static String rejection( - List> ingredients, List blocked, List> pairs) { - return rejection(ingredients, blocked, pairs, 4); - } - - public static String rejection( - List> ingredients, - List blocked, - List> pairs, - int count) { - if (ingredients.size() != count) return "Нужно ровно " + count + " ингредиента."; - for (Set tags : ingredients) { - for (String selector : blocked) { - if (matches(tags, selector)) return "Запрещён ингредиент: " + selector; - } - } - for (List pair : pairs) { - for (int i = 0; i < ingredients.size(); i++) { - if (!matches(ingredients.get(i), pair.get(0))) continue; - for (int j = 0; j < ingredients.size(); j++) { - if (i != j && matches(ingredients.get(j), pair.get(1))) { - return "Несовместимые ингредиенты: " + String.join(" + ", pair); - } - } - } - } - return null; - } -} diff --git a/src/main/java/online/astradev/cauldron/IngredientColors.java b/src/main/java/online/astradev/cauldron/IngredientColors.java deleted file mode 100644 index b9f5534..0000000 --- a/src/main/java/online/astradev/cauldron/IngredientColors.java +++ /dev/null @@ -1,38 +0,0 @@ -package online.astradev.cauldron; - -final class IngredientColors { - private IngredientColors() {} - - static int food(String material, int fallback) { - int rgb = - switch (material) { - case "spider_eye", "fermented_spider_eye" -> 0xB52B38; - case "golden_apple", "enchanted_golden_apple", "golden_carrot" -> 0xF2C94C; - case "apple", "sweet_berries" -> 0xC73735; - case "beetroot", "beetroot_soup" -> 0xA52B4B; - case "carrot", "pumpkin_pie", "glow_berries" -> 0xE99032; - case "dried_kelp" -> 0x47733B; - case "poisonous_potato" -> 0x91A340; - case "melon_slice" -> 0xD94E58; - case "chorus_fruit" -> 0x9C6C9D; - case "beef", "mutton", "porkchop", "rabbit" -> 0xC76B70; - case "chicken" -> 0xE2A6A0; - case "cooked_beef", "cooked_mutton" -> 0x815033; - case "cooked_porkchop", "cooked_rabbit", "cooked_chicken" -> 0xBA8551; - case "salmon", "cooked_salmon", "tropical_fish" -> 0xD98262; - case "cod" -> 0xB0A07B; - case "cooked_cod" -> 0xC4B486; - case "pufferfish" -> 0xD3B54D; - case "bread", "cookie", "baked_potato" -> 0xBA873F; - case "potato" -> 0xC7A76B; - case "rotten_flesh" -> 0x8F6540; - case "honey_bottle" -> 0xE9AC32; - case "cake" -> 0xE8CCBA; - case "mushroom_stew" -> 0xA37A53; - case "rabbit_stew" -> 0xAC8854; - case "suspicious_stew" -> 0x867743; - default -> fallback; - }; - return rgb; - } -} diff --git a/src/main/java/online/astradev/cauldron/Ingredients.java b/src/main/java/online/astradev/cauldron/Ingredients.java deleted file mode 100644 index cfae5cc..0000000 --- a/src/main/java/online/astradev/cauldron/Ingredients.java +++ /dev/null @@ -1,306 +0,0 @@ -package online.astradev.cauldron; - -import net.minecraft.ChatFormatting; -import net.minecraft.core.HolderLookup; -import net.minecraft.core.component.DataComponents; -import net.minecraft.core.registries.BuiltInRegistries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.Identifier; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.food.FoodProperties; -import net.minecraft.world.item.*; -import net.minecraft.world.item.component.*; -import net.minecraft.world.item.consume_effects.*; - -import online.astradev.plus.api.AstraPlusApi; - -import java.util.*; - -public final class Ingredients { - public record Ingredient( - int nutrition, - float saturation, - List effects, - Set tags, - int color) {} - - private record Custom( - String id, - ItemStack sample, - SoupConfig.Custom definition, - List effects) {} - - private final SoupConfig config; - private final HolderLookup.Provider registries; - private final List custom = new ArrayList<>(); - - public Ingredients(SoupConfig config, HolderLookup.Provider registries) { - config.validate(); - this.config = config; - this.registries = registries; - for (var entry : config.customIngredients.entrySet()) { - var c = entry.getValue(); - ItemStack sample = - c.item == null ? ItemStack.EMPTY : SoupFiles.decode(c.item, registries); - if (c.item != null && (sample.isEmpty() || sample.getCount() != 1)) - throw new IllegalArgumentException("Некорректный образец " + entry.getKey()); - normalize(sample); - List effects = new ArrayList<>(); - for (var e : c.effects) { - var type = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(e.type)).orElseThrow(); - effects.add(new MobEffectInstance(type, e.duration, e.amplifier)); - } - custom.add(new Custom(entry.getKey(), sample, c, List.copyOf(effects))); - } - } - - public Ingredient read(ItemStack stack) { - if (stack.isEmpty()) return null; - var plus = AstraPlusApi.current().flatMap(api -> api.find(stack)); - String plusId = plus.map(value -> value.id().toString()).orElse(null); - Custom match = findCustom(stack, plusId); - var food = stack.get(DataComponents.FOOD); - boolean potion = - stack.is(Items.POTION) - || stack.is(Items.SPLASH_POTION) - || stack.is(Items.LINGERING_POTION); - boolean cake = stack.is(Items.CAKE); - if (food == null && !potion && !cake && match == null) return null; - int nutrition = 0; - float saturation = 0; - if (food != null) { - nutrition = food.nutrition(); - saturation = food.saturation(); - } else if (cake) { - nutrition = 14; - saturation = 2.8f; - } - var effects = new ArrayList(); - var consumable = stack.get(DataComponents.CONSUMABLE); - if (consumable != null) effects.addAll(consumable.onConsumeEffects()); - String material = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath(); - int color = IngredientColors.food(material, SoupConfig.rgb(config.defaultColor)); - if (isCombined(stack)) color = color(stack); - var contents = stack.get(DataComponents.POTION_CONTENTS); - if (potion && contents != null) { - List potionEffects = new ArrayList<>(); - contents.forEachEffect( - potionEffects::add, - stack.transmuteCopy(Items.POTION, 1) - .getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f)); - if (!potionEffects.isEmpty()) - effects.add(new ApplyStatusEffectsConsumeEffect(potionEffects)); - color = contents.getColor() & 0xFFFFFF; - } - var stew = stack.get(DataComponents.SUSPICIOUS_STEW_EFFECTS); - if (stew != null && !stew.effects().isEmpty()) - effects.add( - new ApplyStatusEffectsConsumeEffect( - stew.effects().stream() - .map(SuspiciousStewEffects.Entry::createEffectInstance) - .toList())); - Set tags = new HashSet<>(); - tags.add("material:" + material); - if (isCombined(stack)) tags.add("soup:combined"); - plus.ifPresent(p -> tags.add("astraplus:" + p.id())); - if (match != null) { - nutrition = match.definition.nutrition; - saturation = match.definition.saturation; - if (match.definition.color != null) color = SoupConfig.rgb(match.definition.color); - if (!match.effects.isEmpty()) - effects.add(new ApplyStatusEffectsConsumeEffect(match.effects)); - tags.add("custom:" + match.id); - } - for (var effect : effects) - if (effect instanceof ApplyStatusEffectsConsumeEffect apply) - for (var e : apply.effects()) - tags.add( - "effect:" + BuiltInRegistries.MOB_EFFECT.getKey(e.getEffect().value())); - return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color); - } - - private Custom findCustom(ItemStack stack, String plusId) { - ItemStack normalized = null; - for (var ingredient : custom) { - String expected = ingredient.definition.astraPlusId; - if (expected != null) { - if (expected.equals(plusId)) return ingredient; - continue; - } - if (normalized == null) normalized = normalizedCopy(stack); - if (ItemStack.isSameItemSameComponents(ingredient.sample, normalized)) - return ingredient; - } - return null; - } - - public String rejection(List items) { - var data = items.stream().map(this::read).toList(); - if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент."; - String error = - CombinationRules.rejection( - data.stream().map(Ingredient::tags).toList(), - config.blockedIngredients, - config.incompatible, - config.ingredientCount); - if (error != null) return error; - long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum(); - double saturation = data.stream().mapToDouble(Ingredient::saturation).sum(); - if (nutrition < 0 - || nutrition > config.maxNutrition - || !Double.isFinite(saturation) - || saturation < 0 - || saturation > config.maxSaturation) return "Превышен лимит питания супа."; - if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) - return "В супе слишком много эффектов."; - return null; - } - - public ItemStack brew(List items) { - String error = rejection(items); - if (error != null) throw new IllegalArgumentException(error); - var data = - items.stream() - .map(Ingredients::normalizedCopy) - .sorted( - Comparator.comparing( - s -> SoupFiles.encode(s, registries).toString())) - .map(this::read) - .toList(); - int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum(); - float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum(); - List effects = - config.inheritEffects - ? data.stream().flatMap(i -> i.effects.stream()).toList() - : List.of(); - int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray()); - var soup = new ItemStack(Items.MUSHROOM_STEW); - CustomData.update( - DataComponents.CUSTOM_DATA, - soup, - tag -> { - tag.putBoolean("astracauldron:combined_soup", true); - tag.putInt("astracauldron:soup_color", rgb); - }); - soup.set( - DataComponents.CUSTOM_NAME, - Component.literal(config.soupName) - .withStyle(s -> s.withColor(rgb).withItalic(false))); - soup.set( - DataComponents.FOOD, - new FoodProperties(nutrition, saturation, config.alwaysEdible)); - var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE)); - soup.set( - DataComponents.CONSUMABLE, - new Consumable( - config.consumeSeconds, - base.animation(), - base.sound(), - config.particles && base.hasConsumeParticles(), - effects)); - if (config.returnBowl) - soup.set( - DataComponents.USE_REMAINDER, - new UseRemainder( - ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL)))); - else soup.remove(DataComponents.USE_REMAINDER); - normalize(soup); - return soup; - } - - static int averageColor(int[] colors) { - int r = 0, g = 0, b = 0; - for (int c : colors) { - r += (c >> 16) & 255; - g += (c >> 8) & 255; - b += c & 255; - } - return ((r / colors.length) << 16) | ((g / colors.length) << 8) | (b / colors.length); - } - - public static boolean isCombined(ItemStack stack) { - return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY) - .copyTag() - .getBooleanOr("astracauldron:combined_soup", false); - } - - public static int color(ItemStack stack) { - return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY) - .copyTag() - .getIntOr("astracauldron:soup_color", 0xB77A36) - & 0xFFFFFF; - } - - static ItemStack normalizedCopy(ItemStack stack) { - var copy = stack.copyWithCount(1); - normalize(copy); - return copy; - } - - public static void normalize(ItemStack stack) { - if (!(stack.is(Items.MUSHROOM_STEW) - || stack.is(Items.RABBIT_STEW) - || stack.is(Items.BEETROOT_SOUP) - || stack.is(Items.SUSPICIOUS_STEW))) return; - if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups) - stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize); - if (!isCombined(stack)) return; - stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup")); - var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY); - var colors = new ArrayList<>(data.colors()); - if (colors.isEmpty()) colors.add(color(stack)); - else colors.set(0, color(stack)); - stack.set( - DataComponents.CUSTOM_MODEL_DATA, - new CustomModelData(data.floats(), data.flags(), data.strings(), colors)); - var food = stack.get(DataComponents.FOOD); - var consumable = stack.get(DataComponents.CONSUMABLE); - if (food != null && consumable != null) - stack.set(DataComponents.LORE, new ItemLore(lore(food, consumable.onConsumeEffects()))); - } - - private static List lore(FoodProperties food, List effects) { - var lines = new ArrayList(); - lines.add(line("Голод: +" + food.nutrition(), ChatFormatting.YELLOW)); - lines.add( - line( - String.format(Locale.ROOT, "Насыщение: +%.1f", food.saturation()), - ChatFormatting.GOLD)); - for (var effect : effects) { - if (effect instanceof ApplyStatusEffectsConsumeEffect apply) { - for (var instance : apply.effects()) - lines.add(effectLine(instance, apply.probability())); - continue; - } - String description = - switch (effect) { - case TeleportRandomlyConsumeEffect ignored -> "Случайная телепортация"; - case ClearAllStatusEffectsConsumeEffect ignored -> "Снятие всех эффектов"; - case RemoveStatusEffectsConsumeEffect ignored -> "Снятие эффектов"; - default -> "Звук при употреблении"; - }; - lines.add(line(description, ChatFormatting.GRAY)); - } - return lines; - } - - private static Component effectLine(MobEffectInstance effect, float probability) { - String duration = "∞"; - if (!effect.isInfiniteDuration()) - duration = - String.format( - Locale.ROOT, - "%d:%02d", - effect.getDuration() / 1200, - effect.getDuration() / 20 % 60); - String details = " " + SoupText.roman(effect.getAmplifier() + 1) + " (" + duration + ")"; - if (probability < 1) details += " " + Math.round(probability * 100) + "%"; - return Component.translatable(effect.getDescriptionId()) - .append(details) - .withStyle(style -> style.withColor(ChatFormatting.AQUA).withItalic(false)); - } - - private static Component line(String text, ChatFormatting color) { - return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false)); - } -} diff --git a/src/main/java/online/astradev/cauldron/LiquidPots.java b/src/main/java/online/astradev/cauldron/LiquidPots.java deleted file mode 100644 index d239ae8..0000000 --- a/src/main/java/online/astradev/cauldron/LiquidPots.java +++ /dev/null @@ -1,444 +0,0 @@ -package online.astradev.cauldron; - -import com.google.gson.*; - -import net.minecraft.ChatFormatting; -import net.minecraft.core.BlockPos; -import net.minecraft.core.registries.Registries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.*; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.*; -import net.minecraft.sounds.*; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.item.*; -import net.minecraft.world.item.alchemy.PotionContents; -import net.minecraft.world.item.alchemy.Potions; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.storage.LevelResource; - -import online.astradev.plus.api.*; -import online.astradev.plus.api.AstraPlusApi; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; - -/** - * Persistent dyed water and potion storage; all item transformations and rendering use AstraPlus - * API. - */ -public final class LiquidPots implements AutoCloseable { - private record Position(String dimension, BlockPos pos) { - static Position at(ServerLevel level, BlockPos pos) { - return new Position(level.dimension().identifier().toString(), pos.immutable()); - } - } - - public record Liquid(int levels, int rgb, CauldronApi.Potion potion) { - public Liquid { - if (levels < 1 || levels > 3 || rgb < 0 || rgb > 0xFFFFFF) - throw new IllegalArgumentException("Invalid liquid"); - } - - Liquid withLevels(int value) { - return new Liquid(value, rgb, potion); - } - - public String source() { - if (potion == null) return "dyed_water"; - return potion.contents() - .potion() - .flatMap(holder -> holder.unwrapKey()) - .map(key -> key.identifier().toString()) - .orElse("astracauldron:custom_potion"); - } - } - - private static final Identifier OWNER = Identifier.parse("astracauldron:liquids"); - private final MinecraftServer server; - private final CauldronApi api; - private final Path file; - private final Map liquids = new LinkedHashMap<>(); - - public LiquidPots(MinecraftServer server) throws IOException { - this.server = server; - api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow(); - file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json"); - if (Files.exists(file)) load(); - } - - private void load() throws IOException { - var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject(); - if (json.get("version").getAsInt() != 1) { - throw new IllegalArgumentException("Unknown liquid data version"); - } - for (var entry : json.getAsJsonArray("cauldrons")) { - var record = entry.getAsJsonObject(); - String dimension = Identifier.parse(record.get("dimension").getAsString()).toString(); - int x = record.get("x").getAsInt(); - int y = record.get("y").getAsInt(); - int z = record.get("z").getAsInt(); - var position = new Position(dimension, new BlockPos(x, y, z)); - CauldronApi.Potion potion = null; - if (record.has("potion")) { - ItemStack bottle = SoupFiles.decode(record.get("potion"), server.registryAccess()); - potion = api.potion(bottle).orElseThrow(); - } - int levels = record.get("levels").getAsInt(); - int color = record.get("rgb").getAsInt(); - var liquid = new Liquid(levels, color, potion); - if (liquids.putIfAbsent(position, liquid) != null) { - throw new IllegalArgumentException("Duplicate liquid cauldron"); - } - } - } - - public Liquid get(ServerLevel level, BlockPos pos) { - return liquids.get(Position.at(level, pos)); - } - - public boolean contains(ServerLevel level, BlockPos pos) { - return get(level, pos) != null; - } - - public boolean applyRecipe(ServerLevel level, BlockPos blockPos, int remaining, Integer color) { - var pos = Position.at(level, blockPos); - var previous = liquids.get(pos); - if (remaining < 0 || remaining > 3) - throw new IllegalArgumentException("Invalid remaining liquid"); - Liquid next = null; - if (remaining > 0) { - int rgb = color == null ? Objects.requireNonNull(previous).rgb : color; - next = new Liquid(remaining, rgb, previous == null ? null : previous.potion); - } - if (!change(pos, next)) return false; - level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3); - if (next != null) setVisual(level, pos, next); - return true; - } - - private boolean change(Position pos, Liquid next) { - var old = liquids.get(pos); - if (next == null) liquids.remove(pos); - else liquids.put(pos, next); - try { - save(); - if (next == null) removeSurface(pos); - return true; - } catch (Exception e) { - if (old == null) liquids.remove(pos); - else liquids.put(pos, old); - AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e); - return false; - } - } - - private void save() throws IOException { - var root = new JsonObject(); - root.addProperty("version", 1); - var array = new JsonArray(); - root.add("cauldrons", array); - for (var entry : liquids.entrySet()) { - var p = entry.getKey(); - var liquid = entry.getValue(); - var c = new JsonObject(); - c.addProperty("dimension", p.dimension); - c.addProperty("x", p.pos.getX()); - c.addProperty("y", p.pos.getY()); - c.addProperty("z", p.pos.getZ()); - c.addProperty("levels", liquid.levels); - c.addProperty("rgb", liquid.rgb); - if (liquid.potion != null) - c.add( - "potion", - SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess())); - array.add(c); - } - SoupFiles.write(file, root); - } - - public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) { - if (player.isSpectator()) return false; - var level = player.level(); - var pos = Position.at(level, blockPos); - var liquid = liquids.get(pos); - if (hand != InteractionHand.MAIN_HAND) return liquid != null; - var state = level.getBlockState(blockPos); - if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false; - if (liquid == null) return fillVanilla(player, pos); - if (liquid.potion == null) return useDyedWater(player, pos, liquid); - return usePotion(player, pos, liquid); - } - - private boolean fillVanilla(ServerPlayer player, Position pos) { - var level = player.level(); - var blockPos = pos.pos; - var held = player.getMainHandItem(); - var state = level.getBlockState(blockPos); - var potion = api.potion(held); - if (potion.isPresent() && plainWater(potion.get())) { - int current = - state.is(Blocks.WATER_CAULDRON) - ? state.getValue(LayeredCauldronBlock.LEVEL) - : 0; - if (current < 3) { - level.setBlock( - blockPos, - Blocks.WATER_CAULDRON - .defaultBlockState() - .setValue(LayeredCauldronBlock.LEVEL, current + 1), - 3); - consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); - } - return true; - } - var dye = api.mixDye(OptionalInt.empty(), held); - if (AstraCauldron.config().dyeWater && state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) { - var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null); - if (!change(pos, next)) { - error(player); - return true; - } - held.consume(1, player); - setVisual(level, pos, next); - say( - player, - "Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно" - + " смешивать."); - return true; - } - if (AstraCauldron.config().storePotions - && state.is(Blocks.CAULDRON) - && potion.isPresent()) { - var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get()); - if (!change(pos, next)) { - error(player); - return true; - } - consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); - setVisual(level, pos, next); - say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать."); - return true; - } - return false; - } - - private boolean useDyedWater(ServerPlayer player, Position pos, Liquid liquid) { - var level = player.level(); - var blockPos = pos.pos; - var held = player.getMainHandItem(); - var dye = api.mixDye(OptionalInt.of(liquid.rgb), held); - if (AstraCauldron.config().dyeWater && dye.isPresent()) { - var next = new Liquid(liquid.levels, dye.getAsInt(), null); - if (!change(pos, next)) { - error(player); - return true; - } - held.consume(1, player); - setVisual(level, pos, next); - return true; - } - var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels); - if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) { - var batch = blocks.get(); - var result = batch.result(); - if (!decrease(level, pos, liquid, batch.levelsUsed())) { - error(player); - return true; - } - int count = result.getCount(); - consumeAndGive(player, count, result); - sound(level, blockPos); - say(player, "Окрашено предметов: " + count + "."); - return true; - } - var armor = api.dyeArmor(held, liquid.rgb); - if (AstraCauldron.config().dyeArmor && armor.isPresent()) { - if (!decrease(level, pos, liquid, 1)) { - error(player); - return true; - } - // Transform the equipped item, including Creative, preserving - // enchantments/damage/name. - if (held.getCount() == 1) player.setItemInHand(InteractionHand.MAIN_HAND, armor.get()); - else consumeAndGive(player, 1, armor.get()); - sound(level, blockPos); - say(player, "Броня окрашена. Израсходован один уровень воды."); - return true; - } - if (held.is(Items.WATER_BUCKET)) { - if (!change(pos, null)) { - error(player); - return true; - } - level.setBlock( - blockPos, - Blocks.WATER_CAULDRON - .defaultBlockState() - .setValue(LayeredCauldronBlock.LEVEL, 3), - 3); - consumeAndGive(player, 1, new ItemStack(Items.BUCKET)); - return true; - } - if (held.is(Items.BUCKET) && liquid.levels == 3) { - if (!decrease(level, pos, liquid, 3)) { - error(player); - return true; - } - consumeAndGive(player, 1, new ItemStack(Items.WATER_BUCKET)); - return true; - } - if (held.is(Items.GLASS_BOTTLE)) { - if (!decrease(level, pos, liquid, 1)) { - error(player); - return true; - } - var water = new CauldronApi.Potion(new PotionContents(Potions.WATER), 1); - consumeAndGive(player, 1, api.bottle(water)); - return true; - } - say(player, "Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); - return true; - } - - private boolean usePotion(ServerPlayer player, Position pos, Liquid liquid) { - var level = player.level(); - var blockPos = pos.pos; - var held = player.getMainHandItem(); - var potion = api.potion(held); - if (potion.isPresent()) { - if (!AstraCauldron.config().storePotions) return true; - if (!potion.get().equals(liquid.potion)) { - say(player, "В котле другое зелье. Сначала заберите его бутылочками."); - return true; - } - if (liquid.levels == 3) { - say(player, "Котёл уже полон."); - return true; - } - var next = liquid.withLevels(liquid.levels + 1); - if (!change(pos, next)) { - error(player); - return true; - } - consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); - setVisual(level, pos, next); - return true; - } - if (held.is(Items.GLASS_BOTTLE)) { - var bottle = api.bottle(liquid.potion); - if (!decrease(level, pos, liquid, 1)) { - error(player); - return true; - } - consumeAndGive(player, 1, bottle); - sound(level, blockPos); - return true; - } - var arrows = api.tipArrows(held, liquid.potion, liquid.levels); - if (AstraCauldron.config().tipArrows && arrows.isPresent()) { - var batch = arrows.get(); - var result = batch.result(); - if (!decrease(level, pos, liquid, batch.levelsUsed())) { - error(player); - return true; - } - int count = result.getCount(); - consumeAndGive(player, count, result); - sound(level, blockPos); - say(player, "Обработано стрел: " + count + "."); - return true; - } - say( - player, - "Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку."); - return true; - } - - private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) { - int remaining = old.levels - used; - var next = remaining == 0 ? null : old.withLevels(remaining); - if (!change(pos, next)) return false; - level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3); - if (next != null) setVisual(level, pos, next); - return true; - } - - private static boolean plainWater(CauldronApi.Potion potion) { - var contents = potion.contents(); - return contents.is(Potions.WATER) - && contents.customColor().isEmpty() - && contents.customName().isEmpty() - && potion.durationScale() == 1f; - } - - public boolean breakPot(ServerLevel level, BlockPos pos) { - var position = Position.at(level, pos); - return !liquids.containsKey(position) || change(position, null); - } - - public void tick() { - for (var entry : new ArrayList<>(liquids.entrySet())) { - var pos = entry.getKey(); - var level = level(pos); - if (level == null || !level.hasChunkAt(pos.pos)) continue; - if (!level.getBlockState(pos.pos).is(Blocks.CAULDRON)) { - change(pos, null); - continue; - } - surface(level, pos, entry.getValue()); - } - } - - private void setVisual(ServerLevel level, Position pos, Liquid liquid) { - level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3); - surface(level, pos, liquid); - } - - private void surface(ServerLevel level, Position pos, Liquid liquid) { - float height = 0.375f + 0.1875f * liquid.levels; - var surface = new ColoredWaterApi.Surface(OWNER, liquid.rgb, height); - api.water().show(level, pos.pos, surface); - } - - private ServerLevel level(Position pos) { - return server.getLevel( - ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension))); - } - - private void removeSurface(Position pos) { - var level = level(pos); - if (level != null) api.water().remove(level, pos.pos, OWNER); - } - - @Override - public void close() { - api.water().removeAll(OWNER); - } - - private static void consumeAndGive(ServerPlayer player, int count, ItemStack result) { - player.getMainHandItem().consume(count, player); - AstraPlusApi.give(player, result); - } - - private static void sound(ServerLevel level, BlockPos pos) { - var config = AstraCauldron.config(); - if (config.sounds) - level.playSound( - null, pos, SoundEvents.BOTTLE_FILL, SoundSource.BLOCKS, config.soundVolume, 1); - } - - private static void say(ServerPlayer player, String text) { - var config = AstraCauldron.config(); - if (config.messages) - player.sendSystemMessage( - Component.literal(config.messageOverrides.getOrDefault(text, text)) - .withStyle(ChatFormatting.GOLD), - true); - } - - private static void error(ServerPlayer player) { - say(player, "Не удалось сохранить котёл. Действие отменено."); - } -} diff --git a/src/main/java/online/astradev/cauldron/RegisteredRecipes.java b/src/main/java/online/astradev/cauldron/RegisteredRecipes.java deleted file mode 100644 index d053ad4..0000000 --- a/src/main/java/online/astradev/cauldron/RegisteredRecipes.java +++ /dev/null @@ -1,79 +0,0 @@ -package online.astradev.cauldron; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.CampfireBlock; -import net.minecraft.world.level.block.LayeredCauldronBlock; -import net.neoforged.neoforge.common.NeoForge; - -import online.astradev.plus.api.AstraPlusApi; -import online.astradev.plus.api.CauldronRecipeEvent; - -/** Java and editor recipes use the same matching and transactional liquid consumption. */ -public final class RegisteredRecipes { - private RegisteredRecipes() {} - - public static String heat(ServerLevel level, BlockPos pos) { - var below = level.getBlockState(pos.below()); - if (!below.hasProperty(CampfireBlock.LIT) || !below.getValue(CampfireBlock.LIT)) - return "none"; - if (below.is(Blocks.SOUL_CAMPFIRE)) return "soul_campfire"; - if (below.is(Blocks.CAMPFIRE)) return "campfire"; - return "none"; - } - - public static boolean interact(ServerPlayer player, BlockPos pos, InteractionHand hand) { - var level = player.level(); - if (AstraCauldron.pots().contains(level, pos) - || player.isSpectator() - || !player.mayInteract(level, pos)) return false; - var state = level.getBlockState(pos); - var saved = AstraCauldron.liquids().get(level, pos); - if (saved != null && !state.is(Blocks.CAULDRON)) return false; - String source; - int fill; - if (saved != null) { - source = saved.source(); - fill = saved.levels(); - } else { - if (state.is(Blocks.CAULDRON)) source = "empty"; - else if (state.is(Blocks.WATER_CAULDRON)) source = "water"; - else if (state.is(Blocks.LAVA_CAULDRON)) source = "lava"; - else if (state.is(Blocks.POWDER_SNOW_CAULDRON)) source = "powder_snow"; - else return false; - fill = source.equals("empty") ? 0 : 3; - if (state.hasProperty(LayeredCauldronBlock.LEVEL)) - fill = state.getValue(LayeredCauldronBlock.LEVEL); - } - var request = - NeoForge.EVENT_BUS.post( - new CauldronRecipeEvent( - player.getItemInHand(hand), source, fill, heat(level, pos))); - ItemStack output = request.output(); - if (output.isEmpty()) return false; - int remaining = fill - request.liquidCost(); - if (saved != null || request.color() != null) { - if (!AstraCauldron.liquids().applyRecipe(level, pos, remaining, request.color())) - return true; - } else if (request.liquidCost() > 0) { - var next = - remaining == 0 - ? Blocks.CAULDRON.defaultBlockState() - : state.setValue(LayeredCauldronBlock.LEVEL, remaining); - if (!level.setBlock(pos, next, 3)) return true; - } - ItemStack held = player.getItemInHand(hand); - held.consume(request.inputCount(), player); - if (held.isEmpty()) player.setItemInHand(hand, output); - else AstraPlusApi.give(player, output); - level.playSound(null, pos, SoundEvents.BUCKET_EMPTY, SoundSource.BLOCKS, 0.5F, 1); - player.containerMenu.broadcastChanges(); - return true; - } -} diff --git a/src/main/java/online/astradev/cauldron/SoupConfig.java b/src/main/java/online/astradev/cauldron/SoupConfig.java deleted file mode 100644 index c0d775d..0000000 --- a/src/main/java/online/astradev/cauldron/SoupConfig.java +++ /dev/null @@ -1,147 +0,0 @@ -package online.astradev.cauldron; - -import com.google.gson.*; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; - -public final class SoupConfig { - public boolean soupsEnabled = true; - public boolean dyeWater = true; - public boolean dyeArmor = true; - public boolean dyeBlocks = true; - public boolean storePotions = true; - public boolean tipArrows = true; - public boolean requireHeat = true; - public boolean particles = true; - public boolean ingredientDisplays = true; - public boolean sounds = true; - public float soundVolume = .8f; - public boolean messages = true; - public int ingredientCount = 4; - public boolean inheritEffects = true; - public boolean alwaysEdible = true; - public float consumeSeconds = 1.6f; - public boolean returnBowl = true; - public int soupStackSize = 16; - public boolean normalizeVanillaSoups = true; - public Map messageOverrides = new LinkedHashMap<>(); - public int servingsPerBrew = 4; - public boolean requireFullWater = true; - public double brewSeconds = 4; - public String soupName = "Комбинированный суп"; - public String defaultColor = "#B77A36"; - public int maxNutrition = 1000; - public float maxSaturation = 1000; - public List blockedIngredients = new ArrayList<>(); - public List> incompatible = new ArrayList<>(); - public Map customIngredients = new LinkedHashMap<>(); - - public static final class Custom { - public JsonElement item; - public String astraPlusId; - public int nutrition; - public float saturation; - public String color; - public List effects = new ArrayList<>(); - } - - public static final class Effect { - public String type; - public int duration; - public int amplifier; - } - - Custom updateIngredient(String id, int nutrition, float saturation) { - var ingredient = customIngredients.computeIfAbsent(id, ignored -> new Custom()); - ingredient.nutrition = nutrition; - ingredient.saturation = saturation; - return ingredient; - } - - public static SoupConfig load(Path file) throws IOException { - SoupConfig config = - Files.exists(file) - ? SoupFiles.JSON.fromJson(Files.readString(file), SoupConfig.class) - : new SoupConfig(); - if (config == null) throw new IllegalArgumentException("Пустая конфигурация"); - config.validate(); - if (!Files.exists(file)) SoupFiles.write(file, SoupFiles.JSON.toJsonTree(config)); - return config; - } - - public void validate() { - if (ingredientCount < 1 - || ingredientCount > 4 - || soupStackSize < 1 - || soupStackSize > 64 - || !Float.isFinite(consumeSeconds) - || consumeSeconds < .05 - || consumeSeconds > 60) - throw new IllegalArgumentException("Invalid ingredients/consumption settings"); - if (!Float.isFinite(soundVolume) - || soundVolume < 0 - || soundVolume > 4 - || messageOverrides == null - || messageOverrides.containsValue(null)) - throw new IllegalArgumentException("Invalid sound/messages"); - if (servingsPerBrew < 1 - || servingsPerBrew > 16 - || !Double.isFinite(brewSeconds) - || brewSeconds < .5 - || brewSeconds > 60 - || maxNutrition < 0 - || !Float.isFinite(maxSaturation) - || maxSaturation < 0 - || soupName == null - || soupName.isBlank()) - throw new IllegalArgumentException("Некорректные настройки варки/питания"); - rgb(defaultColor); - if (blockedIngredients == null || incompatible == null || customIngredients == null) - throw new IllegalArgumentException("Списки настроек не могут быть null"); - blockedIngredients.forEach(SoupConfig::selector); - for (var pair : incompatible) { - if (pair == null || pair.size() != 2) - throw new IllegalArgumentException("В incompatible нужны пары"); - pair.forEach(SoupConfig::selector); - } - for (var entry : customIngredients.entrySet()) { - var c = entry.getValue(); - if (!entry.getKey().matches("[a-z0-9_-]+") - || c == null - || (c.item == null) == (c.astraPlusId == null) - || c.nutrition < 0 - || c.nutrition > maxNutrition - || !Float.isFinite(c.saturation) - || c.saturation < 0 - || c.saturation > maxSaturation - || c.effects == null) - throw new IllegalArgumentException("Некорректный ингредиент " + entry.getKey()); - if (c.astraPlusId != null && !c.astraPlusId.matches("[a-z0-9_.-]+:[a-z0-9/._-]+")) - throw new IllegalArgumentException("Некорректный AstraPlus ID"); - if (c.color != null) rgb(c.color); - for (var e : c.effects) - if (e == null - || e.type == null - || e.duration < -1 - || e.duration == 0 - || e.amplifier < 0 - || e.amplifier > 255) - throw new IllegalArgumentException("Некорректный эффект"); - } - } - - private static void selector(String s) { - if (s == null - || !s.toLowerCase(Locale.ROOT) - .matches("\\*|(?:material|effect|custom|astraplus|soup):[a-z0-9_:./-]+")) - throw new IllegalArgumentException("Неизвестный селектор: " + s); - } - - static int rgb(String s) { - if (s == null || !s.matches("#[0-9a-fA-F]{6}")) - throw new IllegalArgumentException("Цвет: #RRGGBB"); - return Integer.parseInt(s.substring(1), 16); - } -} diff --git a/src/main/java/online/astradev/cauldron/SoupDisplay.java b/src/main/java/online/astradev/cauldron/SoupDisplay.java deleted file mode 100644 index 22ded35..0000000 --- a/src/main/java/online/astradev/cauldron/SoupDisplay.java +++ /dev/null @@ -1,53 +0,0 @@ -package online.astradev.cauldron; - -import com.mojang.math.Transformation; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.entity.Display; -import net.minecraft.world.entity.EntityTypes; -import net.minecraft.world.item.*; -import net.minecraft.world.level.storage.ValueOutput; - -import org.joml.Quaternionf; -import org.joml.Vector3f; - -final class SoupDisplay extends Display.ItemDisplay { - static final String TAG = "astracauldron:cauldron_visual"; - - SoupDisplay(ServerLevel level, BlockPos pos, ItemStack stack) { - super(EntityTypes.ITEM_DISPLAY, level); - setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5); - getSlot(0).set(stack.copy()); - setItemTransform(ItemDisplayContext.FIXED); - setNoGravity(true); - setInvulnerable(true); - setSilent(true); - addTag(TAG); - setTransformationInterpolationDuration(2); - } - - void ingredient(int slot, int water, int ticks, int elapsed, int duration) { - var frame = CauldronAnimation.frame(slot, water, ticks, elapsed, duration); - setTransformationInterpolationDelay(0); - setTransformation( - new Transformation( - new Vector3f( - (float) frame.x() - .5f, - (float) frame.y() - .5f, - (float) frame.z() - .5f), - new Quaternionf(), - new Vector3f(.3f), - new Quaternionf().rotationY(ticks * .035f + slot))); - } - - @Override - public boolean shouldBeSaved() { - return false; - } - - @Override - public boolean saveAsPassenger(ValueOutput output) { - return false; - } -} diff --git a/src/main/java/online/astradev/cauldron/SoupFiles.java b/src/main/java/online/astradev/cauldron/SoupFiles.java deleted file mode 100644 index e3530d2..0000000 --- a/src/main/java/online/astradev/cauldron/SoupFiles.java +++ /dev/null @@ -1,48 +0,0 @@ -package online.astradev.cauldron; - -import com.google.gson.*; -import com.mojang.serialization.JsonOps; - -import net.minecraft.core.HolderLookup; -import net.minecraft.resources.RegistryOps; -import net.minecraft.world.item.ItemStack; - -import java.io.IOException; -import java.nio.file.*; - -final class SoupFiles { - static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); - - private SoupFiles() {} - - static void write(Path path, JsonElement json) throws IOException { - Files.createDirectories(path.getParent()); - Path temp = Files.createTempFile(path.getParent(), "soups-", ".tmp"); - try { - Files.writeString(temp, JSON.toJson(json)); - try { - Files.move( - temp, - path, - StandardCopyOption.ATOMIC_MOVE, - StandardCopyOption.REPLACE_EXISTING); - } catch (AtomicMoveNotSupportedException e) { - Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING); - } - } finally { - Files.deleteIfExists(temp); - } - } - - static JsonElement encode(ItemStack stack, HolderLookup.Provider registries) { - return ItemStack.CODEC - .encodeStart(RegistryOps.create(JsonOps.INSTANCE, registries), stack) - .getOrThrow(); - } - - static ItemStack decode(JsonElement json, HolderLookup.Provider registries) { - return ItemStack.CODEC - .parse(RegistryOps.create(JsonOps.INSTANCE, registries), json) - .getOrThrow(); - } -} diff --git a/src/main/java/online/astradev/cauldron/SoupPots.java b/src/main/java/online/astradev/cauldron/SoupPots.java deleted file mode 100644 index bac9035..0000000 --- a/src/main/java/online/astradev/cauldron/SoupPots.java +++ /dev/null @@ -1,521 +0,0 @@ -package online.astradev.cauldron; - -import com.google.gson.*; - -import net.minecraft.ChatFormatting; -import net.minecraft.core.BlockPos; -import net.minecraft.core.particles.ParticleTypes; -import net.minecraft.core.registries.Registries; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.*; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.*; -import net.minecraft.sounds.*; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.item.*; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.LevelResource; - -import online.astradev.plus.api.AstraPlusApi; -import online.astradev.plus.api.ColoredWaterApi; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; - -public final class SoupPots implements AutoCloseable { - record Position(String dimension, BlockPos pos) { - static Position at(ServerLevel level, BlockPos pos) { - return new Position(level.dimension().identifier().toString(), pos.immutable()); - } - } - - public record Pot( - List items, ItemStack soup, int brewTicks, int servings, int capacity) { - public Pot { - items = List.copyOf(items); - } - - boolean brewing() { - return brewTicks > 0; - } - - boolean ready() { - return !soup.isEmpty() && !brewing(); - } - - static Pot raw(List items) { - return new Pot(items, ItemStack.EMPTY, 0, 0, 0); - } - } - - private final MinecraftServer server; - private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons"); - private final ColoredWaterApi water; - private final Path file; - private final Path configFile; - private SoupConfig config; - private Ingredients ingredients; - private final Map pots = new LinkedHashMap<>(); - private final Map> visuals = new HashMap<>(); - private final Map elapsed = new HashMap<>(); - private int ticks; - - public SoupPots(MinecraftServer server, Path configFile) throws IOException { - this.server = server; - this.water = AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow(); - this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json"); - this.configFile = configFile; - reload(); - load(); - } - - public Ingredients ingredients() { - return ingredients; - } - - public SoupConfig config() { - return config; - } - - public boolean contains(ServerLevel level, BlockPos pos) { - return pots.containsKey(Position.at(level, pos)); - } - - public Pot get(ServerLevel level, BlockPos pos) { - return pots.get(Position.at(level, pos)); - } - - public void reload() throws IOException { - var next = SoupConfig.load(configFile); - var nextIngredients = new Ingredients(next, server.registryAccess()); - config = next; - ingredients = nextIngredients; - } - - public void register(String id, ServerPlayer player, int nutrition, float saturation) - throws IOException { - if (!id.matches("[a-z0-9_-]+") || player.getMainHandItem().isEmpty()) - throw new IllegalArgumentException("Нужны ID и предмет в руке"); - var next = SoupFiles.JSON.fromJson(SoupFiles.JSON.toJson(config), SoupConfig.class); - var custom = next.updateIngredient(id, nutrition, saturation); - custom.item = null; - custom.astraPlusId = null; - // Resolve by stable AstraPlus identity; definitions can evolve without invalidating the - // registration. - var plus = AstraPlusApi.current().flatMap(api -> api.find(player.getMainHandItem())); - if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString(); - else - custom.item = - SoupFiles.encode( - Ingredients.normalizedCopy(player.getMainHandItem()), - server.registryAccess()); - var validated = new Ingredients(next, server.registryAccess()); - SoupFiles.write(configFile, SoupFiles.JSON.toJsonTree(next)); - config = next; - ingredients = validated; - } - - private void load() throws IOException { - if (!Files.exists(file)) return; - var root = JsonParser.parseString(Files.readString(file)).getAsJsonObject(); - if (root.get("version").getAsInt() != 1) - throw new IllegalArgumentException("Unknown cauldron data version"); - for (var value : root.getAsJsonArray("cauldrons")) { - var c = value.getAsJsonObject(); - String dimension = Identifier.parse(c.get("dimension").getAsString()).toString(); - var pos = - new Position( - dimension, - new BlockPos( - c.get("x").getAsInt(), - c.get("y").getAsInt(), - c.get("z").getAsInt())); - var items = new ArrayList(); - for (var i : c.getAsJsonArray("items")) - items.add(SoupFiles.decode(i, server.registryAccess())); - var soup = - c.has("soup") - ? SoupFiles.decode(c.get("soup"), server.registryAccess()) - : ItemStack.EMPTY; - var pot = - new Pot( - items, - soup, - c.get("brewTicks").getAsInt(), - c.get("servings").getAsInt(), - c.get("capacity").getAsInt()); - validate(pot); - if (pots.putIfAbsent(pos, pot) != null) - throw new IllegalArgumentException("Duplicate cauldron " + pos); - } - } - - private static void validate(Pot pot) { - if (pot.items.size() > 4) - throw new IllegalArgumentException("Too many cauldron ingredients"); - for (ItemStack ingredient : pot.items) { - if (ingredient.isEmpty() || ingredient.getCount() != 1) { - throw new IllegalArgumentException("Cauldron ingredients must be single items"); - } - } - if (pot.brewTicks < 0 || pot.brewTicks > 1200) { - throw new IllegalArgumentException("Invalid cauldron brewing time"); - } - if (pot.soup.isEmpty()) { - if (pot.servings != 0 || pot.capacity != 0 || pot.brewing() || pot.items.isEmpty()) { - throw new IllegalArgumentException("Invalid uncooked cauldron contents"); - } - return; - } - if (pot.soup.getCount() != 1 || !Ingredients.isCombined(pot.soup)) { - throw new IllegalArgumentException("Invalid cauldron soup"); - } - if (pot.servings < 1 || pot.capacity < pot.servings || pot.capacity > 16) { - throw new IllegalArgumentException("Invalid cauldron servings"); - } - if (pot.brewing()) { - if (pot.items.isEmpty()) - throw new IllegalArgumentException("Brewing requires ingredients"); - } else if (!pot.items.isEmpty()) { - throw new IllegalArgumentException("Finished soup cannot retain ingredients"); - } - } - - private boolean change(Position pos, Pot next) { - Pot old = pots.get(pos); - if (next == null) pots.remove(pos); - else { - validate(next); - pots.put(pos, next); - } - try { - var root = new JsonObject(); - root.addProperty("version", 1); - var array = new JsonArray(); - root.add("cauldrons", array); - for (var e : pots.entrySet()) { - var c = new JsonObject(); - var p = e.getKey(); - var pot = e.getValue(); - c.addProperty("dimension", p.dimension); - c.addProperty("x", p.pos.getX()); - c.addProperty("y", p.pos.getY()); - c.addProperty("z", p.pos.getZ()); - var items = new JsonArray(); - pot.items.forEach(i -> items.add(SoupFiles.encode(i, server.registryAccess()))); - c.add("items", items); - if (!pot.soup.isEmpty()) - c.add("soup", SoupFiles.encode(pot.soup, server.registryAccess())); - c.addProperty("brewTicks", pot.brewTicks); - c.addProperty("servings", pot.servings); - c.addProperty("capacity", pot.capacity); - array.add(c); - } - SoupFiles.write(file, root); - if (old == null - || next == null - || old.ready() != next.ready() - || old.items.size() != next.items.size()) removeVisuals(pos); - elapsed.remove(pos); - return true; - } catch (Exception e) { - if (old == null) pots.remove(pos); - else pots.put(pos, old); - AstraCauldron.LOG.error("Не удалось сохранить котёл; действие отменено", e); - return false; - } - } - - /** Returns whether vanilla interaction should be consumed. Saves before taking/giving items. */ - public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) { - var level = player.level(); - var pos = Position.at(level, blockPos); - var pot = pots.get(pos); - if (player.isSpectator()) return false; - if (!config.soupsEnabled && pot == null) return false; - if (hand != InteractionHand.MAIN_HAND) return pot != null; - var state = level.getBlockState(blockPos); - if (!valid(state, pot)) return false; - var held = player.getMainHandItem(); - if (pot == null && ingredients.read(held) == null) return false; - if (pot == null) { - if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) { - say(player, "Сначала наполните котёл водой доверху."); - return true; - } - pot = Pot.raw(List.of()); - } - if (pot.brewing()) { - say( - player, - (!config.requireHeat || CauldronHeat.heated(level, blockPos)) - ? "Суп варится… Осталось: " - + Math.max( - 1, - (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) - / 20) - + " с." - : "Варка приостановлена. Зажгите костёр под котлом."); - return true; - } - if (pot.ready()) { - if (!held.is(Items.BOWL)) { - say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); - return true; - } - int left = pot.servings - 1; - var result = pot.soup.copy(); - if (!change( - pos, left == 0 ? null : new Pot(List.of(), pot.soup, 0, left, pot.capacity))) { - saveError(player); - return true; - } - held.consume(1, player); - give(player, result); - level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3); - if (left > 0) show(level, pos, pots.get(pos)); - sound(level, blockPos, SoundEvents.BOTTLE_FILL); - say( - player, - left == 0 - ? "Последняя порция собрана. Котёл пуст." - : "Осталось порций: " + left + "."); - return true; - } - if (pot.items.size() >= config.ingredientCount - && (player.isShiftKeyDown() || !held.isEmpty())) { - if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) { - say(player, "Для варки нужен горящий костёр прямо под котлом."); - return true; - } - String rejection = ingredients.rejection(pot.items); - if (rejection != null) { - say(player, rejection + " ПКМ пустой рукой возвращает последний ингредиент."); - return true; - } - var next = - new Pot( - pot.items, - ingredients.brew(pot.items), - (int) Math.round(config.brewSeconds * 20), - config.servingsPerBrew, - config.servingsPerBrew); - if (!change(pos, next)) { - saveError(player); - return true; - } - sound(level, blockPos, SoundEvents.BREWING_STAND_BREW); - say(player, "Варка началась! Дождитесь окончания водоворота."); - return true; - } - if (held.isEmpty()) { - if (pot.items.isEmpty()) return true; - var remaining = new ArrayList<>(pot.items); - var last = remaining.removeLast(); - if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { - saveError(player); - return true; - } - give(player, last.copy()); - say( - player, - "Возвращён последний ингредиент. В котле: " - + remaining.size() - + "/" - + config.ingredientCount - + "."); - return true; - } - if (ingredients.read(held) == null) { - say( - player, - "Добавьте еду или зелье. В котле: " - + pot.items.size() - + "/" - + config.ingredientCount - + "."); - return true; - } - var items = new ArrayList<>(pot.items); - items.add(held.copyWithCount(1)); - if (!change(pos, Pot.raw(items))) { - saveError(player); - return true; - } - held.consume(1, player); - show(level, pos, pots.get(pos)); - sound(level, blockPos, SoundEvents.GENERIC_SPLASH); - say( - player, - "Ингредиенты: " - + items.size() - + "/" - + config.ingredientCount - + "." - + (items.size() == config.ingredientCount - ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." - : "")); - return true; - } - - public boolean breakPot(ServerLevel level, BlockPos blockPos) { - var pos = Position.at(level, blockPos); - var old = pots.get(pos); - if (old == null) return true; - if (!change(pos, null)) return false; - old.items.forEach(i -> Block.popResource(level, blockPos, i.copy())); - return true; - } - - private static boolean valid(BlockState state, Pot pot) { - return state.is(Blocks.WATER_CAULDRON) - || (state.is(Blocks.CAULDRON) && pot != null && pot.ready()); - } - - public void tick() { - ticks++; - for (var entry : new ArrayList<>(pots.entrySet())) { - var pos = entry.getKey(); - var pot = entry.getValue(); - var level = - server.getLevel( - ResourceKey.create( - Registries.DIMENSION, Identifier.parse(pos.dimension))); - if (level == null || !level.hasChunkAt(pos.pos)) { - removeVisuals(pos); - continue; - } - if (!valid(level.getBlockState(pos.pos), pot)) { - breakPot(level, pos.pos); - continue; - } - boolean heated = !config.requireHeat || CauldronHeat.heated(level, pos.pos); - if (pot.brewing() && heated) { - int time = elapsed.merge(pos, 1, Integer::sum); - if (time >= pot.brewTicks - && (time - pot.brewTicks) % 20 == 0 - && change( - pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) { - pot = pots.get(pos); - level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3); - sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP); - if (config.particles) - level.sendParticles( - ParticleTypes.CLOUD, - pos.pos.getX() + .5, - pos.pos.getY() + 1.05, - pos.pos.getZ() + .5, - 12, - .2, - .12, - .2, - .01); - } - } - show(level, pos, pot); - if (config.ingredientDisplays && ticks % 2 == 0 && !pot.ready()) { - var displays = visuals.get(pos); - int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL); - for (int i = 0; i < displays.size(); i++) - displays.get(i) - .ingredient( - i, - water, - ticks + 2, - elapsed.getOrDefault(pos, 0) + (heated ? 2 : 0), - pot.brewTicks); - } - } - if (ticks % 20 == 0) - for (var player : server.getPlayerList().getPlayers()) { - for (var slot : player.containerMenu.slots) Ingredients.normalize(slot.getItem()); - for (int i = 0; i < player.getInventory().getContainerSize(); i++) - Ingredients.normalize(player.getInventory().getItem(i)); - Ingredients.normalize(player.containerMenu.getCarried()); - player.containerMenu.broadcastChanges(); - } - } - - private void show(ServerLevel level, Position pos, Pot pot) { - if (pot.ready()) { - water.show( - level, - pos.pos, - new ColoredWaterApi.Surface( - WATER_OWNER, - Ingredients.color(pot.soup), - (float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity))); - return; - } - if (!config.ingredientDisplays) { - removeVisuals(pos); - return; - } - var existing = visuals.get(pos); - if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { - removeVisuals(pos); - existing = null; - } - if (existing != null) return; - var displays = new ArrayList(); - for (int i = 0; i < pot.items.size(); i++) { - var display = new SoupDisplay(level, pos.pos, pot.items.get(i)); - display.ingredient( - i, - level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL), - ticks, - elapsed.getOrDefault(pos, 0), - pot.brewTicks); - displays.add(display); - } - displays.forEach(level::addFreshEntity); - visuals.put(pos, displays); - } - - public void unload(ServerLevel level, int chunkX, int chunkZ) { - for (var pos : new ArrayList<>(visuals.keySet())) - if (pos.dimension.equals(level.dimension().identifier().toString()) - && (pos.pos.getX() >> 4) == chunkX - && (pos.pos.getZ() >> 4) == chunkZ) removeVisuals(pos); - } - - private void removeVisuals(Position pos) { - var list = visuals.remove(pos); - if (list != null) list.forEach(SoupDisplay::discard); - var level = - server.getLevel( - ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension))); - if (level != null) water.remove(level, pos.pos, WATER_OWNER); - } - - @Override - public void close() { - for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos); - water.removeAll(WATER_OWNER); - } - - private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { - if (config.sounds) - level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 1f); - } - - private static void give(ServerPlayer player, ItemStack item) { - Ingredients.normalize(item); - AstraPlusApi.give(player, item); - } - - private static void say(ServerPlayer player, String text) { - var config = AstraCauldron.config(); - if (config.messages) - player.sendSystemMessage( - Component.literal(config.messageOverrides.getOrDefault(text, text)) - .withStyle(ChatFormatting.GOLD), - true); - } - - private static void saveError(ServerPlayer player) { - say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); - } -} diff --git a/src/main/java/online/astradev/cauldron/SoupText.java b/src/main/java/online/astradev/cauldron/SoupText.java deleted file mode 100644 index 6cd7e3b..0000000 --- a/src/main/java/online/astradev/cauldron/SoupText.java +++ /dev/null @@ -1,19 +0,0 @@ -package online.astradev.cauldron; - -final class SoupText { - private SoupText() {} - - static String roman(int level) { - if (level < 1 || level > 256) - throw new IllegalArgumentException("Potion level out of range: " + level); - int[] values = {100, 90, 50, 40, 10, 9, 5, 4, 1}; - String[] numerals = {"C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; - StringBuilder text = new StringBuilder(); - for (int i = 0; i < values.length; i++) - while (level >= values[i]) { - text.append(numerals[i]); - level -= values[i]; - } - return text.toString(); - } -} diff --git a/src/main/java/online/astradev/cauldron/mixin/CampfireHeatMixin.java b/src/main/java/online/astradev/cauldron/mixin/CampfireHeatMixin.java deleted file mode 100644 index da37ffb..0000000 --- a/src/main/java/online/astradev/cauldron/mixin/CampfireHeatMixin.java +++ /dev/null @@ -1,28 +0,0 @@ -package online.astradev.cauldron.mixin; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.crafting.*; -import net.minecraft.world.level.block.entity.CampfireBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -import online.astradev.cauldron.CauldronHeat; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(CampfireBlockEntity.class) -public abstract class CampfireHeatMixin { - @Inject(method = "cookTick", at = @At("TAIL")) - private static void astracauldron$heat( - ServerLevel level, - BlockPos pos, - BlockState state, - CampfireBlockEntity entity, - RecipeManager.CachedCheck recipes, - CallbackInfo ci) { - CauldronHeat.tick(level, pos); - } -} diff --git a/src/main/java/online/astradev/cauldron/mixin/CauldronWeatherMixin.java b/src/main/java/online/astradev/cauldron/mixin/CauldronWeatherMixin.java deleted file mode 100644 index 230e4c4..0000000 --- a/src/main/java/online/astradev/cauldron/mixin/CauldronWeatherMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package online.astradev.cauldron.mixin; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Fluid; - -import online.astradev.cauldron.AstraCauldron; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.*; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** NeoForge has no cancellable event for these vanilla cauldron mutations. */ -@Mixin({CauldronBlock.class, LayeredCauldronBlock.class}) -abstract class CauldronWeatherMixin { - @Inject(method = "handlePrecipitation", at = @At("HEAD"), cancellable = true) - private void soups$rain( - BlockState state, - Level level, - BlockPos pos, - Biome.Precipitation precipitation, - CallbackInfo ci) { - if (AstraCauldron.occupied(level, pos)) ci.cancel(); - } - - @Inject(method = "receiveStalactiteDrip", at = @At("HEAD"), cancellable = true) - private void soups$drip( - BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) { - if (AstraCauldron.occupied(level, pos)) ci.cancel(); - } -} diff --git a/src/main/java/online/astradev/cauldron/mixin/LayeredCauldronMixin.java b/src/main/java/online/astradev/cauldron/mixin/LayeredCauldronMixin.java deleted file mode 100644 index b418813..0000000 --- a/src/main/java/online/astradev/cauldron/mixin/LayeredCauldronMixin.java +++ /dev/null @@ -1,20 +0,0 @@ -package online.astradev.cauldron.mixin; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.LayeredCauldronBlock; -import net.minecraft.world.level.block.state.BlockState; - -import online.astradev.cauldron.AstraCauldron; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.*; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(LayeredCauldronBlock.class) -abstract class LayeredCauldronMixin { - @Inject(method = "lowerFillLevel", at = @At("HEAD"), cancellable = true) - private static void soups$lower(BlockState state, Level level, BlockPos pos, CallbackInfo ci) { - if (AstraCauldron.occupied(level, pos)) ci.cancel(); - } -} diff --git a/src/main/java/online/astradev/cauldron/mixin/SoupStackMixin.java b/src/main/java/online/astradev/cauldron/mixin/SoupStackMixin.java deleted file mode 100644 index bf07ba9..0000000 --- a/src/main/java/online/astradev/cauldron/mixin/SoupStackMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package online.astradev.cauldron.mixin; - -import net.minecraft.core.Holder; -import net.minecraft.core.component.*; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import online.astradev.cauldron.AstraCauldron; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.*; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -/** Per-stack patch is sent to vanilla clients; no change to their assumed item defaults. */ -@Mixin(ItemStack.class) -abstract class SoupStackMixin { - @Inject( - method = - "(Lnet/minecraft/core/Holder;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", - at = @At("RETURN")) - private void soups$stackSize( - Holder item, int count, PatchedDataComponentMap components, CallbackInfo ci) { - var key = item.unwrapKey().orElse(null); - if (key == null || !key.identifier().getNamespace().equals("minecraft")) return; - switch (key.identifier().getPath()) { - case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> { - var config = AstraCauldron.config(); - if (config.normalizeVanillaSoups) - components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize); - } - default -> {} - } - } -} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 341695f..b065b26 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -6,8 +6,6 @@ modId="astracauldron" version="${version}" displayName="AstraCauldron" description='''Server-side cauldron soups with AstraPlus ingredients and resources.''' -[[mixins]] -config="astracauldron.mixins.json" [[dependencies.astracauldron]] modId="neoforge" type="required" diff --git a/src/main/resources/astracauldron.mixins.json b/src/main/resources/astracauldron.mixins.json deleted file mode 100644 index ae1dc32..0000000 --- a/src/main/resources/astracauldron.mixins.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "required": true, - "package": "online.astradev.cauldron.mixin", - "compatibilityLevel": "JAVA_25", - "server": ["CauldronWeatherMixin", "LayeredCauldronMixin", "SoupStackMixin", "CampfireHeatMixin"], - "injectors": {"defaultRequire": 1} -} diff --git a/src/main/resources/editor/combination-compatibility.json b/src/main/resources/editor/combination-compatibility.json new file mode 100644 index 0000000..b85e267 --- /dev/null +++ b/src/main/resources/editor/combination-compatibility.json @@ -0,0 +1,13 @@ +{ + "soupPath": "astracauldron/cauldrons.json", + "liquidPath": "astracauldron/liquids.json", + "entriesKey": "cauldrons", + "waterOwner": "astracauldron:cauldrons", + "liquidOwner": "astracauldron:liquids", + "markerTag": "astracauldron:combined_soup", + "colorTag": "astracauldron:soup_color", + "visualTag": "astracauldron:cauldron_visual", + "combinedSelector": "soup:combined", + "customPotionSource": "astracauldron:custom_potion", + "commands": ["cauldron", "soups"] +} diff --git a/src/main/resources/editor/combination-defaults.json b/src/main/resources/editor/combination-defaults.json new file mode 100644 index 0000000..92fe37e --- /dev/null +++ b/src/main/resources/editor/combination-defaults.json @@ -0,0 +1,153 @@ +{ + "soupsEnabled": true, + "dyeWater": true, + "dyeArmor": true, + "dyeBlocks": true, + "storePotions": true, + "tipArrows": true, + "requireHeat": true, + "particles": true, + "ingredientDisplays": true, + "sounds": true, + "soundVolume": 0.8, + "messages": true, + "ingredientCount": 4, + "inheritEffects": true, + "alwaysEdible": true, + "consumeSeconds": 1.6, + "returnBowl": true, + "soupStackSize": 16, + "normalizeVanillaSoups": true, + "messageOverrides": {}, + "servingsPerBrew": 4, + "requireFullWater": true, + "brewSeconds": 4, + "soupName": "Комбинированный суп", + "defaultColor": "#B77A36", + "maxNutrition": 1000, + "maxSaturation": 1000, + "blockedIngredients": [], + "incompatible": [], + "customIngredients": {}, + "cakeNutrition": 14, + "cakeSaturation": 2.8, + "ingredientColors": { + "spider_eye": "#B52B38", + "fermented_spider_eye": "#B52B38", + "golden_apple": "#F2C94C", + "enchanted_golden_apple": "#F2C94C", + "golden_carrot": "#F2C94C", + "apple": "#C73735", + "sweet_berries": "#C73735", + "beetroot": "#A52B4B", + "beetroot_soup": "#A52B4B", + "carrot": "#E99032", + "pumpkin_pie": "#E99032", + "glow_berries": "#E99032", + "dried_kelp": "#47733B", + "poisonous_potato": "#91A340", + "melon_slice": "#D94E58", + "chorus_fruit": "#9C6C9D", + "beef": "#C76B70", + "mutton": "#C76B70", + "porkchop": "#C76B70", + "rabbit": "#C76B70", + "chicken": "#E2A6A0", + "cooked_beef": "#815033", + "cooked_mutton": "#815033", + "cooked_porkchop": "#BA8551", + "cooked_rabbit": "#BA8551", + "cooked_chicken": "#BA8551", + "salmon": "#D98262", + "cooked_salmon": "#D98262", + "tropical_fish": "#D98262", + "cod": "#B0A07B", + "cooked_cod": "#C4B486", + "pufferfish": "#D3B54D", + "bread": "#BA873F", + "cookie": "#BA873F", + "baked_potato": "#BA873F", + "potato": "#C7A76B", + "rotten_flesh": "#8F6540", + "honey_bottle": "#E9AC32", + "cake": "#E8CCBA", + "mushroom_stew": "#A37A53", + "rabbit_stew": "#AC8854", + "suspicious_stew": "#867743" + }, + "engine": { + "carrier": "minecraft:mushroom_stew", + "model": "astradev_soups:combined_soup", + "remainder": "minecraft:bowl", + "specialFood": "minecraft:cake", + "potionBase": "minecraft:potion", + "consumeTemplate": "minecraft:mushroom_stew", + "glassBottle": "minecraft:glass_bottle", + "waterBucket": "minecraft:water_bucket", + "bucket": "minecraft:bucket", + "emptyContainer": "minecraft:cauldron", + "waterContainer": "minecraft:water_cauldron", + "lavaContainer": "minecraft:lava_cauldron", + "snowContainer": "minecraft:powder_snow_cauldron", + "normalHeat": "minecraft:campfire", + "soulHeat": "minecraft:soul_campfire", + "waterPotion": "minecraft:water", + "normalizedItems": [ + "minecraft:mushroom_stew", + "minecraft:rabbit_stew", + "minecraft:beetroot_soup", + "minecraft:suspicious_stew" + ], + "potionItems": [ + "minecraft:potion", + "minecraft:splash_potion", + "minecraft:lingering_potion" + ], + "maxIngredientCount": 4, + "maxServings": 16, + "maxBrewTicks": 1200, + "maxEffectCount": 256, + "maxLiquidLevels": 3, + "normalizationIntervalTicks": 20, + "displayUpdateTicks": 2, + "heatParticleIntervalTicks": 10, + "saveRetryTicks": 20, + "displayInterpolationTicks": 2, + "displayScale": 0.3, + "displayRotationPerTick": 0.035, + "orbitRadius": 0.23, + "orbitRadiansPerBrewTick": 0.1, + "orbitAngles": "-135,-45,135,45", + "bobSpeed": 0.04, + "bobHeight": 0.004, + "ingredientSubmersion": 0.055, + "liquidBaseHeight": 0.25, + "liquidHeightRange": 0.6875, + "waterBaseHeight": 0.375, + "waterStepHeight": 0.1875, + "soundFill": "minecraft:item.bottle.fill", + "soundStart": "minecraft:block.brewing_stand.brew", + "soundIngredient": "minecraft:entity.generic.splash", + "soundComplete": "minecraft:block.bubble_column.bubble_pop", + "soundRecipe": "minecraft:item.bucket.empty", + "recipeSoundVolume": 0.5, + "heatBubbleParticle": "minecraft:bubble_pop", + "heatBubbleCount": 4, + "heatBubbleOffset": 0.01, + "heatBubbleHorizontal": 0.18, + "heatBubbleVertical": 0.015, + "heatBubbleSpeed": 0, + "heatSplashParticle": "minecraft:splash", + "heatSplashCount": 2, + "heatSplashOffset": 0.02, + "heatSplashHorizontal": 0.16, + "heatSplashVertical": 0, + "heatSplashSpeed": 0, + "completionParticle": "minecraft:cloud", + "completionCount": 12, + "completionHeight": 1.05, + "completionHorizontal": 0.2, + "completionVertical": 0.12, + "completionSpeed": 0.01 + } +} diff --git a/src/main/resources/editor/combination-schema.json b/src/main/resources/editor/combination-schema.json new file mode 100644 index 0000000..ffa5d8f --- /dev/null +++ b/src/main/resources/editor/combination-schema.json @@ -0,0 +1,710 @@ +{ + "description": "Действующие правила котлов AstraCauldron. Сохранение сразу применяется к новым взаимодействиям; уже сваренные порции и содержимое мира не переписываются.", + "fields": [ + { + "path": "soupsEnabled", + "label": "Варка супов", + "type": "boolean", + "group": "Варка" + }, + { + "path": "ingredientCount", + "label": "Количество ингредиентов", + "type": "integer", + "min": 1, + "max": 64, + "group": "Варка" + }, + { + "path": "servingsPerBrew", + "label": "Порций за варку", + "type": "integer", + "min": 1, + "max": 64, + "group": "Варка" + }, + { + "path": "brewSeconds", + "label": "Время варки, секунды", + "type": "number", + "min": 0.5, + "max": 3600, + "group": "Варка" + }, + { + "path": "requireHeat", + "label": "Требуется источник тепла", + "type": "boolean", + "group": "Варка" + }, + { + "path": "requireFullWater", + "label": "Требуется полный котёл воды", + "type": "boolean", + "group": "Варка" + }, + { + "path": "blockedIngredients", + "label": "Запрещённые ингредиенты", + "type": "strings", + "group": "Сочетания", + "description": "Селекторы: material:carrot, effect:minecraft:poison, custom:имя, astraplus:namespace:id, soup:combined или *." + }, + { + "path": "incompatible", + "label": "Несовместимые пары", + "type": "object", + "group": "Сочетания", + "editor": { + "kind": "pairs", + "labels": [ + "Первый селектор", + "Второй селектор" + ], + "valueType": "selector" + }, + "description": "Укажите два селектора, например material:carrot и material:potato. Порядок ингредиентов не имеет значения." + }, + { + "path": "customIngredients", + "label": "Пользовательские ингредиенты", + "type": "object", + "group": "Сочетания", + "editor": { + "kind": "ingredients" + }, + "description": "Каждый ингредиент имеет свой ключ и привязку к ID AstraPlus или точному образцу предмета. Питание и эффекты добавляются при варке." + }, + { + "path": "maxNutrition", + "label": "Максимальное питание супа", + "type": "integer", + "min": 0, + "max": 2147483647, + "group": "Питание" + }, + { + "path": "maxSaturation", + "label": "Максимальное насыщение супа", + "type": "number", + "min": 0, + "group": "Питание" + }, + { + "path": "cakeNutrition", + "label": "Питание целого торта", + "type": "integer", + "min": 0, + "max": 2147483647, + "group": "Питание" + }, + { + "path": "cakeSaturation", + "label": "Насыщение целого торта", + "type": "number", + "min": 0, + "group": "Питание" + }, + { + "path": "inheritEffects", + "label": "Наследовать эффекты ингредиентов", + "type": "boolean", + "group": "Питание" + }, + { + "path": "alwaysEdible", + "label": "Можно есть при полном голоде", + "type": "boolean", + "group": "Готовый суп" + }, + { + "path": "consumeSeconds", + "label": "Время употребления, секунды", + "type": "number", + "min": 0.05, + "max": 60, + "group": "Готовый суп" + }, + { + "path": "returnBowl", + "label": "Возвращать миску", + "type": "boolean", + "group": "Готовый суп" + }, + { + "path": "soupStackSize", + "label": "Размер стопки супов", + "type": "integer", + "min": 1, + "max": 64, + "group": "Готовый суп" + }, + { + "path": "normalizeVanillaSoups", + "label": "Применять размер стопки к ванильным супам", + "type": "boolean", + "group": "Готовый суп" + }, + { + "path": "soupName", + "label": "Название супа", + "type": "string", + "group": "Внешний вид" + }, + { + "path": "defaultColor", + "label": "Цвет по умолчанию", + "type": "string", + "group": "Внешний вид", + "description": "Цвет в формате #RRGGBB." + }, + { + "path": "ingredientColors", + "label": "Цвета ингредиентов", + "type": "object", + "group": "Внешний вид", + "editor": { + "kind": "map", + "keyType": "material", + "valueType": "color", + "keyLabel": "Материал без namespace", + "valueLabel": "Цвет" + }, + "description": "Имена ванильных материалов без namespace. Цвет готового супа усредняется по ингредиентам." + }, + { + "path": "particles", + "label": "Частицы", + "type": "boolean", + "group": "Внешний вид" + }, + { + "path": "ingredientDisplays", + "label": "Отображать ингредиенты в котле", + "type": "boolean", + "group": "Внешний вид" + }, + { + "path": "sounds", + "label": "Звуки", + "type": "boolean", + "group": "Обратная связь" + }, + { + "path": "soundVolume", + "label": "Громкость", + "type": "number", + "min": 0, + "max": 4, + "group": "Обратная связь" + }, + { + "path": "messages", + "label": "Сообщения игрокам", + "type": "boolean", + "group": "Обратная связь" + }, + { + "path": "messageOverrides", + "label": "Тексты сообщений", + "type": "object", + "group": "Обратная связь", + "editor": { + "kind": "map", + "keyType": "text", + "valueType": "text", + "keyLabel": "Исходная фраза", + "valueLabel": "Замена" + }, + "description": "Укажите точный исходный текст и его замену. Пробелы и переносы строк сохраняются." + }, + { + "path": "dyeWater", + "label": "Окрашивание воды", + "type": "boolean", + "group": "Жидкости" + }, + { + "path": "dyeArmor", + "label": "Окрашивание брони", + "type": "boolean", + "group": "Жидкости" + }, + { + "path": "dyeBlocks", + "label": "Окрашивание блоков", + "type": "boolean", + "group": "Жидкости" + }, + { + "path": "storePotions", + "label": "Хранение зелий", + "type": "boolean", + "group": "Жидкости" + }, + { + "path": "tipArrows", + "label": "Стрелы с эффектами зелий", + "type": "boolean", + "group": "Жидкости" + }, + { + "path": "engine.carrier", + "label": "Предмет-носитель смеси", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.model", + "label": "Модель готовой смеси", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.remainder", + "label": "Возвращаемая ёмкость", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.specialFood", + "label": "Особый пищевой ингредиент", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.potionBase", + "label": "Базовая форма зелья", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.consumeTemplate", + "label": "Образец поведения употребления", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.glassBottle", + "label": "Пустая бутылочка", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.waterBucket", + "label": "Ёмкость с водой", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.bucket", + "label": "Пустая ёмкость для воды", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.emptyContainer", + "label": "Пустой контейнер", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.waterContainer", + "label": "Контейнер с водой", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.lavaContainer", + "label": "Контейнер с лавой", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.snowContainer", + "label": "Контейнер со снегом", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.normalHeat", + "label": "Обычный источник нагрева", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.soulHeat", + "label": "Альтернативный источник нагрева", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.waterPotion", + "label": "Зелье чистой воды", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.normalizedItems", + "label": "Предметы с общей нормализацией стопки", + "type": "strings", + "group": "Движок смешивания" + }, + { + "path": "engine.potionItems", + "label": "Пищевые формы зелий", + "type": "strings", + "group": "Движок смешивания" + }, + { + "path": "engine.maxIngredientCount", + "label": "Предел ингредиентов", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 64 + }, + { + "path": "engine.maxServings", + "label": "Предел порций", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 64 + }, + { + "path": "engine.maxBrewTicks", + "label": "Предельное время варки, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 10, + "max": 72000 + }, + { + "path": "engine.maxEffectCount", + "label": "Предел действий эффектов", + "type": "integer", + "group": "Движок смешивания", + "min": 0, + "max": 1024 + }, + { + "path": "engine.maxLiquidLevels", + "label": "Максимум уровней жидкости", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 3 + }, + { + "path": "engine.normalizationIntervalTicks", + "label": "Интервал обновления инвентаря, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 1200 + }, + { + "path": "engine.displayUpdateTicks", + "label": "Интервал анимации ингредиентов, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 1200 + }, + { + "path": "engine.heatParticleIntervalTicks", + "label": "Интервал частиц нагрева, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 1200 + }, + { + "path": "engine.saveRetryTicks", + "label": "Повтор сохранения завершённой варки, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 1, + "max": 1200 + }, + { + "path": "engine.displayInterpolationTicks", + "label": "Интерполяция отображения, тики", + "type": "integer", + "group": "Движок смешивания", + "min": 0, + "max": 1200 + }, + { + "path": "engine.displayScale", + "label": "Масштаб ингредиента", + "type": "number", + "group": "Движок смешивания", + "min": 0.001, + "max": 16 + }, + { + "path": "engine.displayRotationPerTick", + "label": "Вращение ингредиента, радиан/тик", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 10 + }, + { + "path": "engine.orbitRadius", + "label": "Радиус орбиты ингредиентов", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.orbitRadiansPerBrewTick", + "label": "Вращение орбиты при варке, радиан/тик", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 10 + }, + { + "path": "engine.orbitAngles", + "label": "Начальные углы ингредиентов, градусы через запятую", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.bobSpeed", + "label": "Частота покачивания", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 10 + }, + { + "path": "engine.bobHeight", + "label": "Высота покачивания", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.ingredientSubmersion", + "label": "Погружение ингредиентов", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.liquidBaseHeight", + "label": "Нижняя высота готовой жидкости", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 1 + }, + { + "path": "engine.liquidHeightRange", + "label": "Диапазон высоты готовой жидкости", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 1 + }, + { + "path": "engine.waterBaseHeight", + "label": "Нижняя высота воды", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 1 + }, + { + "path": "engine.waterStepHeight", + "label": "Высота одного уровня воды", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 1 + }, + { + "path": "engine.soundFill", + "label": "Звук наполнения ёмкости", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.soundStart", + "label": "Звук начала варки", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.soundIngredient", + "label": "Звук добавления ингредиента", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.soundComplete", + "label": "Звук завершения варки", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.soundRecipe", + "label": "Звук мгновенного рецепта", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.recipeSoundVolume", + "label": "Громкость мгновенного рецепта", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatBubbleParticle", + "label": "Частица пузырьков", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.heatBubbleCount", + "label": "Количество пузырьков", + "type": "integer", + "group": "Движок смешивания", + "min": 0, + "max": 1000 + }, + { + "path": "engine.heatBubbleOffset", + "label": "Высота пузырьков над водой", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatBubbleHorizontal", + "label": "Горизонтальный разброс пузырьков", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatBubbleVertical", + "label": "Вертикальный разброс пузырьков", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatBubbleSpeed", + "label": "Скорость пузырьков", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatSplashParticle", + "label": "Частица брызг", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.heatSplashCount", + "label": "Количество брызг", + "type": "integer", + "group": "Движок смешивания", + "min": 0, + "max": 1000 + }, + { + "path": "engine.heatSplashOffset", + "label": "Высота брызг над водой", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatSplashHorizontal", + "label": "Горизонтальный разброс брызг", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatSplashVertical", + "label": "Вертикальный разброс брызг", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.heatSplashSpeed", + "label": "Скорость брызг", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.completionParticle", + "label": "Частица завершения варки", + "type": "string", + "group": "Движок смешивания" + }, + { + "path": "engine.completionCount", + "label": "Количество частиц завершения", + "type": "integer", + "group": "Движок смешивания", + "min": 0, + "max": 1000 + }, + { + "path": "engine.completionHeight", + "label": "Высота частиц завершения", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.completionHorizontal", + "label": "Горизонтальный разброс завершения", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.completionVertical", + "label": "Вертикальный разброс завершения", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + }, + { + "path": "engine.completionSpeed", + "label": "Скорость частиц завершения", + "type": "number", + "group": "Движок смешивания", + "min": 0, + "max": 4 + } + ] +} diff --git a/src/test/java/online/astradev/cauldron/CauldronAnimationTest.java b/src/test/java/online/astradev/cauldron/CauldronAnimationTest.java deleted file mode 100644 index 98980ff..0000000 --- a/src/test/java/online/astradev/cauldron/CauldronAnimationTest.java +++ /dev/null @@ -1,73 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class CauldronAnimationTest { - @Test - void remainsInsideCauldronAtEveryWaterLevel() { - for (int level = 1; level <= 3; level++) - for (int tick = 0; tick <= 80; tick++) - for (int slot = 0; slot < 4; slot++) { - var p = CauldronAnimation.frame(slot, level, tick, tick, 80); - assertTrue(p.x() > .125 && p.x() < .875 && p.z() > .125 && p.z() < .875); - assertTrue(p.y() >= .26 && p.y() < .375 + .1875 * level); - } - } - - @Test - void displayCenterIsPartlySubmergedWithoutNativeBobbing() { - for (int tick = 0; tick < 200; tick++) { - var p = CauldronAnimation.frame(0, 3, tick, 0, 0); - assertTrue(.9375 - p.y() >= .05 && .9375 - p.y() <= .06); - } - } - - @Test - void whirlpoolKeepsRadiusThroughoutRotation() { - var start = CauldronAnimation.frame(0, 3, 0, 0, 80); - var middle = CauldronAnimation.frame(0, 3, 40, 40, 80); - var end = CauldronAnimation.frame(0, 3, 80, 80, 80); - for (int tick = 0; tick <= 80; tick++) { - var p = CauldronAnimation.frame(0, 3, tick, tick, 80); - assertEquals(.23, Math.hypot(p.x() - .5, p.z() - .5), .000001); - } - assertEquals(start.y(), end.y(), .008); - assertTrue( - Math.atan2(middle.z() - .5, middle.x() - .5) - != Math.atan2(start.z() - .5, start.x() - .5)); - } - - @Test - void initialPositionDoesNotJumpWhenBrewingStarts() { - assertEquals( - CauldronAnimation.frame(2, 3, 15, 0, 0), CauldronAnimation.frame(2, 3, 15, 0, 80)); - } - - @Test - void everyPortionLowersLiquidAndUnderlyingWater() { - for (int remaining = 4; remaining > 0; remaining--) { - assertEquals(remaining - 1, CauldronAnimation.waterLevel(remaining, 4)); - assertTrue( - CauldronAnimation.liquidHeight(remaining, 4) - > CauldronAnimation.liquidHeight(remaining - 1, 4)); - int water = CauldronAnimation.waterLevel(remaining, 4); - if (water > 0) - assertTrue(.375 + .1875 * water <= CauldronAnimation.liquidHeight(remaining, 4)); - } - } - - @Test - void arbitraryBatchSizesNeverExposeBlueWaterAboveSoup() { - for (int capacity = 1; capacity <= 16; capacity++) - for (int remaining = 1; remaining <= capacity; remaining++) { - int water = CauldronAnimation.waterLevel(remaining, capacity); - if (water > 0) - assertTrue( - .375 + .1875 * water - <= CauldronAnimation.liquidHeight(remaining, capacity) - + .00001); - } - } -} diff --git a/src/test/java/online/astradev/cauldron/CombinationRulesTest.java b/src/test/java/online/astradev/cauldron/CombinationRulesTest.java deleted file mode 100644 index cf5dec1..0000000 --- a/src/test/java/online/astradev/cauldron/CombinationRulesTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -import java.util.*; - -class CombinationRulesTest { - private final List> four = - List.of( - Set.of("material:beef", "effect:minecraft:strength"), - Set.of("material:carrot"), - Set.of("material:beef"), - Set.of("material:potion", "effect:minecraft:weakness")); - - @Test - void exactlyFour() { - assertNotNull(CombinationRules.rejection(four.subList(0, 3), List.of(), List.of())); - assertNull(CombinationRules.rejection(four, List.of(), List.of())); - } - - @Test - void blockedSelectorsAreCaseInsensitive() { - assertNotNull(CombinationRules.rejection(four, List.of("material:BEEF"), List.of())); - } - - @Test - void compatibilityIsSymmetricAcrossSlots() { - assertNotNull( - CombinationRules.rejection( - four, - List.of(), - List.of( - List.of( - "effect:minecraft:weakness", - "effect:minecraft:strength")))); - } - - @Test - void oneIngredientDoesNotConflictWithItself() { - assertNull( - CombinationRules.rejection( - four, - List.of(), - List.of(List.of("material:potion", "effect:minecraft:weakness")))); - } - - @Test - void duplicatesCanBeForbiddenExplicitly() { - assertNotNull( - CombinationRules.rejection( - four, List.of(), List.of(List.of("material:beef", "material:beef")))); - assertNull( - CombinationRules.rejection( - four, List.of(), List.of(List.of("material:carrot", "material:carrot")))); - } - - @Test - void wildcardAndUnknownSelector() { - assertNotNull(CombinationRules.rejection(four, List.of("*"), List.of())); - assertNull(CombinationRules.rejection(four, List.of("custom:other"), List.of())); - } -} diff --git a/src/test/java/online/astradev/cauldron/ConfigurationPolicyTest.java b/src/test/java/online/astradev/cauldron/ConfigurationPolicyTest.java deleted file mode 100644 index fd3da42..0000000 --- a/src/test/java/online/astradev/cauldron/ConfigurationPolicyTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.*; -import java.util.*; - -class ConfigurationPolicyTest { - @TempDir Path root; - - @Test - void oldConfigKeepsDefaultsAndNewFieldsAreValidated() throws Exception { - Path file = root.resolve("cauldron.json"); - Files.writeString( - file, - "{\"servingsPerBrew\":2,\"ingredientCount\":2,\"requireHeat\":false,\"soupStackSize\":8}"); - var config = SoupConfig.load(file); - assertEquals(2, config.servingsPerBrew); - assertEquals(2, config.ingredientCount); - assertEquals(8, config.soupStackSize); - assertFalse(config.requireHeat); - assertTrue(config.tipArrows); - config.ingredientCount = 5; - assertThrows(IllegalArgumentException.class, config::validate); - } - - @Test - void ingredientCountStillChecksForbiddenCombinations() { - var ingredients = List.of(Set.of("material:carrot"), Set.of("material:potato")); - assertNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 2)); - assertNotNull( - CombinationRules.rejection(ingredients, List.of("material:carrot"), List.of(), 2)); - assertNotNull( - CombinationRules.rejection( - ingredients, - List.of(), - List.of(List.of("material:carrot", "material:potato")), - 2)); - assertNotNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 3)); - } -} diff --git a/src/test/java/online/astradev/cauldron/IngredientUpdateTest.java b/src/test/java/online/astradev/cauldron/IngredientUpdateTest.java deleted file mode 100644 index b73bdf9..0000000 --- a/src/test/java/online/astradev/cauldron/IngredientUpdateTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class IngredientUpdateTest { - @Test - void nutritionUpdatePreservesConfiguredColorAndEffects() { - var config = new SoupConfig(); - var original = config.updateIngredient("herb", 2, .5f); - original.color = "#70AA40"; - var effect = new SoupConfig.Effect(); - effect.type = "minecraft:regeneration"; - effect.duration = 100; - original.effects.add(effect); - - var updated = config.updateIngredient("herb", 5, .8f); - - assertSame(original, updated); - assertEquals(5, updated.nutrition); - assertEquals(.8f, updated.saturation); - assertEquals("#70AA40", updated.color); - assertEquals(1, updated.effects.size()); - assertSame(effect, updated.effects.getFirst()); - } -} diff --git a/src/test/java/online/astradev/cauldron/SoupConfigTest.java b/src/test/java/online/astradev/cauldron/SoupConfigTest.java deleted file mode 100644 index ac41cb5..0000000 --- a/src/test/java/online/astradev/cauldron/SoupConfigTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.*; -import java.util.List; - -class SoupConfigTest { - @TempDir Path root; - - @Test - void writesDefaultsAndRejectsInvalidFileWithoutReplacingIt() throws Exception { - Path path = root.resolve("config.json"); - assertEquals(4, SoupConfig.load(path).servingsPerBrew); - String broken = "{\"brewSeconds\":0}"; - Files.writeString(path, broken); - assertThrows(IllegalArgumentException.class, () -> SoupConfig.load(path)); - assertEquals(broken, Files.readString(path)); - } - - @Test - void validatesSelectorsAndDistinctCustomIdentityModes() { - var c = new SoupConfig(); - c.blockedIngredients = List.of("astraplus:foods:chili"); - c.validate(); - c.blockedIngredients = List.of("itemsadder:foods:chili"); - assertThrows(IllegalArgumentException.class, c::validate); - c.blockedIngredients = List.of(); - var food = new SoupConfig.Custom(); - food.astraPlusId = "foods:chili"; - food.nutrition = 4; - food.saturation = 2; - c.customIngredients.put("chili", food); - c.validate(); - food.item = new com.google.gson.JsonObject(); - assertThrows(IllegalArgumentException.class, c::validate); - } - - @Test - void rejectsNonfiniteNutritionAndInvalidColors() { - var c = new SoupConfig(); - c.maxSaturation = Float.NaN; - assertThrows(IllegalArgumentException.class, c::validate); - c.maxSaturation = 1000; - c.defaultColor = "#1234567"; - assertThrows(IllegalArgumentException.class, c::validate); - } -} diff --git a/src/test/java/online/astradev/cauldron/SoupTextTest.java b/src/test/java/online/astradev/cauldron/SoupTextTest.java deleted file mode 100644 index 466faeb..0000000 --- a/src/test/java/online/astradev/cauldron/SoupTextTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package online.astradev.cauldron; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.Test; - -class SoupTextTest { - @Test - void formatsPotionLevelsAsRomanNumerals() { - assertEquals("I", SoupText.roman(1)); - assertEquals("II", SoupText.roman(2)); - assertEquals("IV", SoupText.roman(4)); - assertEquals("IX", SoupText.roman(9)); - assertEquals("XL", SoupText.roman(40)); - assertEquals("XC", SoupText.roman(90)); - assertEquals("CCLVI", SoupText.roman(256)); - } -}