From 84f22a931fa2a8060175c02f399f30acfdb1815a Mon Sep 17 00:00:00 2001 From: ScarPC Date: Thu, 24 Sep 2026 20:16:29 +0300 Subject: [PATCH] Own cauldron gameplay lifecycle and persistence outside AstraPlus --- README.md | 32 +- build.gradle.kts | 26 +- src/integrationTest/compatibility.ps1 | 127 +++ .../verification/ClassRecipeVerification.java | 139 +++ .../verification/MixingVerification.java | 808 ++++++++++++++++++ .../verification/VillagerAppearanceSmoke.java | 173 ++++ .../resources/META-INF/neoforge.mods.toml | 19 + src/integrationTest/run.ps1 | 73 ++ .../astradev/cauldron/AstraCauldron.java | 89 +- .../cauldron/mixin/MixingHeatMixin.java | 28 + .../cauldron/mixin/MixingLevelMixin.java | 20 + .../cauldron/mixin/MixingStackMixin.java | 30 + .../cauldron/mixin/MixingWeatherMixin.java | 34 + .../cauldron/mixing/LiquidMixingPots.java | 467 ++++++++++ .../cauldron/mixing/MixingAnimation.java | 46 + .../cauldron/mixing/MixingAuthoring.java | 28 + .../cauldron/mixing/MixingCapabilities.java | 254 ++++++ .../cauldron/mixing/MixingConfig.java | 188 ++++ .../cauldron/mixing/MixingDisplay.java | 52 ++ .../astradev/cauldron/mixing/MixingFiles.java | 48 ++ .../astradev/cauldron/mixing/MixingHeat.java | 62 ++ .../cauldron/mixing/MixingIngredients.java | 315 +++++++ .../astradev/cauldron/mixing/MixingPots.java | 554 ++++++++++++ .../cauldron/mixing/MixingProfile.java | 36 + .../cauldron/mixing/MixingRecipes.java | 80 ++ .../astradev/cauldron/mixing/MixingRules.java | 37 + .../cauldron/mixing/MixingRuntime.java | 100 +++ .../astradev/cauldron/mixing/MixingText.java | 19 + .../resources/META-INF/neoforge.mods.toml | 4 +- src/main/resources/astracauldron.mixins.json | 12 + .../astradev/cauldron/AstraCauldronTest.java | 39 + .../mixing/ConfigurationPolicyTest.java | 44 + .../cauldron/mixing/IngredientUpdateTest.java | 27 + .../cauldron/mixing/MixingAnimationTest.java | 73 ++ .../cauldron/mixing/MixingAuthoringTest.java | 73 ++ .../cauldron/mixing/MixingConfigTest.java | 51 ++ .../cauldron/mixing/MixingFixtures.java | 19 + .../cauldron/mixing/MixingLifecycleTest.java | 26 + .../cauldron/mixing/MixingRulesTest.java | 67 ++ .../cauldron/mixing/MixingRuntimeTest.java | 64 ++ .../cauldron/mixing/MixingTextTest.java | 18 + 41 files changed, 4385 insertions(+), 16 deletions(-) create mode 100644 src/integrationTest/compatibility.ps1 create mode 100644 src/integrationTest/java/online/astradev/cauldron/mixing/verification/ClassRecipeVerification.java create mode 100644 src/integrationTest/java/online/astradev/cauldron/mixing/verification/MixingVerification.java create mode 100644 src/integrationTest/java/online/astradev/cauldron/mixing/verification/VillagerAppearanceSmoke.java create mode 100644 src/integrationTest/resources/META-INF/neoforge.mods.toml create mode 100644 src/integrationTest/run.ps1 create mode 100644 src/main/java/online/astradev/cauldron/mixin/MixingHeatMixin.java create mode 100644 src/main/java/online/astradev/cauldron/mixin/MixingLevelMixin.java create mode 100644 src/main/java/online/astradev/cauldron/mixin/MixingStackMixin.java create mode 100644 src/main/java/online/astradev/cauldron/mixin/MixingWeatherMixin.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/LiquidMixingPots.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingAnimation.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingAuthoring.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingCapabilities.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingConfig.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingDisplay.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingFiles.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingHeat.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingIngredients.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingPots.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingProfile.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingRecipes.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingRules.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingRuntime.java create mode 100644 src/main/java/online/astradev/cauldron/mixing/MixingText.java create mode 100644 src/main/resources/astracauldron.mixins.json create mode 100644 src/test/java/online/astradev/cauldron/AstraCauldronTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/ConfigurationPolicyTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/IngredientUpdateTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingAnimationTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingAuthoringTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingConfigTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingFixtures.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingLifecycleTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingRulesTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingRuntimeTest.java create mode 100644 src/test/java/online/astradev/cauldron/mixing/MixingTextTest.java diff --git a/README.md b/README.md index 844d372..95de2c2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # AstraCauldron -Исходные данные стартового набора смешивания для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**. -Runtime находится в общем capability `mixing` **AstraPlus 0.9.9+**; отдельный AstraCauldron -содержит только совместимую идентичность мода и не добавляет обработчиков или mixin. +Серверный мод котлов и смешивания для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**. +Начиная с AstraCauldron **0.3.6**, обработчики, сохранения и четыре необходимых mixin +находятся здесь, а не в ядре **AstraPlus 0.9.12+**. Общий API рецептов и цветной воды +предоставляет AstraPlus. Обновлять ядро и прежнюю оболочку AstraCauldron 0.3.5 нужно +совместно; несовместимая пара отклоняется загрузчиком до открытия мира. Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks. Модели супа зарегистрированы через AstraPlus и берутся из JAR. Пользовательские замены можно положить в `astraplus/resources/assets/astradev_soups`; мод не переписывает их. @@ -158,14 +160,26 @@ Minecraft и мода не является общей транзакцией с другими модами действия уважаются. Внешняя замена блока очищает состояние при проверке. ```powershell -cd ../AstraPlus -.\gradlew.bat build mixingTestJar -pwsh -File src/mixingTest/run.ps1 +.\gradlew.bat build +.\gradlew.bat integrationTest +.\gradlew.bat compatibilityTest -PoldCauldronJar="C:/path/to/archive/AstraCauldron-0.3.5.jar" ``` -Unit- и серверные тесты перенесены в AstraPlus. Изолированный сервер загружает только основной -AstraPlus и тестовый JAR, использует отдельные миры в build и проверяет игровой процесс и -сохранение после перезапуска. Тестовый JAR запрещено устанавливать на рабочий сервер. +Модульные и серверные тесты находятся в этом репозитории. Перед ними соберите соседний +AstraPlus. Изолированный сервер загружает AstraPlus, AstraCauldron и тестовый JAR, +использует отдельные миры в `build` и проверяет игровой процесс и сохранение после +перезапуска. Используются библиотеки NeoForge и копия уже принятой владельцем EULA +из рабочего сервера, не его миры или настройки. `compatibilityTest` требует именно +отказа по версии 0.3.5, а не произвольной ошибки старта. Тестовый JAR запрещено +устанавливать на рабочий сервер. + +Без AstraCauldron ядро не подключает смешивание и не меняет размеры стопок супов; +сохранённые данные и конфигурация модуля остаются на диске без перезаписи. Runtime +запускается после публикации API ядра, но до загрузки сущностей мира, чтобы прежние +служебные отображения правильно восстанавливались. Доступность станции `cauldron` +объявляется через `RecipeStationRuntimes` только после успешного старта и снимается +перед остановкой. Без исполнителя редактор запрещает включать рецепт, но позволяет +его отключить. Это ещё не полная реализация алгоритма котлов редактируемыми узлами. ## Настройки diff --git a/build.gradle.kts b/build.gradle.kts index 907c670..fd57569 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,12 +3,12 @@ plugins { id("net.neoforged.moddev") version "2.0.146" } group = "online.astradev" -version = "0.3.5" +version = "0.3.6" repositories { mavenCentral() } val astraPlusApi = providers.gradleProperty("astraPlusApi") - .orElse("../AstraPlus/build/libs/AstraPlus-0.9.9-api.jar") + .orElse("../AstraPlus/build/libs/AstraPlus-0.9.12-api.jar") val astraPlusRuntime = providers.gradleProperty("astraPlusRuntime") - .orElse("../AstraPlus/build/libs/AstraPlus-0.9.9.jar") + .orElse("../AstraPlus/build/libs/AstraPlus-0.9.12.jar") dependencies { compileOnly(files(astraPlusApi)) testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") @@ -39,3 +39,23 @@ 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 + files(astraPlusRuntime) + 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") +} + +tasks.register("compatibilityTest") { + commandLine("pwsh", "-NoProfile", "-File", "src/integrationTest/compatibility.ps1") + providers.gradleProperty("oldCauldronJar").orNull?.let { args("-OldCauldronJar", it) } +} diff --git a/src/integrationTest/compatibility.ps1 b/src/integrationTest/compatibility.ps1 new file mode 100644 index 0000000..9db38f4 --- /dev/null +++ b/src/integrationTest/compatibility.ps1 @@ -0,0 +1,127 @@ +param( + [string]$ServerRoot = 'C:\Users\ScarPC\Documents\NeoForge Server 26.2', + [string]$PlusJar, + [string]$OldCauldronJar, + [ValidateRange(10, 180)][int]$TimeoutSeconds = 90 +) + +$ErrorActionPreference = 'Stop' +$project = (Resolve-Path -LiteralPath "$PSScriptRoot/../..").Path +$runtime = (Resolve-Path -LiteralPath $ServerRoot).Path +$plusRoot = Join-Path (Split-Path $project -Parent) 'AstraPlus' +if (!$PlusJar) { $PlusJar = Join-Path $plusRoot 'build/libs/AstraPlus-0.9.12.jar' } +if (!$OldCauldronJar) { $OldCauldronJar = Join-Path $runtime 'mods/AstraCauldron-0.3.5.jar' } +$plus = (Get-Item -LiteralPath $PlusJar).FullName +$oldCauldron = (Get-Item -LiteralPath $OldCauldronJar).FullName +$acceptedEula = Join-Path $runtime 'eula.txt' +if (!(Test-Path -LiteralPath $acceptedEula) -or + !(Select-String -LiteralPath $acceptedEula -Pattern '^eula=true\s*$' -Quiet)) { + throw 'The server owner must have accepted the Minecraft EULA before this test can run.' +} + +# Verify the inputs rather than treating an unrelated startup failure as a pass. +Add-Type -AssemblyName System.IO.Compression.FileSystem +function Read-ModMetadata([string]$Path) { + $archive = [IO.Compression.ZipFile]::OpenRead($Path) + try { + $entry = $archive.GetEntry('META-INF/neoforge.mods.toml') + if (!$entry) { throw "Missing mod metadata: $Path" } + $reader = [IO.StreamReader]::new($entry.Open()) + try { return $reader.ReadToEnd() } finally { $reader.Dispose() } + } finally { $archive.Dispose() } +} +function Assert-ModVersion([string]$Metadata, [string]$Id, [string]$Version, [string]$Path) { + $pattern = '(?ms)^\[\[mods\]\]\s*modId\s*=\s*"' + [regex]::Escape($Id) + + '"\s*version\s*=\s*"' + [regex]::Escape($Version) + '"' + if ($Metadata -notmatch $pattern) { throw "Expected $Id $Version in $Path" } +} +$plusMetadata = Read-ModMetadata $plus +Assert-ModVersion $plusMetadata 'astraplus' '0.9.12' $plus +Assert-ModVersion (Read-ModMetadata $oldCauldron) 'astracauldron' '0.3.5' $oldCauldron +$dependencyBlocks = [regex]::Matches($plusMetadata, '(?ms)^\[\[dependencies\.astraplus\]\]\s*(.*?)(?=^\[|\z)') +$cauldronDependency = @($dependencyBlocks | Where-Object { $_.Groups[1].Value -match '(?m)^modId\s*=\s*"astracauldron"\s*$' }) +if ($cauldronDependency.Count -ne 1 -or + $cauldronDependency[0].Groups[1].Value -notmatch '(?m)^type\s*=\s*"optional"\s*$' -or + $cauldronDependency[0].Groups[1].Value -notmatch '(?m)^versionRange\s*=\s*"\[0\.3\.6,\)"\s*$') { + throw "Expected optional AstraCauldron [0.3.6,) dependency in $plus" +} + +$output = Join-Path $project ('build/compatibility-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + [guid]::NewGuid().ToString('N').Substring(0, 8)) +New-Item -ItemType Directory -Path "$output/mods", "$output/config" | Out-Null +Copy-Item -LiteralPath $acceptedEula -Destination "$output/eula.txt" +Copy-Item -LiteralPath $plus, $oldCauldron -Destination "$output/mods" +$libraryRoot = $runtime.Replace('\', '/') +$argsFile = Join-Path $runtime 'libraries/net/neoforged/neoforge/26.2.0.79/win_args.txt' +$lines = (Get-Content -Raw -LiteralPath $argsFile).Replace('libraries/', "$libraryRoot/libraries/") -split "`r?`n" +for ($i = 0; $i -lt $lines.Length; $i++) { + if ($lines[$i].StartsWith('-DlibraryDirectory=')) { $lines[$i] = '"-DlibraryDirectory=' + $libraryRoot + '/libraries"' } + if ($i -gt 0 -and $lines[$i - 1] -eq '-classpath') { $lines[$i] = '"' + $lines[$i] + '"' } +} +$lines | Set-Content -LiteralPath "$output/server-args.txt" +# Even an unexpectedly successful startup must not compete for production/test ports. +@' +server-ip=127.0.0.1 +server-port=0 +online-mode=false +level-name=compatibility-world +enable-query=false +enable-rcon=false +max-tick-time=30000 +'@ | Set-Content -LiteralPath "$output/server.properties" +'{"build":{"onStartup":false},"astraPacks":{"enabled":false},"editor":{"enabled":false}}' | + Set-Content -LiteralPath "$output/config/astraplus.json" + +$java = if ($env:JAVA_HOME) { Join-Path $env:JAVA_HOME 'bin/java.exe' } else { (Get-Command java -CommandType Application | Select-Object -First 1).Source } +$start = [Diagnostics.ProcessStartInfo]::new() +$start.FileName = $java +$start.WorkingDirectory = $output +$start.UseShellExecute = $false +$start.CreateNoWindow = $true +$start.RedirectStandardOutput = $true +$start.RedirectStandardError = $true +foreach ($argument in @('-Xmx1G', '@server-args.txt', 'nogui')) { $start.ArgumentList.Add($argument) } +$process = [Diagnostics.Process]::new() +$process.StartInfo = $start +$started = $false +try { + $started = $process.Start() + if (!$started) { throw 'Failed to start the isolated compatibility-test JVM.' } + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + $timer = [Diagnostics.Stopwatch]::StartNew() + while (!$process.WaitForExit(1000)) { + if ($timer.Elapsed.TotalSeconds -ge $TimeoutSeconds) { + $process.Kill($true) + $process.WaitForExit() + $stdout.GetAwaiter().GetResult() | Set-Content -LiteralPath "$output/stdout.log" + $stderr.GetAwaiter().GetResult() | Set-Content -LiteralPath "$output/stderr.log" + throw "Timed out after ${TimeoutSeconds}s; stopped only the test JVM. Evidence: $output" + } + } + $exitCode = $process.ExitCode + $outText = $stdout.GetAwaiter().GetResult() + $errText = $stderr.GetAwaiter().GetResult() + $outText | Set-Content -LiteralPath "$output/stdout.log" + $errText | Set-Content -LiteralPath "$output/stderr.log" + $log = $outText + "`n" + $errText + if ($exitCode -eq 0) { throw "Incompatible mods unexpectedly exited successfully. Evidence: $output" } + $dependencyError = "(?s)Mod ID: 'astracauldron', Requested by: 'astraplus', Expected range: '\[0\.3\.6,\)', Actual version: '0\.3\.5'" + $translatedError = '(?is)Mod astraplus only supports astracauldron 0\.3\.6 or above\s*Currently,? astracauldron is 0\.3\.5' + if ($log -notmatch $dependencyError -and $log -notmatch $translatedError) { + throw "Failure was not the expected AstraPlus -> AstraCauldron [0.3.6,) / actual 0.3.5 dependency rejection. Evidence: $output" + } + if ((Test-Path -LiteralPath "$output/compatibility-world") -or (Test-Path -LiteralPath "$output/world") -or + $log -match 'Preparing level|Preparing start region|Done \([\d.,]+s\)!') { + throw "Loader opened a world despite incompatible mods. Evidence: $output" + } + $result = "PASS compatibility: AstraPlus 0.9.12 rejects AstraCauldron 0.3.5 for [0.3.6,), exit=$exitCode, no world opened" + $result | Set-Content -LiteralPath "$output/verification-result.txt" + Write-Output $result + Write-Output "Evidence: $output" +} finally { + if ($started -and !$process.HasExited) { + $process.Kill($true) + $process.WaitForExit() + } + $process.Dispose() +} diff --git a/src/integrationTest/java/online/astradev/cauldron/mixing/verification/ClassRecipeVerification.java b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/ClassRecipeVerification.java new file mode 100644 index 0000000..64893a8 --- /dev/null +++ b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/ClassRecipeVerification.java @@ -0,0 +1,139 @@ +package online.astradev.cauldron.mixing.verification; + +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.component.DataComponents; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.alchemy.PotionContents; +import net.minecraft.world.item.alchemy.Potions; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.CampfireBlock; +import net.minecraft.world.level.block.LayeredCauldronBlock; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.common.util.FakePlayerFactory; +import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; +import online.astradev.cauldron.mixing.LiquidMixingPots; +import online.astradev.cauldron.mixing.MixingCapabilities; +import online.astradev.cauldron.mixing.MixingRecipes; +import online.astradev.plus.api.AstraPlusApi; +import online.astradev.plus.api.content.ContentRegistry; +import online.astradev.plus.api.content.Item; +import online.astradev.plus.api.content.Recipe; +import online.astradev.plus.api.content.Recipe.Heat; +import online.astradev.plus.api.content.Recipe.Station; + +/** Class-API execution belongs in the test of the module that implements the station. */ +final class ClassRecipeVerification { + private ClassRecipeVerification() {} + + static void register() { + var content = new ContentRegistry("cauldronverify"); + content.item("ruby", new Item() {{ + name("Cauldron test ruby"); + texture("minecraft:item/diamond"); + stackSize(16); + }}); + content.recipe("soul", new Recipe(Station.CAULDRON) {{ + input("cauldronverify:ruby", 2); + liquid("water", 3, 1); + heat(Heat.SOUL_CAMPFIRE); + color(0xE04488); + result("minecraft:emerald", 1); + }}); + content.recipe("dyed", new Recipe(Station.CAULDRON) {{ + input("minecraft:amethyst_shard"); + liquid("dyed_water", 2, 1); + heat(Heat.ANY); + result("minecraft:diamond", 1); + }}); + content.recipe("potion", new Recipe(Station.CAULDRON) {{ + input("minecraft:amethyst_shard"); + liquid("minecraft:healing", 1, 1); + result("minecraft:emerald", 1); + }}); + } + + static void verify(MinecraftServer server, ServerLevel level) throws Exception { + var pos = new BlockPos(8, 100, 0); + var player = FakePlayerFactory.getMinecraft(level); + player.setGameMode(GameType.SURVIVAL); + player.getInventory().clearContent(); + player.setPos(8.5, 100, 1.5); + MixingCapabilities.liquids().breakPot(level, pos); + level.setBlock( + pos, + Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL, 3), + 3); + player.setItemInHand( + InteractionHand.MAIN_HAND, AstraPlusApi.current().orElseThrow().create(Identifier.parse("cauldronverify:ruby"), 2)); + level.setBlock(pos.below(), Blocks.CAMPFIRE.defaultBlockState(), 3); + require( + !MixingRecipes.interact(player, pos, InteractionHand.MAIN_HAND), + "Wrong heat rejects recipe"); + require(player.getMainHandItem().getCount() == 2, "Rejected recipe consumes nothing"); + level.setBlock( + pos.below(), + Blocks.SOUL_CAMPFIRE.defaultBlockState().setValue(CampfireBlock.LIT, false), + 3); + require( + !MixingRecipes.interact(player, pos, InteractionHand.MAIN_HAND), + "Unlit soul campfire rejects recipe"); + level.setBlock(pos.below(), Blocks.SOUL_CAMPFIRE.defaultBlockState(), 3); + var denied = click(player, pos); + denied.setCanceled(true); + NeoForge.EVENT_BUS.post(denied); + require(player.getMainHandItem().getCount() == 2 + && !MixingCapabilities.liquids().contains(level, pos) + && level.getBlockState(pos).getValue(LayeredCauldronBlock.LEVEL) == 3, + "Cancelled class recipe right-click consumes neither item nor liquid"); + var accepted = NeoForge.EVENT_BUS.post(click(player, pos)); + require(accepted.isCanceled(), "Soul campfire class recipe consumes handled right-click"); + require( + player.getMainHandItem().is(Items.EMERALD), + "Recipe output and exact input consumption"); + var liquid = MixingCapabilities.liquids().get(level, pos); + require( + liquid != null && liquid.levels() == 2 && liquid.rgb() == 0xE04488, + "Recipe liquid cost and color"); + var reopened = new LiquidMixingPots(server); + require( + reopened.get(level, pos).equals(liquid), + "Colored recipe liquid persists on reload"); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.AMETHYST_SHARD)); + require( + MixingRecipes.interact(player, pos, InteractionHand.MAIN_HAND), + "Dyed water is an independent recipe source"); + require(MixingCapabilities.liquids().get(level, pos).levels() == 1, "Saved liquid consumption"); + MixingCapabilities.liquids().breakPot(level, pos); + level.setBlock(pos, Blocks.CAULDRON.defaultBlockState(), 3); + ItemStack potion = new ItemStack(Items.POTION); + potion.set(DataComponents.POTION_CONTENTS, new PotionContents(Potions.HEALING)); + player.setItemInHand(InteractionHand.MAIN_HAND, potion); + require( + MixingCapabilities.liquids().interact(player, pos, InteractionHand.MAIN_HAND), + "Potion source stored"); + player.setItemInHand(InteractionHand.MAIN_HAND, new ItemStack(Items.AMETHYST_SHARD)); + require( + MixingRecipes.interact(player, pos, InteractionHand.MAIN_HAND), + "Potion ID matches cauldron recipe"); + require(!MixingCapabilities.liquids().contains(level, pos), "Last potion level consumed"); + } + + private static PlayerInteractEvent.RightClickBlock click(ServerPlayer player, BlockPos pos) { + return new PlayerInteractEvent.RightClickBlock(player, InteractionHand.MAIN_HAND, pos, + new BlockHitResult(Vec3.atCenterOf(pos), Direction.UP, pos, false)); + } + + private static void require(boolean value, String message) { + if (!value) throw new AssertionError(message); + } +} diff --git a/src/integrationTest/java/online/astradev/cauldron/mixing/verification/MixingVerification.java b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/MixingVerification.java new file mode 100644 index 0000000..efd54fb --- /dev/null +++ b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/MixingVerification.java @@ -0,0 +1,808 @@ +package online.astradev.cauldron.mixing.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.mixing.*; +import online.astradev.plus.api.*; +import online.astradev.plus.api.editor.EditorDefinitions; + +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 MixingVerification { + 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 MixingVerification() { + if (!Boolean.getBoolean("astracauldron.isolatedVerification")) + throw new IllegalStateException("Isolated verification flag required"); + ClassRecipeVerification.register(); + 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) { + checkModuleBoundary(server); + 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( + MixingCapabilities.pots().get(level, READY).servings() == 2, + "ready servings restored"); + require( + MixingCapabilities.pots().get(level, RAW).items().size() == 1, + "raw ingredient restored"); + require( + MixingCapabilities.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 = MixingCapabilities.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( + MixingCapabilities.liquids().get(level, new BlockPos(26, 100, 8)).levels() + == 2, + "dyed water volume survives restart"); + VillagerAppearanceSmoke.verifyRestartAndDiscard(level); + require(true, "native villager appearance survives restart without duplicate overlays"); + } + if (tick == 20) { + VillagerAppearanceSmoke.verifyCleanup(level); + require(true, "native villager overlay cleanup"); + } + if (tick == 110) { + require( + MixingCapabilities.pots().get(level, BREW).brewTicks() == 0, + "restored brew finishes"); + use(READY, new ItemStack(Items.BOWL)); + use(READY, new ItemStack(Items.BOWL)); + require( + MixingCapabilities.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) { + ClassRecipeVerification.verify(server, level); + require(true, "class API cauldron recipes preserve heat, liquid source, color and persistence"); + VillagerAppearanceSmoke.begin(server, level); + checkIngredients(server, level); + checkAuthoredRules(); + 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( + MixingCapabilities.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( + MixingCapabilities.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( + MixingCapabilities.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++) MixingCapabilities.pots().tick(); + require( + MixingCapabilities.pots().get(level, READY).brewTicks() > 0, + "removing fire pauses cooking beyond full duration"); + level.setBlock(READY.below(), Blocks.SOUL_CAMPFIRE.defaultBlockState(), 3); + require( + MixingHeat.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 == 20) { + VillagerAppearanceSmoke.verifyGameplay(level); + require(true, "native villager biome assignment, commands, AI and trades"); + } + if (tick == 30) { + VillagerAppearanceSmoke.verifyNoDuplicateAfterLiveReload(level); + require(true, "native villager live reload has no duplicate overlays"); + } + if (tick == 100) { + require( + MixingCapabilities.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( + MixingCapabilities.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( + MixingCapabilities.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, + "MixingCapabilities 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 checkModuleBoundary(MinecraftServer server) throws Exception { + var mods = net.neoforged.fml.ModList.get(); + require(mods.isLoaded("astraplus") && mods.isLoaded("astracauldron"), + "both core and cauldron implementation JARs are loaded"); + require(RecipeStationRuntimes.isAvailable("cauldron"), + "content module advertises the running cauldron station"); + var owner = online.astradev.cauldron.AstraCauldron.class + .getProtectionDomain().getCodeSource().getLocation(); + require(MixingCapabilities.class.getProtectionDomain().getCodeSource().getLocation().equals(owner), + "mixing runtime is packaged in the concrete cauldron module"); + require(!AstraPlusApi.class.getProtectionDomain().getCodeSource().getLocation().equals(owner), + "generic API remains in a separate core JAR"); + try { + Class.forName("online.astradev.plus.capability.mixing.MixingCapabilities"); + throw new AssertionError("old core mixing runtime is still bundled"); + } catch (ClassNotFoundException expected) { + require(true, "old core mixing implementation is absent"); + } + require(EditorDefinitions.find("astracauldron:combination_rules").isPresent(), + "content-owned rules retain their existing editor identity"); + for (var alias : MixingCapabilities.profile().commands()) + require(server.getCommands().getDispatcher().getRoot().getChild(alias) != null, + "compatibility command is available before first tick: " + alias); + } + + private void checkIngredients(MinecraftServer server, ServerLevel level) throws Exception { + var ingredients = MixingCapabilities.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); + MixingCapabilities.pots().register("plus_food", player, 9, 6); + require( + MixingCapabilities.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( + MixingCapabilities.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 { + MixingCapabilities.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( + MixingCapabilities.pots().ingredients().read(api.create(id, 1)).nutrition() == 9, + "invalid reload leaves previous runtime intact"); + } + + private void checkAuthoredRules() throws Exception { + var definition = EditorDefinitions.find("astracauldron:combination_rules").orElseThrow(); + var original = definition.snapshot(); + var document = JsonParser.parseString(original.documentJson()).getAsJsonObject(); + document.addProperty("ingredientCount", 2); + document.addProperty("cakeNutrition", 18); + document.addProperty("cakeSaturation", 3.6); + document.add("blockedIngredients", new JsonArray()); + document.add("incompatible", JsonParser.parseString("[[\"material:carrot\",\"material:potato\"]]")); + document.getAsJsonObject("ingredientColors").addProperty("cake", "#123456"); + var engine = document.getAsJsonObject("engine"); + engine.addProperty("carrier", "minecraft:apple"); + engine.addProperty("model", "minecraft:apple"); + engine.addProperty("remainder", "minecraft:stick"); + engine.add("normalizedItems", JsonParser.parseString("[\"minecraft:bread\"]")); + document.addProperty("soupStackSize", 8); + try { + definition.save(document.toString(), original.revision()); + var current = MixingCapabilities.pots().ingredients(); + require(current.read(new ItemStack(Items.CAKE)).nutrition() == 18, + "authored native config immediately changes ingredient nutrition"); + require(current.rejection(List.of(new ItemStack(Items.CARROT), new ItemStack(Items.POTATO))) != null, + "authored combination rules reject the current runtime recipe"); + var soup = current.brew(List.of(new ItemStack(Items.CAKE), new ItemStack(Items.CAKE))); + require(soup.is(Items.APPLE) + && soup.get(DataComponents.ITEM_MODEL).equals(Identifier.parse("minecraft:apple")) + && soup.getMaxStackSize() == 8 + && soup.get(DataComponents.USE_REMAINDER).convertInto().create().is(Items.STICK), + "authored carrier, model, stack limit and remainder reach the native output"); + require(new ItemStack(Items.BREAD).getMaxStackSize() == 8, + "generic stack mixin reads authored normalization targets"); + require(soup.get(DataComponents.FOOD).nutrition() == 36 + && Math.abs(soup.get(DataComponents.FOOD).saturation() - 7.2f) < .001f + && MixingIngredients.color(soup) == 0x123456, + "authored ingredient count, nutrition, saturation and palette reach the real soup stack"); + try { + definition.save(original.documentJson(), original.revision()); + throw new AssertionError("stale authored revision accepted"); + } catch (online.astradev.plus.api.editor.FileEditorDefinition.Conflict expected) { + require(MixingCapabilities.pots().ingredients() == current, + "stale editor save preserves live ingredients"); + } + } finally { + definition.save(original.documentJson(), definition.snapshot().revision()); + } + require(MixingCapabilities.pots().ingredients().read(new ItemStack(Items.CAKE)).nutrition() == 14, + "restoring authored native config restores default runtime behavior"); + } + + 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( + MixingCapabilities.pots().get(level, pos) == null + && player.getMainHandItem().getCount() == 2, + "cancelled interaction is respected"); + NeoForge.EVENT_BUS.post(click(pos)); + require( + MixingCapabilities.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( + MixingCapabilities.pots().get(level, pos) != null, + "cancelled breaking preserves ingredients"); + use(pos, ItemStack.EMPTY); + require( + MixingCapabilities.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(MixingCapabilities.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( + MixingCapabilities.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 + && !MixingCapabilities.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)) { + MixingCapabilities.liquids().breakPot(level, pos); + fill(level, pos); + use(pos, dye.copyWithCount(2)); + require( + player.getMainHandItem().getCount() == 1 + && MixingCapabilities.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( + MixingCapabilities.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( + MixingCapabilities.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) + && MixingCapabilities.liquids().get(level, pos).levels() == 2, + "non-leather armor rejected without water loss"); + MixingCapabilities.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( + MixingCapabilities.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 + && MixingCapabilities.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 + && MixingCapabilities.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 + && !MixingCapabilities.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 + && !MixingCapabilities.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 + && !MixingCapabilities.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}) { + MixingCapabilities.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 = MixingCapabilities.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"); + MixingCapabilities.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/java/online/astradev/cauldron/mixing/verification/VillagerAppearanceSmoke.java b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/VillagerAppearanceSmoke.java new file mode 100644 index 0000000..4f2a311 --- /dev/null +++ b/src/integrationTest/java/online/astradev/cauldron/mixing/verification/VillagerAppearanceSmoke.java @@ -0,0 +1,173 @@ +package online.astradev.cauldron.mixing.verification; + +import java.util.List; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.entity.Display; +import net.minecraft.world.entity.EntitySpawnReason; +import net.minecraft.world.entity.EntityTypes; +import net.minecraft.world.entity.npc.villager.Villager; +import net.minecraft.world.entity.npc.villager.VillagerProfession; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; +import net.minecraft.world.item.trading.ItemCost; +import net.minecraft.world.item.trading.MerchantOffer; +import net.minecraft.world.phys.AABB; +import online.astradev.plus.api.editor.EditorDefinitions; + +/** Focused two-launch smoke for the native-villager appearance capability. */ +final class VillagerAppearanceSmoke { + private static final BlockPos AUTO = new BlockPos(8, 100, 14); + private static final BlockPos SPAWNED = new BlockPos(16, 100, 14); + private static final BlockPos APPLIED = new BlockPos(24, 100, 14); + private static final String AUTO_TAG = "verify_villager_auto"; + private static final String SPAWN_TAG = "verify_villager_spawn"; + private static final String APPLY_TAG = "verify_villager_apply"; + private static final String VARIANT_TAG = "astraplus:villager_variant"; + private static final String CHECKED_TAG = "astraplus:villager_checked"; + private static final String DISPLAY_TAG = "astraplus:villager_clothes"; + private static final String VARIANT = "astraplus:cherry"; + + private static Villager authored; + private static Object brain; + private static Object villagerData; + private static Object offers; + private static MerchantOffer sentinel; + private static float health; + private static float width; + private static float height; + + private VillagerAppearanceSmoke() {} + + static void begin(MinecraftServer server, ServerLevel level) { + command(server, "fillbiome 7 96 13 9 104 15 minecraft:cherry_grove"); + String biome = level.getBiome(AUTO).unwrapKey().orElseThrow().identifier().toString(); + check(biome.equals("minecraft:cherry_grove"), "native join occurs in cherry_grove"); + + authored = EntityTypes.VILLAGER.create(level, EntitySpawnReason.COMMAND); + check(authored != null, "native villager factory"); + authored.setPos(AUTO.getX() + .5, AUTO.getY(), AUTO.getZ() + .5); + authored.setNoAi(true); + authored.addTag(AUTO_TAG); + var farmer = BuiltInRegistries.VILLAGER_PROFESSION + .get(Identifier.parse("minecraft:farmer")).orElseThrow(); + authored.setVillagerData(authored.getVillagerData().withProfession(farmer).withLevel(3)); + authored.setHealth(13); + sentinel = new MerchantOffer(new ItemCost(Items.EMERALD, 2), new ItemStack(Items.BREAD, 3), 7, 4, .05f); + authored.getOffers().add(sentinel); + brain = authored.getBrain(); + villagerData = authored.getVillagerData(); + offers = authored.getOffers(); + health = authored.getHealth(); + width = authored.getBbWidth(); + height = authored.getBbHeight(); + check(level.addFreshEntity(authored), "native villager joins the world"); + + command(server, "execute positioned 16.5 100 14.5 run astraplus villager spawn " + VARIANT); + Villager spawned = villagers(level, SPAWNED, 2).stream() + .filter(value -> !value.entityTags().contains(AUTO_TAG)).findFirst().orElseThrow(); + spawned.addTag(SPAWN_TAG); + spawned.setNoAi(true); + check(variant(spawned).equals(VARIANT), + "villager spawn command is registered before server start"); + + Villager applied = EntityTypes.VILLAGER.create(level, EntitySpawnReason.COMMAND); + check(applied != null, "second native villager factory"); + applied.setPos(APPLIED.getX() + .5, APPLIED.getY(), APPLIED.getZ() + .5); + applied.setNoAi(true); + applied.addTag(APPLY_TAG); + check(level.addFreshEntity(applied), "apply-command villager joins the world"); + command(server, "astraplus villager apply @e[tag=" + APPLY_TAG + ",limit=1] " + VARIANT); + check(variant(applied).equals(VARIANT), + "villager apply command resolves the active generic policy"); + } + + static void verifyGameplay(ServerLevel level) throws Exception { + check(authored != null && !authored.isRemoved(), "authored native villager remains loaded"); + check(authored.getType() == EntityTypes.VILLAGER && authored.getClass() == Villager.class, + "appearance keeps the vanilla entity class and type"); + check(authored.isNoAi(), "appearance leaves the native AI flag unchanged"); + check(authored.getBrain() == brain, "appearance leaves the native brain unchanged"); + check(authored.getVillagerData().equals(villagerData), "appearance leaves profession and level unchanged"); + check(authored.getOffers() == offers && authored.getOffers().contains(sentinel), + "appearance leaves the native trade list unchanged"); + check(authored.getHealth() == health + && authored.getBbWidth() == width && authored.getBbHeight() == height, + "appearance leaves health and collision unchanged"); + check(variant(authored).equals(VARIANT) + && authored.getPersistentData().getBooleanOr(CHECKED_TAG, false), + "new native villager receives one persistent biome assignment"); + check(overlays(level, authored).size() == 5, "adult native villager has five transient clothing parts"); + check(overlays(level, authored).stream().noneMatch(Display::shouldBeSaved), + "villager clothing never persists as standalone entities"); + check(villagers(level, SPAWNED, 3).stream().anyMatch(v -> v.entityTags().contains(SPAWN_TAG) + && variant(v).equals(VARIANT) && overlays(level, v).size() == 5), + "spawn command creates a native dressed villager"); + check(villagers(level, APPLIED, 3).stream().anyMatch(v -> v.entityTags().contains(APPLY_TAG) + && variant(v).equals(VARIANT) && overlays(level, v).size() == 5), + "apply command dresses an existing native villager"); + + var provider = EditorDefinitions.find("astraplus:villager_appearance").orElseThrow(); + var snapshot = provider.snapshot(); + provider.save(snapshot.documentJson(), snapshot.revision()); + } + + static void verifyNoDuplicateAfterLiveReload(ServerLevel level) { + check(overlays(level, authored).size() == 5, + "live FILE reload keeps one clothing set on the existing villager"); + } + + static void verifyRestartAndDiscard(ServerLevel level) { + var all = level.getEntitiesOfClass(Villager.class, new AABB(6, 96, 12, 28, 106, 17)); + check(all.size() == 3, "three native villagers survive restart"); + Villager restored = all.stream().filter(v -> v.entityTags().contains(AUTO_TAG)).findFirst().orElseThrow(); + check(restored.getType() == EntityTypes.VILLAGER && restored.getClass() == Villager.class, + "restart preserves the native villager entity"); + check(restored.isNoAi(), "restart preserves the native AI flag"); + check(restored.getVillagerData().profession().is(VillagerProfession.FARMER) + && restored.getVillagerData().level() == 3, + "restart preserves profession and level"); + check(restored.getOffers().stream().anyMatch(offer -> offer.getResult().is(Items.BREAD) + && offer.getResult().getCount() == 3 && offer.getMaxUses() == 7), + "restart preserves the native authored trade"); + for (Villager villager : all) { + check(variant(villager).equals(VARIANT) + && villager.getPersistentData().getBooleanOr(CHECKED_TAG, false), + "restart preserves appearance identity on the owner"); + check(overlays(level, villager).size() == 5, + "restart restores one transient clothing set without duplicates"); + villager.discard(); + } + } + + static void verifyCleanup(ServerLevel level) { + check(level.getEntitiesOfClass(Display.ItemDisplay.class, + new AABB(6, 96, 12, 28, 106, 17), + display -> display.entityTags().contains(DISPLAY_TAG)).isEmpty(), + "removing native owners cleans every clothing display"); + } + + private static void command(MinecraftServer server, String command) { + server.getCommands().performPrefixedCommand(server.createCommandSourceStack(), command); + } + + private static List villagers(ServerLevel level, BlockPos position, double radius) { + return level.getEntitiesOfClass(Villager.class, new AABB(position).inflate(radius)); + } + + private static List overlays(ServerLevel level, Villager owner) { + return level.getEntitiesOfClass(Display.ItemDisplay.class, owner.getBoundingBox().inflate(2), + display -> display.entityTags().contains(DISPLAY_TAG)); + } + + private static String variant(Villager villager) { + return villager.getPersistentData().getString(VARIANT_TAG).orElse(""); + } + + private static void check(boolean value, String message) { + if (!value) throw new AssertionError(message); + } +} diff --git a/src/integrationTest/resources/META-INF/neoforge.mods.toml b/src/integrationTest/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..3adfbe7 --- /dev/null +++ b/src/integrationTest/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,19 @@ +modLoader="javafml" +loaderVersion="[11,)" +license="All Rights Reserved" +[[mods]] +modId="astracauldron_verify" +version="1.0.0" +displayName="AstraCauldron isolated mixing verification" +[[dependencies.astracauldron_verify]] +modId="astraplus" +type="required" +versionRange="[0.9.12,0.10)" +ordering="AFTER" +side="SERVER" +[[dependencies.astracauldron_verify]] +modId="astracauldron" +type="required" +versionRange="[0.3.6,0.4)" +ordering="AFTER" +side="SERVER" diff --git a/src/integrationTest/run.ps1 b/src/integrationTest/run.ps1 new file mode 100644 index 0000000..0da7672 --- /dev/null +++ b/src/integrationTest/run.ps1 @@ -0,0 +1,73 @@ +param( + [string]$ServerDirectory = 'C:/Users/ScarPC/Documents/NeoForge Server 26.2', + [string]$Java = 'java', + [ValidateRange(1024, 65535)][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 = if ($PlusDirectory) { (Resolve-Path -LiteralPath $PlusDirectory).Path } else { + (Resolve-Path -LiteralPath (Join-Path (Split-Path $repo -Parent) 'AstraPlus')).Path +} +$serverRoot = (Resolve-Path -LiteralPath $ServerDirectory).Path.Replace('\','/') +$acceptedEula = Join-Path $serverRoot 'eula.txt' +if (!(Test-Path -LiteralPath $acceptedEula -PathType Leaf) -or + !(Select-String -LiteralPath $acceptedEula -Pattern '^eula=true\s*$' -Quiet)) { + throw 'The server owner must have accepted the Minecraft EULA before integration tests can run.' +} +$plusVersion = [regex]::Match((Get-Content "$plus/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value +$version = [regex]::Match((Get-Content "$repo/build.gradle.kts" -Raw), '(?m)^version = "([^"]+)"').Groups[1].Value +if (!$plusVersion -or !$version) { throw 'Cannot resolve the exact built mod versions.' } +$jars = @( + "$plus/build/libs/AstraPlus-$plusVersion.jar", + "$repo/build/libs/AstraCauldron-$version.jar", + "$repo/build/libs/AstraCauldron-$version-integration-tests.jar" +) +foreach ($jar in $jars) { + if (!(Test-Path -LiteralPath $jar -PathType Leaf)) { throw "Build required JAR first: $jar" } +} +$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'), (Join-Path $run 'config') | Out-Null +foreach ($jar in $jars) { Copy-Item -LiteralPath $jar -Destination (Join-Path $run 'mods') } +Copy-Item -LiteralPath $acceptedEula -Destination (Join-Path $run 'eula.txt') +$argsLines = Get-Content -LiteralPath "$serverRoot/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)) +$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 mixing verification +"@ +[IO.File]::WriteAllText((Join-Path $run 'server.properties'), $properties) +[IO.File]::WriteAllText((Join-Path $run 'config/astraplus.json'), '{"build":{"onStartup":true},"astraPacks":{"enabled":false},"editor":{"enabled":false}}') +Set-Content -LiteralPath "$repo/build/active-verification.txt" -Value $run +Write-Output "Isolated verification: $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" } + if (Select-String -LiteralPath "$phase.log" -Pattern 'Exception stopping the server|Encountered an unexpected exception|Failed to save chunk|Mixin apply failed' -Quiet) { + throw "Server lifecycle 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 a48e4c7..390918e 100644 --- a/src/main/java/online/astradev/cauldron/AstraCauldron.java +++ b/src/main/java/online/astradev/cauldron/AstraCauldron.java @@ -1,13 +1,96 @@ package online.astradev.cauldron; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import net.neoforged.bus.api.EventPriority; import net.neoforged.api.distmarker.Dist; import net.neoforged.fml.common.Mod; +import net.neoforged.fml.loading.FMLPaths; +import net.neoforged.neoforge.common.NeoForge; +import net.neoforged.neoforge.event.server.ServerAboutToStartEvent; +import net.neoforged.neoforge.event.server.ServerStoppedEvent; +import net.neoforged.neoforge.event.server.ServerStoppingEvent; + +import online.astradev.cauldron.mixing.MixingCapabilities; +import online.astradev.plus.api.AstraPlusApi; +import online.astradev.plus.api.RecipeStationRuntimes; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; /** - * Legacy mod identity only. Authored starter resources are assembled into AstraPlus; - * the generic mixing capability owns all runtime listeners, persistence and mixins. + * Owns cauldron gameplay, persistence and the narrowly scoped vanilla hooks it requires. + * AstraPlus supplies reusable item, recipe, editor and colored-water services only. */ @Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER) public final class AstraCauldron { - public AstraCauldron() {} + private static final int POLICY_RESOURCE_LIMIT = 512 * 1024; + private final String defaults; + private final String schema; + private final JsonObject compatibility; + private RecipeStationRuntimes.Registration station; + + public AstraCauldron() { + try { + defaults = resource("defaults"); + schema = resource("schema"); + compatibility = JsonParser.parseString(resource("compatibility")).getAsJsonObject(); + } catch (IOException failure) { + throw new IllegalStateException("Cannot read AstraCauldron policy", failure); + } + // Minecraft constructs its command dispatcher before ServerStartingEvent. + // This immutable identity is available early without requiring the runtime API. + MixingCapabilities.declareCompatibility(compatibility); + MixingCapabilities.register(NeoForge.EVENT_BUS); + NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::start); + NeoForge.EVENT_BUS.addListener(this::stopping); + NeoForge.EVENT_BUS.addListener(this::stopped); + } + + private void start(ServerAboutToStartEvent event) { + if (station != null) throw new IllegalStateException("AstraCauldron already started"); + // AstraPlus installs its API at NORMAL priority in the same event. Start before + // world entities load so persisted cauldron displays can be safely reconciled. + if (AstraPlusApi.current().isEmpty()) + throw new IllegalStateException("AstraCauldron requires the running AstraPlus API"); + try { + MixingCapabilities.start(event.getServer(), + FMLPaths.GAMEDIR.get().resolve("config/astracauldron.json"), + "astracauldron:combination_rules", "Котлы и сочетания ингредиентов", + defaults, schema, compatibility); + station = RecipeStationRuntimes.register("cauldron", "astracauldron:combination_rules"); + } catch (IOException | RuntimeException failure) { + close(); + throw new IllegalStateException("Cannot initialize AstraCauldron", failure); + } + } + + static String resource(String kind) throws IOException { + String path = "/editor/combination-" + kind + ".json"; + try (var stream = AstraCauldron.class.getResourceAsStream(path)) { + if (stream == null) throw new IOException("Missing AstraCauldron policy resource: " + path); + byte[] bytes = stream.readNBytes(POLICY_RESOURCE_LIMIT + 1); + if (bytes.length > POLICY_RESOURCE_LIMIT) + throw new IOException("AstraCauldron policy resource exceeds 512 KiB: " + path); + return new String(bytes, StandardCharsets.UTF_8); + } + } + + private void stopping(ServerStoppingEvent event) { + // NORMAL runs before AstraPlus tears down its water service at LOWEST. + close(); + } + + private void stopped(ServerStoppedEvent event) { + close(); + } + + private void close() { + if (station != null) { + station.close(); + station = null; + } + MixingCapabilities.close(); + } } diff --git a/src/main/java/online/astradev/cauldron/mixin/MixingHeatMixin.java b/src/main/java/online/astradev/cauldron/mixin/MixingHeatMixin.java new file mode 100644 index 0000000..8cde04b --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixin/MixingHeatMixin.java @@ -0,0 +1,28 @@ +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.mixing.MixingHeat; + +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 MixingHeatMixin { + @Inject(method = "cookTick", at = @At("TAIL")) + private static void astracauldron$mixingheat( + ServerLevel level, + BlockPos pos, + BlockState state, + CampfireBlockEntity entity, + RecipeManager.CachedCheck recipes, + CallbackInfo ci) { + MixingHeat.tick(level, pos); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixin/MixingLevelMixin.java b/src/main/java/online/astradev/cauldron/mixin/MixingLevelMixin.java new file mode 100644 index 0000000..7a9ac9a --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixin/MixingLevelMixin.java @@ -0,0 +1,20 @@ +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.mixing.MixingCapabilities; + +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 MixingLevelMixin { + @Inject(method = "lowerFillLevel", at = @At("HEAD"), cancellable = true) + private static void astracauldron$mixinglower(BlockState state, Level level, BlockPos pos, CallbackInfo ci) { + if (MixingCapabilities.occupied(level, pos)) ci.cancel(); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixin/MixingStackMixin.java b/src/main/java/online/astradev/cauldron/mixin/MixingStackMixin.java new file mode 100644 index 0000000..199b3b5 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixin/MixingStackMixin.java @@ -0,0 +1,30 @@ +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.mixing.MixingCapabilities; + +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 MixingStackMixin { + @Inject( + method = + "(Lnet/minecraft/core/Holder;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", + at = @At("RETURN")) + private void astracauldron$mixingstackSize( + Holder item, int count, PatchedDataComponentMap components, CallbackInfo ci) { + if (!MixingCapabilities.active()) return; + var key = item.unwrapKey().orElse(null); + if (key == null) return; + var config = MixingCapabilities.config(); + if (config.normalizeVanillaSoups && config.runtime().strings("normalizedItems").contains(key.identifier().toString())) + components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixin/MixingWeatherMixin.java b/src/main/java/online/astradev/cauldron/mixin/MixingWeatherMixin.java new file mode 100644 index 0000000..07fee77 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixin/MixingWeatherMixin.java @@ -0,0 +1,34 @@ +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.mixing.MixingCapabilities; + +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 MixingWeatherMixin { + @Inject(method = "handlePrecipitation", at = @At("HEAD"), cancellable = true) + private void astracauldron$mixingrain( + BlockState state, + Level level, + BlockPos pos, + Biome.Precipitation precipitation, + CallbackInfo ci) { + if (MixingCapabilities.occupied(level, pos)) ci.cancel(); + } + + @Inject(method = "receiveStalactiteDrip", at = @At("HEAD"), cancellable = true) + private void astracauldron$mixingdrip( + BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) { + if (MixingCapabilities.occupied(level, pos)) ci.cancel(); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/LiquidMixingPots.java b/src/main/java/online/astradev/cauldron/mixing/LiquidMixingPots.java new file mode 100644 index 0000000..3cd87eb --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/LiquidMixingPots.java @@ -0,0 +1,467 @@ +package online.astradev.cauldron.mixing; + +import com.google.gson.*; + +import net.minecraft.ChatFormatting; +import net.minecraft.core.BlockPos; +import net.minecraft.core.component.DataComponents; +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.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 LiquidMixingPots 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(MixingCapabilities.profile().customPotionSource()); + } + } + + private final Identifier owner = MixingCapabilities.profile().liquidOwner(); + private final MinecraftServer server; + private final CauldronApi api; + private final Path file; + private final Map liquids = new LinkedHashMap<>(); + + public LiquidMixingPots(MinecraftServer server) throws IOException { + this.server = server; + api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow(); + file = server.getWorldPath(LevelResource.ROOT).resolve(MixingCapabilities.profile().liquidPath()); + 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(MixingCapabilities.profile().entriesKey())) { + 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 = MixingFiles.decode(record.get("potion"), server.registryAccess()); + // Stored contents retain their meaning even after the authored bottle carrier changes. + var contents = bottle.get(DataComponents.POTION_CONTENTS); + if (contents == null) throw new IllegalArgumentException("Stored bottle has no potion contents"); + potion = new CauldronApi.Potion(contents, bottle.getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f)); + } + 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 > MixingCapabilities.runtime().integer("maxLiquidLevels")) + 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, MixingCapabilities.runtime().block("emptyContainer").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); + MixingCapabilities.LOG.error("Не удалось сохранить жидкость; действие отменено", e); + return false; + } + } + + private void save() throws IOException { + var root = new JsonObject(); + root.addProperty("version", 1); + var array = new JsonArray(); + root.add(MixingCapabilities.profile().entriesKey(), 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", + MixingFiles.encode(bottle(liquid.potion), server.registryAccess())); + array.add(c); + } + MixingFiles.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(MixingCapabilities.runtime().block("emptyContainer")) && !state.is(MixingCapabilities.runtime().block("waterContainer"))) 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 = readPotion(held); + if (potion.isPresent() && plainWater(potion.get())) { + int current = + state.is(MixingCapabilities.runtime().block("waterContainer")) + ? state.getValue(LayeredCauldronBlock.LEVEL) + : 0; + if (current < MixingCapabilities.runtime().integer("maxLiquidLevels")) { + level.setBlock( + blockPos, + MixingCapabilities.runtime().block("waterContainer") + .defaultBlockState() + .setValue(LayeredCauldronBlock.LEVEL, current + 1), + 3); + consumeAndGive(player, 1, new ItemStack(MixingCapabilities.runtime().item("glassBottle"))); + } + return true; + } + var dye = api.mixDye(OptionalInt.empty(), held); + if (MixingCapabilities.config().dyeWater && state.is(MixingCapabilities.runtime().block("waterContainer")) && 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 (MixingCapabilities.config().storePotions + && state.is(MixingCapabilities.runtime().block("emptyContainer")) + && 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(MixingCapabilities.runtime().item("glassBottle"))); + setVisual(level, pos, next); + say(player, "Зелье налито: 1/" + MixingCapabilities.runtime().integer("maxLiquidLevels") + ". Бутылочка — забрать, стрелы — обработать."); + 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 (MixingCapabilities.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 (MixingCapabilities.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 (MixingCapabilities.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(MixingCapabilities.runtime().item("waterBucket"))) { + if (!change(pos, null)) { + error(player); + return true; + } + level.setBlock( + blockPos, + MixingCapabilities.runtime().block("waterContainer") + .defaultBlockState() + .setValue(LayeredCauldronBlock.LEVEL, MixingCapabilities.runtime().integer("maxLiquidLevels")), + 3); + consumeAndGive(player, 1, new ItemStack(MixingCapabilities.runtime().item("bucket"))); + return true; + } + if (held.is(MixingCapabilities.runtime().item("bucket")) && liquid.levels >= MixingCapabilities.runtime().integer("maxLiquidLevels")) { + if (!decrease(level, pos, liquid, MixingCapabilities.runtime().integer("maxLiquidLevels"))) { + error(player); + return true; + } + consumeAndGive(player, 1, new ItemStack(MixingCapabilities.runtime().item("waterBucket"))); + return true; + } + if (held.is(MixingCapabilities.runtime().item("glassBottle"))) { + if (!decrease(level, pos, liquid, 1)) { + error(player); + return true; + } + var water = new CauldronApi.Potion(new PotionContents(server.registryAccess().lookupOrThrow(Registries.POTION).getOrThrow(ResourceKey.create(Registries.POTION, MixingCapabilities.runtime().identifier("waterPotion")))), 1); + consumeAndGive(player, 1, bottle(water)); + return true; + } + say(player, "Цветная вода: " + liquid.levels + "/" + MixingCapabilities.runtime().integer("maxLiquidLevels") + ". Для варки супа нужна чистая вода."); + 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 = readPotion(held); + if (potion.isPresent()) { + if (!MixingCapabilities.config().storePotions) return true; + if (!potion.get().equals(liquid.potion)) { + say(player, "В котле другое зелье. Сначала заберите его бутылочками."); + return true; + } + if (liquid.levels >= MixingCapabilities.runtime().integer("maxLiquidLevels")) { + say(player, "Котёл уже полон."); + return true; + } + var next = liquid.withLevels(liquid.levels + 1); + if (!change(pos, next)) { + error(player); + return true; + } + consumeAndGive(player, 1, new ItemStack(MixingCapabilities.runtime().item("glassBottle"))); + setVisual(level, pos, next); + return true; + } + if (held.is(MixingCapabilities.runtime().item("glassBottle"))) { + var bottle = 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 (MixingCapabilities.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 + "/" + MixingCapabilities.runtime().integer("maxLiquidLevels") + ". Окуните обычные стрелы или наберите бутылочку."); + 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, MixingCapabilities.runtime().block("emptyContainer").defaultBlockState(), 3); + if (next != null) setVisual(level, pos, next); + return true; + } + + private static boolean plainWater(CauldronApi.Potion potion) { + var contents = potion.contents(); + return contents.potion().flatMap(holder -> holder.unwrapKey()).map(key -> key.identifier().equals(MixingCapabilities.runtime().identifier("waterPotion"))).orElse(false) + && contents.customColor().isEmpty() + && contents.customName().isEmpty() + && potion.durationScale() == 1f; + } + + private static Optional readPotion(ItemStack stack) { + if (stack.isEmpty() || !MixingCapabilities.runtime().itemMatches(stack, "potionItems")) return Optional.empty(); + return potionContents(stack); + } + + private static Optional potionContents(ItemStack stack) { + var contents = stack.get(DataComponents.POTION_CONTENTS); + if (contents == null) return Optional.empty(); + float scale = stack.transmuteCopy(MixingCapabilities.runtime().item("potionBase"), 1) + .getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f); + return Optional.of(new CauldronApi.Potion(contents, scale)); + } + + private static ItemStack bottle(CauldronApi.Potion potion) { + var result = new ItemStack(MixingCapabilities.runtime().item("potionBase")); + result.set(DataComponents.POTION_CONTENTS, potion.contents()); + result.set(DataComponents.POTION_DURATION_SCALE, potion.durationScale()); + return result; + } + + 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(MixingCapabilities.runtime().block("emptyContainer"))) { + change(pos, null); + continue; + } + surface(level, pos, entry.getValue()); + } + } + + private void setVisual(ServerLevel level, Position pos, Liquid liquid) { + level.setBlock(pos.pos, MixingCapabilities.runtime().block("emptyContainer").defaultBlockState(), 3); + surface(level, pos, liquid); + } + + private void surface(ServerLevel level, Position pos, Liquid liquid) { + float height = MixingAnimation.waterLevelHeight(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 = MixingCapabilities.config(); + if (config.sounds) + level.playSound( + null, pos, MixingCapabilities.runtime().sound("soundFill"), SoundSource.BLOCKS, config.soundVolume, 1); + } + + private static void say(ServerPlayer player, String text) { + var config = MixingCapabilities.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/mixing/MixingAnimation.java b/src/main/java/online/astradev/cauldron/mixing/MixingAnimation.java new file mode 100644 index 0000000..5f6abcc --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingAnimation.java @@ -0,0 +1,46 @@ +package online.astradev.cauldron.mixing; + +/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */ +public final class MixingAnimation { + private MixingAnimation() {} + + public record Offset(double x, double y, double z) {} + + public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) { + return frame(MixingCapabilities.runtime(), slot, waterLevel, tick, elapsed, duration); + } + + static Offset frame(MixingRuntime runtime, int slot, int waterLevel, int tick, int elapsed, int duration) { + double angle = runtime.orbitAngle(slot) + (duration > 0 ? elapsed * runtime.decimal("orbitRadiansPerBrewTick") : 0); + double radius = runtime.decimal("orbitRadius"); + double surface = runtime.decimal("waterBaseHeight") + runtime.decimal("waterStepHeight") * waterLevel; + double bob = Math.sin(tick * runtime.decimal("bobSpeed") + slot) * runtime.decimal("bobHeight"); + return new Offset( + .5 + Math.cos(angle) * radius, surface - runtime.decimal("ingredientSubmersion") + bob, .5 + Math.sin(angle) * radius); + } + + public static double liquidHeight(int servings, int capacity) { + return liquidHeight(MixingCapabilities.runtime(), servings, capacity); + } + + public static float waterLevelHeight(int levels) { + var runtime = MixingCapabilities.runtime(); + return (float) (runtime.decimal("waterBaseHeight") + runtime.decimal("waterStepHeight") * levels); + } + + static double liquidHeight(MixingRuntime runtime, int servings, int capacity) { + return runtime.decimal("liquidBaseHeight") + runtime.decimal("liquidHeightRange") * Math.clamp((double) servings / capacity, 0, 1); + } + + public static int waterLevel(int servings, int capacity) { + return waterLevel(MixingCapabilities.runtime(), servings, capacity); + } + + static int waterLevel(MixingRuntime runtime, int servings, int capacity) { + double height = liquidHeight(runtime, servings, capacity); + int level = 0; + for (int i = 1; i <= runtime.integer("maxLiquidLevels"); i++) + if (runtime.decimal("waterBaseHeight") + runtime.decimal("waterStepHeight") * i <= height + .00001) level = i; + return level; + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingAuthoring.java b/src/main/java/online/astradev/cauldron/mixing/MixingAuthoring.java new file mode 100644 index 0000000..b2e3764 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingAuthoring.java @@ -0,0 +1,28 @@ +package online.astradev.cauldron.mixing; + +import java.nio.file.Path; +import java.util.function.Consumer; +import java.util.function.Function; +import online.astradev.plus.api.editor.FileEditorDefinition; + +/** The editor publishes the same native configuration read by every cauldron interaction. */ +final class MixingAuthoring { + private MixingAuthoring() {} + + static FileEditorDefinition provider(Path file, String id, String name, String defaultsJson, + String schemaJson, Function prepare, Consumer publish) { + return new FileEditorDefinition<>(file, id, name, schema(defaultsJson, schemaJson), prepare, publish); + } + + static String schema(String defaultsJson, String schemaJson) { + var schema = com.google.gson.JsonParser.parseString(schemaJson).getAsJsonObject(); + var defaults = com.google.gson.JsonParser.parseString(defaultsJson).getAsJsonObject(); + for (var entry : schema.getAsJsonArray("fields")) { + var field = entry.getAsJsonObject(); + com.google.gson.JsonElement value = defaults; + for (String key : field.get("path").getAsString().split("\\.")) value = value.getAsJsonObject().get(key); + field.add("default", value.deepCopy()); + } + return schema.toString(); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingCapabilities.java b/src/main/java/online/astradev/cauldron/mixing/MixingCapabilities.java new file mode 100644 index 0000000..8d3b93b --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingCapabilities.java @@ -0,0 +1,254 @@ +package online.astradev.cauldron.mixing; + +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.bus.api.EventPriority; +import net.neoforged.bus.api.IEventBus; +import net.minecraft.server.MinecraftServer; +import com.google.gson.JsonObject; +import java.nio.file.Path; +import java.io.IOException; +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 online.astradev.plus.api.editor.EditorDefinitionProvider; +import online.astradev.plus.api.editor.EditorDefinitions; + +import org.slf4j.*; + +public final class MixingCapabilities { + static final Logger LOG = LoggerFactory.getLogger("MixingCapabilities"); + private static MixingPots pots; + private static MixingProfile profile; + private static MixingConfig initialConfig; + private static LiquidMixingPots liquids; + private static EditorDefinitionProvider editorDefinition; + private static boolean registered; + + private MixingCapabilities() {} + + /** Register immutable command names before Minecraft constructs its dispatcher. */ + public static void declareCompatibility(JsonObject compatibility) { + if (pots != null) throw new IllegalStateException("Mixing capability already started"); + profile = MixingProfile.parse(compatibility); + } + + public static void register(IEventBus bus) { + if (registered) return; + registered = true; + var hooks = new MixingCapabilities(); + bus.addListener(hooks::tick); + bus.addListener(EventPriority.LOWEST, hooks::interact); + bus.addListener(EventPriority.LOWEST, hooks::breakBlock); + bus.addListener(hooks::explosion); + bus.addListener(hooks::piston); + bus.addListener(hooks::unload); + bus.addListener(hooks::join); + bus.addListener(hooks::commands); + } + + public static void start(MinecraftServer server, Path file, String id, String name, + String defaultsJson, String schemaJson, JsonObject compatibility) throws IOException { + close(); + profile = MixingProfile.parse(compatibility); + initialConfig = MixingConfig.parse(defaultsJson, defaultsJson, schemaJson); + try { + AstraPlusApi.current() + .orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable")); + pots = + new MixingPots(server, file, id, name, defaultsJson, schemaJson); + liquids = new LiquidMixingPots(server); + editorDefinition = pots.editorDefinition(); + EditorDefinitions.register(editorDefinition); + new MixingCapabilities().registerCommands(server.getCommands().getDispatcher()); + LOG.info("MixingCapabilities ready: NeoForge 26.2, AstraPlus API"); + } catch (RuntimeException | IOException e) { + close(); + throw e; + } + } + + public static void close() { + if (editorDefinition != null) EditorDefinitions.unregister(editorDefinition); + editorDefinition = null; + if (pots != null) pots.close(); + if (liquids != null) liquids.close(); + pots = null; + liquids = null; + initialConfig = null; + // Keep immutable command names across consecutive server lifecycles. Listeners + // are registered once per mod load and remain inert when no runtime is active. + } + + private void tick(ServerTickEvent.Post event) { + if (pots != null) pots.tick(); + if (liquids != null) liquids.tick(); + } + + public static MixingPots pots() { + return pots; + } + + public static MixingConfig config() { + return pots == null ? initialConfig : pots.config(); + } + + public static boolean active() { return config() != null && profile != null; } + public static MixingProfile profile() { return profile; } + public static MixingRuntime runtime() { return config().runtime(); } + + public static LiquidMixingPots 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 = MixingRecipes.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 (!active()) return; + if (event.loadedFromDisk() && event.getEntity().entityTags().contains(profile.visualTag())) + event.setCanceled(true); + else if (event.getEntity() instanceof ItemEntity item) + MixingIngredients.normalize(item.getItem()); + } + + private void commands(RegisterCommandsEvent event) { + registerCommands(event.getDispatcher()); + } + + private void registerCommands(com.mojang.brigadier.CommandDispatcher dispatcher) { + if (profile == null) return; + var command = Commands.literal(profile.commands().getFirst()).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 = dispatcher.register(command); + for (String alias : profile.commands().subList(1, profile.commands().size())) + dispatcher.register(Commands.literal(alias).redirect(root).executes(root.getCommand())); + } + + private int help(CommandContext context) { + var message = + Component.literal( + "Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и" + + " стрелы с эффектом. Еда/зелья + полный котёл воды: " + config().ingredientCount + " ингредиента" + + " супа, Shift+ПКМ — варка, миска — порция."); + context.getSource().sendSuccess(() -> message, false); + return 1; + } + + private int reload(CommandContext context) { + try { + requirePots().reload(); + context.getSource() + .sendSuccess( + () -> Component.literal("MixingCapabilities: настройки применены."), 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 MixingPots requirePots() { + if (pots == null) throw new IllegalStateException("MixingCapabilities ещё не запущен"); + return pots; + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingConfig.java b/src/main/java/online/astradev/cauldron/mixing/MixingConfig.java new file mode 100644 index 0000000..284be82 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingConfig.java @@ -0,0 +1,188 @@ +package online.astradev.cauldron.mixing; + +import com.google.gson.*; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; + +public final class MixingConfig { + public boolean soupsEnabled; + public boolean dyeWater; + public boolean dyeArmor; + public boolean dyeBlocks; + public boolean storePotions; + public boolean tipArrows; + public boolean requireHeat; + public boolean particles; + public boolean ingredientDisplays; + public boolean sounds; + public float soundVolume; + public boolean messages; + public int ingredientCount; + public boolean inheritEffects; + public boolean alwaysEdible; + public float consumeSeconds; + public boolean returnBowl; + public int soupStackSize; + public boolean normalizeVanillaSoups; + public Map messageOverrides; + public int servingsPerBrew; + public boolean requireFullWater; + public double brewSeconds; + public String soupName; + public String defaultColor; + public int maxNutrition; + public float maxSaturation; + public List blockedIngredients; + public List> incompatible; + public Map customIngredients; + public int cakeNutrition; + public float cakeSaturation; + public Map ingredientColors; + + public JsonObject engine; + private transient MixingRuntime runtime; + + public MixingRuntime runtime() { return runtime; } + + public static MixingConfig parse(String document, String defaultsJson, String schemaJson) { + try { + var authored = JsonParser.parseString(document); + var defaults = JsonParser.parseString(defaultsJson); + if (!authored.isJsonObject() || !defaults.isJsonObject()) throw new IllegalArgumentException("Mixing settings must be objects"); + var merged = defaults.getAsJsonObject().deepCopy(); + merge(merged, authored.getAsJsonObject()); + var config = MixingFiles.JSON.fromJson(merged, MixingConfig.class); + config.runtime = new MixingRuntime(config.engine, schemaJson); + config.validate(); + return config; + } catch (JsonParseException | IllegalStateException error) { + throw new IllegalArgumentException("Invalid mixing settings", error); + } + } + + private static void merge(JsonObject target, JsonObject changes) { + changes.entrySet().forEach(entry -> { + if (entry.getKey().equals("engine") && entry.getValue().isJsonObject() && target.has(entry.getKey()) && target.get(entry.getKey()).isJsonObject()) + merge(target.getAsJsonObject(entry.getKey()), entry.getValue().getAsJsonObject()); + else target.add(entry.getKey(), entry.getValue().deepCopy()); + }); + } + + int ingredientColor(String material) { + return rgb(ingredientColors.getOrDefault(material, defaultColor)); + } + + 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 MixingConfig load(Path file, String defaultsJson, String schemaJson) throws IOException { + var nativeFile = new online.astradev.plus.api.editor.FileEditorDefinition( + file, "mixing:config", "Mixing", schemaJson, + document -> parse(document, defaultsJson, schemaJson), ignored -> {}); + nativeFile.initialize(defaultsJson); + return parse(nativeFile.snapshot().documentJson(), defaultsJson, schemaJson); + } + + public void validate() { + if (ingredientCount < 1 + || ingredientCount > runtime.integer("maxIngredientCount") + || 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 > runtime.integer("maxServings") + || !Double.isFinite(brewSeconds) + || brewSeconds < .5 + || brewSeconds * 20 > runtime.integer("maxBrewTicks") + || maxNutrition < 0 + || !Float.isFinite(maxSaturation) + || maxSaturation < 0 + || soupName == null + || soupName.isBlank()) + throw new IllegalArgumentException("Некорректные настройки варки/питания"); + rgb(defaultColor); + if (cakeNutrition < 0 || !Float.isFinite(cakeSaturation) || cakeSaturation < 0 || ingredientColors == null) + throw new IllegalArgumentException("Некорректные питание торта или цвета ингредиентов"); + ingredientColors.forEach((material, color) -> { + if (material == null || !material.matches("[a-z0-9_./-]+")) + throw new IllegalArgumentException("Некорректный материал цвета ингредиента"); + rgb(color); + }); + if (blockedIngredients == null || incompatible == null || customIngredients == null) + throw new IllegalArgumentException("Списки настроек не могут быть null"); + blockedIngredients.forEach(MixingConfig::selector); + for (var pair : incompatible) { + if (pair == null || pair.size() != 2) + throw new IllegalArgumentException("В incompatible нужны пары"); + pair.forEach(MixingConfig::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/mixing/MixingDisplay.java b/src/main/java/online/astradev/cauldron/mixing/MixingDisplay.java new file mode 100644 index 0000000..d7d7f96 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingDisplay.java @@ -0,0 +1,52 @@ +package online.astradev.cauldron.mixing; + +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 MixingDisplay extends Display.ItemDisplay { + + MixingDisplay(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(MixingCapabilities.profile().visualTag()); + setTransformationInterpolationDuration(MixingCapabilities.runtime().integer("displayInterpolationTicks")); + } + + void ingredient(int slot, int water, int ticks, int elapsed, int duration) { + var frame = MixingAnimation.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(MixingCapabilities.runtime().floating("displayScale")), + new Quaternionf().rotationY(ticks * MixingCapabilities.runtime().floating("displayRotationPerTick") + slot))); + } + + @Override + public boolean shouldBeSaved() { + return false; + } + + @Override + public boolean saveAsPassenger(ValueOutput output) { + return false; + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingFiles.java b/src/main/java/online/astradev/cauldron/mixing/MixingFiles.java new file mode 100644 index 0000000..5c1707e --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingFiles.java @@ -0,0 +1,48 @@ +package online.astradev.cauldron.mixing; + +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 MixingFiles { + static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); + + private MixingFiles() {} + + 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/mixing/MixingHeat.java b/src/main/java/online/astradev/cauldron/mixing/MixingHeat.java new file mode 100644 index 0000000..bed6dc3 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingHeat.java @@ -0,0 +1,62 @@ +package online.astradev.cauldron.mixing; + +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 MixingHeat { + private MixingHeat() {} + + public static boolean heated(LevelReader level, BlockPos cauldron) { + if (!MixingCapabilities.active()) return false; + var below = cauldron.below(); + if (!level.hasChunkAt(below)) return false; + var state = level.getBlockState(below); + return (state.is(MixingCapabilities.runtime().block("normalHeat")) || state.is(MixingCapabilities.runtime().block("soulHeat"))) + && state.hasProperty(CampfireBlock.LIT) && state.getValue(CampfireBlock.LIT); + } + + public static void tick(ServerLevel level, BlockPos campfire) { + if (!MixingCapabilities.active() || !MixingCapabilities.config().particles) return; + var runtime = MixingCapabilities.runtime(); + var pos = campfire.above(); + if ((level.getGameTime() + pos.asLong()) % runtime.integer("heatParticleIntervalTicks") != 0 || !heated(level, pos)) return; + var state = level.getBlockState(pos); + double surface; + if (state.is(MixingCapabilities.runtime().block("waterContainer"))) + surface = runtime.decimal("waterBaseHeight") + runtime.decimal("waterStepHeight") * state.getValue(LayeredCauldronBlock.LEVEL); + else { + var pot = MixingCapabilities.pots() == null ? null : MixingCapabilities.pots().get(level, pos); + if (!state.is(MixingCapabilities.runtime().block("emptyContainer")) + || pot == null + || pot.soup().isEmpty() + || pot.brewTicks() > 0) return; + surface = MixingAnimation.liquidHeight(pot.servings(), pot.capacity()); + } + level.sendParticles( + runtime.particle("heatBubbleParticle"), + pos.getX() + .5, + pos.getY() + surface + runtime.decimal("heatBubbleOffset"), + pos.getZ() + .5, + runtime.integer("heatBubbleCount"), + runtime.decimal("heatBubbleHorizontal"), + runtime.decimal("heatBubbleVertical"), + runtime.decimal("heatBubbleHorizontal"), + runtime.decimal("heatBubbleSpeed")); + level.sendParticles( + runtime.particle("heatSplashParticle"), + pos.getX() + .5, + pos.getY() + surface + runtime.decimal("heatSplashOffset"), + pos.getZ() + .5, + runtime.integer("heatSplashCount"), + runtime.decimal("heatSplashHorizontal"), + runtime.decimal("heatSplashVertical"), + runtime.decimal("heatSplashHorizontal"), + runtime.decimal("heatSplashSpeed")); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingIngredients.java b/src/main/java/online/astradev/cauldron/mixing/MixingIngredients.java new file mode 100644 index 0000000..1559bf6 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingIngredients.java @@ -0,0 +1,315 @@ +package online.astradev.cauldron.mixing; + +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 MixingIngredients { + public record Ingredient( + int nutrition, + float saturation, + List effects, + Set tags, + int color) {} + + private record Custom( + String id, + ItemStack sample, + MixingConfig.Custom definition, + List effects) {} + + private final MixingConfig config; + private final HolderLookup.Provider registries; + private final List custom = new ArrayList<>(); + + public MixingIngredients(MixingConfig config, HolderLookup.Provider registries) { + config.validate(); + config.runtime().validateResources(); + registries.lookupOrThrow(net.minecraft.core.registries.Registries.POTION) + .getOrThrow(net.minecraft.resources.ResourceKey.create( + net.minecraft.core.registries.Registries.POTION, + config.runtime().identifier("waterPotion"))); + if (new ItemStack(config.runtime().item("consumeTemplate")).get(DataComponents.CONSUMABLE) == null) + throw new IllegalArgumentException("The consumeTemplate item must define a consumable component"); + this.config = config; + this.registries = registries; + for (var entry : config.customIngredients.entrySet()) { + var c = entry.getValue(); + ItemStack sample = + c.item == null ? ItemStack.EMPTY : MixingFiles.decode(c.item, registries); + if (c.item != null && (sample.isEmpty() || sample.getCount() != 1)) + throw new IllegalArgumentException("Некорректный образец " + entry.getKey()); + normalize(sample, config); + List effects = new ArrayList<>(); + for (var e : c.effects) { + var type = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(e.type)) + .orElseThrow(() -> new IllegalArgumentException("Неизвестный эффект: " + e.type)); + 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 = config.runtime().itemMatches(stack, "potionItems"); + boolean cake = stack.is(config.runtime().item("specialFood")); + 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 = config.cakeNutrition; + saturation = config.cakeSaturation; + } + 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 = config.ingredientColor(material); + 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(config.runtime().item("potionBase"), 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(MixingCapabilities.profile().combinedSelector()); + 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 = MixingConfig.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 = + MixingRules.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() > config.runtime().integer("maxEffectCount")) + return "В супе слишком много эффектов."; + return null; + } + + public ItemStack brew(List items) { + String error = rejection(items); + if (error != null) throw new IllegalArgumentException(error); + var data = + items.stream() + .map(MixingIngredients::normalizedCopy) + .sorted( + Comparator.comparing( + s -> MixingFiles.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(config.runtime().item("carrier")); + CustomData.update( + DataComponents.CUSTOM_DATA, + soup, + tag -> { + tag.putBoolean(MixingCapabilities.profile().markerTag(), true); + tag.putInt(MixingCapabilities.profile().colorTag(), 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(new ItemStack(config.runtime().item("consumeTemplate")).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(config.runtime().item("remainder"))))); + else soup.remove(DataComponents.USE_REMAINDER); + normalize(soup, config); + 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) { + if (!MixingCapabilities.active()) return false; + return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY) + .copyTag() + .getBooleanOr(MixingCapabilities.profile().markerTag(), false); + } + + public static int color(ItemStack stack) { + if (!MixingCapabilities.active()) return 0; + return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY) + .copyTag() + .getIntOr(MixingCapabilities.profile().colorTag(), MixingConfig.rgb(MixingCapabilities.config().defaultColor)) + & 0xFFFFFF; + } + + static ItemStack normalizedCopy(ItemStack stack) { + var copy = stack.copyWithCount(1); + normalize(copy); + return copy; + } + + public static void normalize(ItemStack stack) { + if (!MixingCapabilities.active()) return; + normalize(stack, MixingCapabilities.config()); + } + + private static void normalize(ItemStack stack, MixingConfig config) { + if (!isCombined(stack) && !config.runtime().itemMatches(stack, "normalizedItems")) return; + if (isCombined(stack) || config.normalizeVanillaSoups) + stack.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize); + if (!isCombined(stack)) return; + stack.set(DataComponents.ITEM_MODEL, config.runtime().identifier("model")); + 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 = " " + MixingText.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/mixing/MixingPots.java b/src/main/java/online/astradev/cauldron/mixing/MixingPots.java new file mode 100644 index 0000000..7ede9f7 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingPots.java @@ -0,0 +1,554 @@ +package online.astradev.cauldron.mixing; + +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 online.astradev.plus.api.editor.EditorDefinitionProvider; + +import java.io.IOException; +import java.nio.file.*; +import java.util.*; + +public final class MixingPots 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 final Identifier waterOwner; + private final ColoredWaterApi water; + private final Path file; + private final Path configFile; + private final String id, name, defaultsJson, schemaJson; + private MixingConfig config; + private MixingIngredients ingredients; + private final Map pots = new LinkedHashMap<>(); + private final Map> visuals = new HashMap<>(); + private final Map elapsed = new HashMap<>(); + private int ticks; + + public MixingPots(MinecraftServer server, Path configFile, String id, String name, + String defaultsJson, String schemaJson) throws IOException { + this.server = server; + this.id = id; + this.name = name; + this.defaultsJson = defaultsJson; + this.schemaJson = schemaJson; + this.waterOwner = MixingCapabilities.profile().waterOwner(); + this.water = AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow(); + this.file = server.getWorldPath(LevelResource.ROOT).resolve(MixingCapabilities.profile().soupPath()); + this.configFile = configFile; + reload(); + load(); + } + + public MixingIngredients ingredients() { + return ingredients; + } + + public MixingConfig 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 = MixingConfig.load(configFile, defaultsJson, schemaJson); + var nextIngredients = new MixingIngredients(next, server.registryAccess()); + config = next; + ingredients = nextIngredients; + } + + private record PreparedConfiguration(MixingConfig config, MixingIngredients ingredients) {} + + EditorDefinitionProvider editorDefinition() { + return MixingAuthoring.provider(configFile, id, name, defaultsJson, schemaJson, document -> { + var next = MixingConfig.parse(document, defaultsJson, schemaJson); + return new PreparedConfiguration(next, new MixingIngredients(next, server.registryAccess())); + }, prepared -> { + // Parsing, registry lookups and item/effect decoding completed before the atomic write. + config = prepared.config(); + ingredients = prepared.ingredients(); + }); + } + + 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 provider = editorDefinition(); + var snapshot = provider.snapshot(); + var nativeDocument = JsonParser.parseString(snapshot.documentJson()).getAsJsonObject(); + var next = MixingConfig.parse(nativeDocument.toString(), defaultsJson, schemaJson); + 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 = + MixingFiles.encode( + MixingIngredients.normalizedCopy(player.getMainHandItem()), + server.registryAccess()); + var authoredIngredients = nativeDocument.has("customIngredients") + ? nativeDocument.getAsJsonObject("customIngredients") + : JsonParser.parseString(defaultsJson).getAsJsonObject().getAsJsonObject("customIngredients").deepCopy(); + var entry = authoredIngredients.has(id) ? authoredIngredients.getAsJsonObject(id) : new JsonObject(); + entry.addProperty("nutrition", nutrition); + entry.addProperty("saturation", saturation); + entry.remove("item"); + entry.remove("astraPlusId"); + if (custom.astraPlusId != null) entry.addProperty("astraPlusId", custom.astraPlusId); + else entry.add("item", custom.item); + authoredIngredients.add(id, entry); + nativeDocument.add("customIngredients", authoredIngredients); + provider.save(nativeDocument.toString(), snapshot.revision()); + } + + 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(MixingCapabilities.profile().entriesKey())) { + 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(MixingFiles.decode(i, server.registryAccess())); + var soup = + c.has("soup") + ? MixingFiles.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() > 64) + 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 > 72000) { + 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 || !MixingIngredients.isCombined(pot.soup)) { + throw new IllegalArgumentException("Invalid cauldron soup"); + } + if (pot.servings < 1 || pot.capacity < pot.servings || pot.capacity > 64) { + 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(MixingCapabilities.profile().entriesKey(), 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(MixingFiles.encode(i, server.registryAccess()))); + c.add("items", items); + if (!pot.soup.isEmpty()) + c.add("soup", MixingFiles.encode(pot.soup, server.registryAccess())); + c.addProperty("brewTicks", pot.brewTicks); + c.addProperty("servings", pot.servings); + c.addProperty("capacity", pot.capacity); + array.add(c); + } + MixingFiles.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); + MixingCapabilities.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) != config.runtime().integer("maxLiquidLevels")) { + say(player, "Сначала наполните котёл водой доверху."); + return true; + } + pot = Pot.raw(List.of()); + } + if (pot.brewing()) { + say( + player, + (!config.requireHeat || MixingHeat.heated(level, blockPos)) + ? "Суп варится… Осталось: " + + Math.max( + 1, + (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) + / 20) + + " с." + : "Варка приостановлена. Зажгите костёр под котлом."); + return true; + } + if (pot.ready()) { + if (!held.is(MixingCapabilities.runtime().item("remainder"))) { + 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, MixingCapabilities.runtime().block("emptyContainer").defaultBlockState(), 3); + if (left > 0) show(level, pos, pots.get(pos)); + sound(level, blockPos, MixingCapabilities.runtime().sound("soundFill")); + say( + player, + left == 0 + ? "Последняя порция собрана. Котёл пуст." + : "Осталось порций: " + left + "."); + return true; + } + if (pot.items.size() >= config.ingredientCount + && (player.isShiftKeyDown() || !held.isEmpty())) { + if (config.requireHeat && !MixingHeat.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, MixingCapabilities.runtime().sound("soundStart")); + 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, MixingCapabilities.runtime().sound("soundIngredient")); + 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(MixingCapabilities.runtime().block("waterContainer")) + || (state.is(MixingCapabilities.runtime().block("emptyContainer")) && 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 || MixingHeat.heated(level, pos.pos); + if (pot.brewing() && heated) { + int time = elapsed.merge(pos, 1, Integer::sum); + if (time >= pot.brewTicks + && (time - pot.brewTicks) % config.runtime().integer("saveRetryTicks") == 0 + && change( + pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) { + pot = pots.get(pos); + level.setBlock(pos.pos, MixingCapabilities.runtime().block("emptyContainer").defaultBlockState(), 3); + sound(level, pos.pos, MixingCapabilities.runtime().sound("soundComplete")); + if (config.particles) + level.sendParticles( + config.runtime().particle("completionParticle"), + pos.pos.getX() + .5, + pos.pos.getY() + config.runtime().decimal("completionHeight"), + pos.pos.getZ() + .5, + config.runtime().integer("completionCount"), + config.runtime().decimal("completionHorizontal"), + config.runtime().decimal("completionVertical"), + config.runtime().decimal("completionHorizontal"), + config.runtime().decimal("completionSpeed")); + } + } + show(level, pos, pot); + if (config.ingredientDisplays && ticks % config.runtime().integer("displayUpdateTicks") == 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 + config.runtime().integer("displayUpdateTicks"), + elapsed.getOrDefault(pos, 0) + (heated ? config.runtime().integer("displayUpdateTicks") : 0), + pot.brewTicks); + } + } + if (ticks % config.runtime().integer("normalizationIntervalTicks") == 0) + for (var player : server.getPlayerList().getPlayers()) { + for (var slot : player.containerMenu.slots) MixingIngredients.normalize(slot.getItem()); + for (int i = 0; i < player.getInventory().getContainerSize(); i++) + MixingIngredients.normalize(player.getInventory().getItem(i)); + MixingIngredients.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( + waterOwner, + MixingIngredients.color(pot.soup), + (float) MixingAnimation.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 MixingDisplay(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(MixingDisplay::discard); + var level = + server.getLevel( + ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension))); + if (level != null) water.remove(level, pos.pos, waterOwner); + } + + @Override + public void close() { + for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos); + water.removeAll(waterOwner); + } + + 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) { + MixingIngredients.normalize(item); + AstraPlusApi.give(player, item); + } + + private static void say(ServerPlayer player, String text) { + var config = MixingCapabilities.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/mixing/MixingProfile.java b/src/main/java/online/astradev/cauldron/mixing/MixingProfile.java new file mode 100644 index 0000000..b979b3b --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingProfile.java @@ -0,0 +1,36 @@ +package online.astradev.cauldron.mixing; + +import com.google.gson.JsonObject; +import java.nio.file.Path; +import java.util.List; +import net.minecraft.resources.Identifier; + +/** Persistent identity only. Authored presentation and gameplay values live in editable settings. */ +public record MixingProfile(String soupPath, String liquidPath, String entriesKey, + Identifier waterOwner, Identifier liquidOwner, String markerTag, String colorTag, + String visualTag, String combinedSelector, String customPotionSource, List commands) { + public static MixingProfile parse(JsonObject value) { + var commands = value.getAsJsonArray("commands").asList().stream().map(entry -> entry.getAsString()).toList(); + if (commands.isEmpty() || commands.stream().anyMatch(command -> !command.matches("[a-z0-9_-]+"))) + throw new IllegalArgumentException("Invalid mixing command aliases"); + return new MixingProfile(path(text(value, "soupPath")), path(text(value, "liquidPath")), text(value, "entriesKey"), + Identifier.parse(text(value, "waterOwner")), Identifier.parse(text(value, "liquidOwner")), + text(value, "markerTag"), text(value, "colorTag"), text(value, "visualTag"), + text(value, "combinedSelector"), text(value, "customPotionSource"), List.copyOf(commands)); + } + + private static String text(JsonObject value, String key) { + if (!value.has(key) || !value.get(key).isJsonPrimitive()) throw new IllegalArgumentException("Missing mixing identity " + key); + String result = value.get(key).getAsString(); + if (result.isBlank() || result.length() > 256) throw new IllegalArgumentException("Invalid mixing identity " + key); + return result; + } + + private static String path(String value) { + if (value.contains("\\") || value.contains(":") || value.startsWith("/") || Path.of(value).isAbsolute()) + throw new IllegalArgumentException("Mixing storage must be world-relative"); + for (String segment : value.split("/", -1)) if (segment.isBlank() || segment.equals(".") || segment.equals("..")) + throw new IllegalArgumentException("Invalid mixing storage path"); + return value; + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingRecipes.java b/src/main/java/online/astradev/cauldron/mixing/MixingRecipes.java new file mode 100644 index 0000000..995f7ea --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingRecipes.java @@ -0,0 +1,80 @@ +package online.astradev.cauldron.mixing; + +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 MixingRecipes { + private MixingRecipes() {} + + 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(MixingCapabilities.runtime().block("soulHeat"))) return "soul_campfire"; + if (below.is(MixingCapabilities.runtime().block("normalHeat"))) return "campfire"; + return "none"; + } + + public static boolean interact(ServerPlayer player, BlockPos pos, InteractionHand hand) { + var level = player.level(); + if (MixingCapabilities.pots().contains(level, pos) + || player.isSpectator() + || !player.mayInteract(level, pos)) return false; + var state = level.getBlockState(pos); + var saved = MixingCapabilities.liquids().get(level, pos); + if (saved != null && !state.is(MixingCapabilities.runtime().block("emptyContainer"))) return false; + String source; + int fill; + if (saved != null) { + source = saved.source(); + fill = saved.levels(); + } else { + if (state.is(MixingCapabilities.runtime().block("emptyContainer"))) source = "empty"; + else if (state.is(MixingCapabilities.runtime().block("waterContainer"))) source = "water"; + else if (state.is(MixingCapabilities.runtime().block("lavaContainer"))) source = "lava"; + else if (state.is(MixingCapabilities.runtime().block("snowContainer"))) source = "powder_snow"; + else return false; + fill = source.equals("empty") ? 0 : MixingCapabilities.runtime().integer("maxLiquidLevels"); + 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 (!MixingCapabilities.liquids().applyRecipe(level, pos, remaining, request.color())) + return true; + } else if (request.liquidCost() > 0) { + var next = + remaining == 0 + ? MixingCapabilities.runtime().block("emptyContainer").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); + if (MixingCapabilities.config().sounds) + level.playSound(null, pos, MixingCapabilities.runtime().sound("soundRecipe"), SoundSource.BLOCKS, MixingCapabilities.runtime().floating("recipeSoundVolume"), 1); + player.containerMenu.broadcastChanges(); + return true; + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingRules.java b/src/main/java/online/astradev/cauldron/mixing/MixingRules.java new file mode 100644 index 0000000..e6d57e4 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingRules.java @@ -0,0 +1,37 @@ +package online.astradev.cauldron.mixing; + +import java.util.List; +import java.util.Locale; +import java.util.Set; + +public final class MixingRules { + private MixingRules() {} + + 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, + 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/mixing/MixingRuntime.java b/src/main/java/online/astradev/cauldron/mixing/MixingRuntime.java new file mode 100644 index 0000000..fef66f1 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingRuntime.java @@ -0,0 +1,100 @@ +package online.astradev.cauldron.mixing; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.util.Arrays; +import java.util.List; +import net.minecraft.core.particles.SimpleParticleType; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.LayeredCauldronBlock; + +/** Typed access to authored engine parameters; no concrete item, sound or geometry defaults. */ +public final class MixingRuntime { + private final JsonObject values; + private final double[] orbitAngles; + + MixingRuntime(JsonObject values, String schemaJson) { + if (values == null) throw new IllegalArgumentException("Missing mixing engine parameters"); + this.values = values.deepCopy(); + var schema = JsonParser.parseString(schemaJson).getAsJsonObject(); + for (var entry : schema.getAsJsonArray("fields")) { + var field = entry.getAsJsonObject(); + String path = field.get("path").getAsString(); + if (!path.startsWith("engine.")) continue; + String key = path.substring("engine.".length()); + JsonElement value = required(key); + switch (field.get("type").getAsString()) { + case "integer", "number" -> { + if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isNumber()) throw invalid(key); + double number = value.getAsDouble(); + if (!Double.isFinite(number) || (field.get("type").getAsString().equals("integer") && number != Math.rint(number)) + || (field.has("min") && number < field.get("min").getAsDouble()) + || (field.has("max") && number > field.get("max").getAsDouble())) throw invalid(key); + } + case "string" -> { if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString() || value.getAsString().isBlank()) throw invalid(key); } + case "strings" -> { strings(key); } + default -> throw new IllegalArgumentException("Unsupported mixing engine parameter type"); + } + } + orbitAngles = angles(); + if (orbitAngles.length < integer("maxIngredientCount")) throw new IllegalArgumentException("Provide an orbit angle for every ingredient slot"); + // ColoredWaterApi is a native cauldron-surface primitive with a bounded height contract. + if (decimal("liquidBaseHeight") < .25 || decimal("liquidBaseHeight") + decimal("liquidHeightRange") > 1 + || decimal("waterBaseHeight") + decimal("waterStepHeight") < .25 + // Existing saved pots can retain all three native levels after lowering the new-fill limit. + || decimal("waterBaseHeight") + decimal("waterStepHeight") * 3 > 1) + throw new IllegalArgumentException("Authored liquid surfaces must remain within height 0.25..1"); + } + + private JsonElement required(String key) { + var value = values.get(key); + if (value == null || value.isJsonNull()) throw invalid(key); + return value; + } + private static IllegalArgumentException invalid(String key) { return new IllegalArgumentException("Invalid mixing parameter engine." + key); } + public String text(String key) { return required(key).getAsString(); } + public int integer(String key) { return required(key).getAsInt(); } + public double decimal(String key) { return required(key).getAsDouble(); } + public float floating(String key) { return required(key).getAsFloat(); } + public List strings(String key) { + var value = required(key); + if (!value.isJsonArray() || value.getAsJsonArray().asList().stream().anyMatch(entry -> !entry.isJsonPrimitive() || !entry.getAsJsonPrimitive().isString())) throw invalid(key); + return value.getAsJsonArray().asList().stream().map(JsonElement::getAsString).toList(); + } + public Identifier identifier(String key) { return Identifier.parse(text(key)); } + public Item item(String key) { return BuiltInRegistries.ITEM.get(identifier(key)).orElseThrow(() -> invalid(key)).value(); } + public Block block(String key) { return BuiltInRegistries.BLOCK.get(identifier(key)).orElseThrow(() -> invalid(key)).value(); } + public SoundEvent sound(String key) { return BuiltInRegistries.SOUND_EVENT.get(identifier(key)).orElseThrow(() -> invalid(key)).value(); } + public SimpleParticleType particle(String key) { + var value = BuiltInRegistries.PARTICLE_TYPE.get(identifier(key)).orElseThrow(() -> invalid(key)).value(); + if (!(value instanceof SimpleParticleType simple)) throw new IllegalArgumentException("Mixing particles must not require additional parameters: " + key); + return simple; + } + public boolean itemMatches(ItemStack stack, String key) { return strings(key).contains(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()); } + private double[] angles() { + double[] angles = Arrays.stream(text("orbitAngles").split(",", -1)).map(String::trim).mapToDouble(Double::parseDouble).toArray(); + if (Arrays.stream(angles).anyMatch(angle -> !Double.isFinite(angle))) throw invalid("orbitAngles"); + return angles; + } + public double orbitAngle(int slot) { return Math.toRadians(orbitAngles[Math.floorMod(slot, orbitAngles.length)]); } + + /** Registry-dependent preparation runs before writing and never in the publisher. */ + void validateResources() { + for (String key : List.of("carrier", "remainder", "specialFood", "potionBase", "consumeTemplate", "glassBottle", "waterBucket", "bucket")) item(key); + for (String key : List.of("emptyContainer", "waterContainer", "lavaContainer", "snowContainer", "normalHeat", "soulHeat")) block(key); + for (String key : List.of("soundFill", "soundStart", "soundIngredient", "soundComplete", "soundRecipe")) sound(key); + for (String key : List.of("heatBubbleParticle", "heatSplashParticle", "completionParticle")) particle(key); + for (String key : List.of("normalizedItems", "potionItems")) for (String id : strings(key)) + BuiltInRegistries.ITEM.get(Identifier.parse(id)).orElseThrow(() -> invalid(key)); + identifier("model"); + identifier("waterPotion"); + if (!block("waterContainer").defaultBlockState().hasProperty(LayeredCauldronBlock.LEVEL) + || !LayeredCauldronBlock.LEVEL.getPossibleValues().contains(integer("maxLiquidLevels"))) throw invalid("waterContainer"); + } +} diff --git a/src/main/java/online/astradev/cauldron/mixing/MixingText.java b/src/main/java/online/astradev/cauldron/mixing/MixingText.java new file mode 100644 index 0000000..66ae655 --- /dev/null +++ b/src/main/java/online/astradev/cauldron/mixing/MixingText.java @@ -0,0 +1,19 @@ +package online.astradev.cauldron.mixing; + +final class MixingText { + private MixingText() {} + + 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/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index b065b26..541fe43 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -6,6 +6,8 @@ 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" @@ -19,6 +21,6 @@ side="SERVER" [[dependencies.astracauldron]] modId="astraplus" type="required" -versionRange="[0.9.9,0.10)" +versionRange="[0.9.12,0.10)" ordering="AFTER" side="SERVER" diff --git a/src/main/resources/astracauldron.mixins.json b/src/main/resources/astracauldron.mixins.json new file mode 100644 index 0000000..6d07d49 --- /dev/null +++ b/src/main/resources/astracauldron.mixins.json @@ -0,0 +1,12 @@ +{ + "required": true, + "package": "online.astradev.cauldron.mixin", + "compatibilityLevel": "JAVA_25", + "mixins": [ + "MixingHeatMixin", + "MixingStackMixin", + "MixingWeatherMixin", + "MixingLevelMixin" + ], + "injectors": {"defaultRequire": 1} +} diff --git a/src/test/java/online/astradev/cauldron/AstraCauldronTest.java b/src/test/java/online/astradev/cauldron/AstraCauldronTest.java new file mode 100644 index 0000000..cdaceef --- /dev/null +++ b/src/test/java/online/astradev/cauldron/AstraCauldronTest.java @@ -0,0 +1,39 @@ +package online.astradev.cauldron; + +import com.google.gson.JsonParser; +import online.astradev.cauldron.mixing.MixingConfig; +import online.astradev.cauldron.mixing.MixingProfile; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class AstraCauldronTest { + @Test void packagedPolicyIsCompleteAndKeepsWorldAndItemIdentity() throws Exception { + var config = MixingConfig.parse(AstraCauldron.resource("defaults"), + AstraCauldron.resource("defaults"), AstraCauldron.resource("schema")); + assertEquals(4, config.ingredientCount); + var profile = MixingProfile.parse(JsonParser.parseString( + AstraCauldron.resource("compatibility")).getAsJsonObject()); + assertEquals("astracauldron/cauldrons.json", profile.soupPath()); + assertEquals("astracauldron/liquids.json", profile.liquidPath()); + assertEquals("cauldrons", profile.entriesKey()); + assertEquals("astracauldron:cauldrons", profile.waterOwner().toString()); + assertEquals("astracauldron:liquids", profile.liquidOwner().toString()); + assertEquals("astracauldron:combined_soup", profile.markerTag()); + assertEquals("astracauldron:soup_color", profile.colorTag()); + assertEquals("astracauldron:cauldron_visual", profile.visualTag()); + assertEquals(java.util.List.of("cauldron", "soups"), profile.commands()); + } + + @Test void moduleOwnsAllFourNarrowVanillaHooks() throws Exception { + try (var stream = getClass().getResourceAsStream("/astracauldron.mixins.json")) { + assertNotNull(stream); + var mixins = JsonParser.parseString(new String(stream.readAllBytes(), + java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + assertEquals("online.astradev.cauldron.mixin", mixins.get("package").getAsString()); + assertEquals(java.util.Set.of("MixingHeatMixin", "MixingStackMixin", "MixingWeatherMixin", "MixingLevelMixin"), + mixins.getAsJsonArray("mixins").asList().stream() + .map(com.google.gson.JsonElement::getAsString).collect(java.util.stream.Collectors.toSet())); + } + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/ConfigurationPolicyTest.java b/src/test/java/online/astradev/cauldron/mixing/ConfigurationPolicyTest.java new file mode 100644 index 0000000..706dd67 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/ConfigurationPolicyTest.java @@ -0,0 +1,44 @@ +package online.astradev.cauldron.mixing; + +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 = MixingFixtures.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(MixingRules.rejection(ingredients, List.of(), List.of(), 2)); + assertNotNull( + MixingRules.rejection(ingredients, List.of("material:carrot"), List.of(), 2)); + assertNotNull( + MixingRules.rejection( + ingredients, + List.of(), + List.of(List.of("material:carrot", "material:potato")), + 2)); + assertNotNull(MixingRules.rejection(ingredients, List.of(), List.of(), 3)); + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/IngredientUpdateTest.java b/src/test/java/online/astradev/cauldron/mixing/IngredientUpdateTest.java new file mode 100644 index 0000000..f295b77 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/IngredientUpdateTest.java @@ -0,0 +1,27 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class IngredientUpdateTest { + @Test + void nutritionUpdatePreservesConfiguredColorAndEffects() { + var config = MixingFixtures.config(); + var original = config.updateIngredient("herb", 2, .5f); + original.color = "#70AA40"; + var effect = new MixingConfig.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/mixing/MixingAnimationTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingAnimationTest.java new file mode 100644 index 0000000..2a1b8a1 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingAnimationTest.java @@ -0,0 +1,73 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class MixingAnimationTest { + @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 = MixingAnimation.frame(MixingFixtures.config().runtime(), 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 = MixingAnimation.frame(MixingFixtures.config().runtime(), 0, 3, tick, 0, 0); + assertTrue(.9375 - p.y() >= .05 && .9375 - p.y() <= .06); + } + } + + @Test + void whirlpoolKeepsRadiusThroughoutRotation() { + var start = MixingAnimation.frame(MixingFixtures.config().runtime(), 0, 3, 0, 0, 80); + var middle = MixingAnimation.frame(MixingFixtures.config().runtime(), 0, 3, 40, 40, 80); + var end = MixingAnimation.frame(MixingFixtures.config().runtime(), 0, 3, 80, 80, 80); + for (int tick = 0; tick <= 80; tick++) { + var p = MixingAnimation.frame(MixingFixtures.config().runtime(), 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( + MixingAnimation.frame(MixingFixtures.config().runtime(), 2, 3, 15, 0, 0), MixingAnimation.frame(MixingFixtures.config().runtime(), 2, 3, 15, 0, 80)); + } + + @Test + void everyPortionLowersLiquidAndUnderlyingWater() { + for (int remaining = 4; remaining > 0; remaining--) { + assertEquals(remaining - 1, MixingAnimation.waterLevel(MixingFixtures.config().runtime(), remaining, 4)); + assertTrue( + MixingAnimation.liquidHeight(MixingFixtures.config().runtime(), remaining, 4) + > MixingAnimation.liquidHeight(MixingFixtures.config().runtime(), remaining - 1, 4)); + int water = MixingAnimation.waterLevel(MixingFixtures.config().runtime(), remaining, 4); + if (water > 0) + assertTrue(.375 + .1875 * water <= MixingAnimation.liquidHeight(MixingFixtures.config().runtime(), remaining, 4)); + } + } + + @Test + void arbitraryBatchSizesNeverExposeBlueWaterAboveSoup() { + for (int capacity = 1; capacity <= 16; capacity++) + for (int remaining = 1; remaining <= capacity; remaining++) { + int water = MixingAnimation.waterLevel(MixingFixtures.config().runtime(), remaining, capacity); + if (water > 0) + assertTrue( + .375 + .1875 * water + <= MixingAnimation.liquidHeight(MixingFixtures.config().runtime(), remaining, capacity) + + .00001); + } + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingAuthoringTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingAuthoringTest.java new file mode 100644 index 0000000..e5e41a5 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingAuthoringTest.java @@ -0,0 +1,73 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; + +import com.google.gson.JsonParser; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import online.astradev.plus.api.editor.FileEditorDefinition; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class MixingAuthoringTest { + @TempDir Path directory; + + @Test + void savedRulesImmediatelyChangeCombinationOutcomeWithoutRewritingExtensions() throws Exception { + var file = directory.resolve("astracauldron.json"); + String original = "{\"ingredientCount\":2,\"extension\":{\"keep\":true}}"; + Files.writeString(file, original); + var current = new AtomicReference<>(MixingFixtures.load(file)); + var provider = MixingAuthoring.provider(file, "test:mixing", "Test mixing", MixingFixtures.defaults(), MixingFixtures.schema(), MixingFixtures::parse, current::set); + var ingredients = List.of(Set.of("material:carrot"), Set.of("material:potato")); + assertNull(rejection(current.get(), ingredients)); + var snapshot = provider.snapshot(); + var changed = JsonParser.parseString(snapshot.documentJson()).getAsJsonObject(); + changed.add("incompatible", JsonParser.parseString("[[\"material:carrot\",\"material:potato\"]]")); + changed.addProperty("brewSeconds", 2.5); + changed.addProperty("cakeNutrition", 18); + changed.add("ingredientColors", JsonParser.parseString("{\"carrot\":\"#112233\"}")); + provider.save(changed.toString(), snapshot.revision()); + assertNotNull(rejection(current.get(), ingredients), "the running rules, not a description, change"); + assertEquals(2.5, current.get().brewSeconds); + assertEquals(18, current.get().cakeNutrition); + assertEquals(0x112233, current.get().ingredientColor("carrot")); + assertTrue(JsonParser.parseString(Files.readString(file)).getAsJsonObject().getAsJsonObject("extension").get("keep").getAsBoolean()); + assertThrows(FileEditorDefinition.Conflict.class, () -> provider.save(original, snapshot.revision())); + String persisted = Files.readString(file); + changed.addProperty("ingredientCount", 8); + assertThrows(IllegalArgumentException.class, () -> provider.save(changed.toString(), provider.snapshot().revision())); + assertEquals(persisted, Files.readString(file)); + assertEquals(2, current.get().ingredientCount); + } + + @Test + void everyFunctionalSettingHasAFormFieldAndSourceDefault() { + var schema = JsonParser.parseString(MixingAuthoring.schema(MixingFixtures.defaults(), MixingFixtures.schema())).getAsJsonObject(); + var covered = new HashSet(); + for (var value : schema.getAsJsonArray("fields")) { + var field = value.getAsJsonObject(); + assertTrue(field.has("default")); + assertTrue(covered.add(field.get("path").getAsString())); + } + for (var field : MixingConfig.class.getFields()) { + if (!Modifier.isStatic(field.getModifiers()) && !field.getName().equals("engine")) assertTrue(covered.remove(field.getName()), field.getName()); + } + for (String key : MixingFixtures.config().engine.keySet()) assertTrue(covered.remove("engine." + key), key); + assertTrue(covered.isEmpty()); + var defaults = MixingFixtures.config(); + assertEquals(14, defaults.cakeNutrition); + assertEquals(2.8f, defaults.cakeSaturation); + assertEquals(0xC73735, defaults.ingredientColor("apple")); + assertEquals(0xB77A36, defaults.ingredientColor("unknown")); + } + + private static String rejection(MixingConfig config, List> ingredients) { + return MixingRules.rejection(ingredients, config.blockedIngredients, config.incompatible, config.ingredientCount); + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingConfigTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingConfigTest.java new file mode 100644 index 0000000..4dd5c31 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingConfigTest.java @@ -0,0 +1,51 @@ +package online.astradev.cauldron.mixing; + +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 MixingConfigTest { + @TempDir Path root; + + @Test + void writesDefaultsAndRejectsInvalidFileWithoutReplacingIt() throws Exception { + Path path = root.resolve("config.json"); + assertEquals(4, MixingFixtures.load(path).servingsPerBrew); + String broken = "{\"brewSeconds\":0}"; + Files.writeString(path, broken); + assertThrows(IllegalArgumentException.class, () -> MixingFixtures.load(path)); + assertEquals(broken, Files.readString(path)); + } + + @Test + void validatesSelectorsAndDistinctCustomIdentityModes() { + var c = MixingFixtures.config(); + 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 MixingConfig.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 = MixingFixtures.config(); + 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/mixing/MixingFixtures.java b/src/test/java/online/astradev/cauldron/mixing/MixingFixtures.java new file mode 100644 index 0000000..f0e8f58 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingFixtures.java @@ -0,0 +1,19 @@ +package online.astradev.cauldron.mixing; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; + +final class MixingFixtures { + static String defaults() { return resource("defaults"); } + static String schema() { return resource("schema"); } + static MixingConfig config() { return parse("{}"); } + static MixingConfig parse(String document) { return MixingConfig.parse(document, defaults(), schema()); } + static MixingConfig load(Path file) throws IOException { return MixingConfig.load(file, defaults(), schema()); } + private static String resource(String type) { + try (var input = MixingFixtures.class.getResourceAsStream("/editor/combination-" + type + ".json")) { + if (input == null) throw new IllegalStateException("Missing starter policy fixture: " + type); + return new String(input.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException error) { throw new IllegalStateException(error); } + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingLifecycleTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingLifecycleTest.java new file mode 100644 index 0000000..cd496ea --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingLifecycleTest.java @@ -0,0 +1,26 @@ +package online.astradev.cauldron.mixing; + +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class MixingLifecycleTest { + @Test void shutdownKeepsOnlyImmutableCommandIdentityForTheNextDispatcher() throws Exception { + try (var stream = getClass().getResourceAsStream("/editor/combination-compatibility.json")) { + assertNotNull(stream); + var compatibility = JsonParser.parseString(new String(stream.readAllBytes(), + java.nio.charset.StandardCharsets.UTF_8)).getAsJsonObject(); + MixingCapabilities.declareCompatibility(compatibility); + var declared = MixingCapabilities.profile(); + MixingCapabilities.close(); + MixingCapabilities.close(); + assertSame(declared, MixingCapabilities.profile()); + assertEquals(java.util.List.of("cauldron", "soups"), MixingCapabilities.profile().commands()); + assertFalse(MixingCapabilities.active()); + assertNull(MixingCapabilities.pots()); + assertNull(MixingCapabilities.liquids()); + assertNull(MixingCapabilities.config()); + } + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingRulesTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingRulesTest.java new file mode 100644 index 0000000..71c80ae --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingRulesTest.java @@ -0,0 +1,67 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +import java.util.*; + +class MixingRulesTest { + private static String rejectFour(List> ingredients, List blocked, List> pairs) { + return MixingRules.rejection(ingredients, blocked, pairs, 4); + } + 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(rejectFour(four.subList(0, 3), List.of(), List.of())); + assertNull(rejectFour(four, List.of(), List.of())); + } + + @Test + void blockedSelectorsAreCaseInsensitive() { + assertNotNull(rejectFour(four, List.of("material:BEEF"), List.of())); + } + + @Test + void compatibilityIsSymmetricAcrossSlots() { + assertNotNull( + rejectFour( + four, + List.of(), + List.of( + List.of( + "effect:minecraft:weakness", + "effect:minecraft:strength")))); + } + + @Test + void oneIngredientDoesNotConflictWithItself() { + assertNull( + rejectFour( + four, + List.of(), + List.of(List.of("material:potion", "effect:minecraft:weakness")))); + } + + @Test + void duplicatesCanBeForbiddenExplicitly() { + assertNotNull( + rejectFour( + four, List.of(), List.of(List.of("material:beef", "material:beef")))); + assertNull( + rejectFour( + four, List.of(), List.of(List.of("material:carrot", "material:carrot")))); + } + + @Test + void wildcardAndUnknownSelector() { + assertNotNull(rejectFour(four, List.of("*"), List.of())); + assertNull(rejectFour(four, List.of("custom:other"), List.of())); + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingRuntimeTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingRuntimeTest.java new file mode 100644 index 0000000..316fa83 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingRuntimeTest.java @@ -0,0 +1,64 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; +import com.google.gson.JsonParser; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class MixingRuntimeTest { + @TempDir Path directory; + + @Test void existingConfigurationAddsEngineDefaultsInMemoryWithoutWritingOrMergingAuthoredMaps() throws Exception { + var file = directory.resolve("native.json"); + String nativeJson = "{\"ingredientColors\":{\"carrot\":\"#010203\"},\"extension\":true,\"engine\":{\"orbitRadius\":0.1}}"; + Files.writeString(file, nativeJson); + var config = MixingFixtures.load(file); + assertEquals(nativeJson, Files.readString(file)); + assertEquals(.1, config.runtime().decimal("orbitRadius")); + assertEquals(0x010203, config.ingredientColor("carrot")); + assertEquals(MixingConfig.rgb(config.defaultColor), config.ingredientColor("apple")); + assertEquals("astradev_soups:combined_soup", config.runtime().text("model")); + } + + @Test void authoredGeometryAndLimitsDriveRuntimeInsteadOfSourceConstants() { + var document = JsonParser.parseString(MixingFixtures.defaults()).getAsJsonObject(); + var engine = document.getAsJsonObject("engine"); + engine.addProperty("maxIngredientCount", 5); + engine.addProperty("orbitAngles", "0,72,144,216,288"); + engine.addProperty("orbitRadius", .1); + engine.addProperty("bobHeight", 0); + engine.addProperty("ingredientSubmersion", .1); + engine.addProperty("waterBaseHeight", .2); + engine.addProperty("waterStepHeight", .1); + document.addProperty("ingredientCount", 5); + var config = MixingFixtures.parse(document.toString()); + var frame = MixingAnimation.frame(config.runtime(), 0, 3, 0, 0, 0); + assertEquals(.6, frame.x(), .000001); + assertEquals(.4, frame.y(), .000001); + assertEquals(.5, frame.z(), .000001); + engine.addProperty("maxIngredientCount", 6); + assertThrows(IllegalArgumentException.class, () -> MixingFixtures.parse(document.toString())); + } + + @Test void surfaceBoundsAreRejectedBeforeRuntimePublication() { + assertThrows(IllegalArgumentException.class, + () -> MixingFixtures.parse("{\"engine\":{\"waterBaseHeight\":0.9,\"waterStepHeight\":0.2}}")); + assertThrows(IllegalArgumentException.class, + () -> MixingFixtures.parse("{\"engine\":{\"liquidBaseHeight\":0.1}}")); + } + + @Test void immutableCompatibilityKeepsOldWorldKeysAndRejectsTraversal() throws Exception { + String json; + try (var stream = getClass().getResourceAsStream("/editor/combination-compatibility.json")) { + json = new String(stream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8); + } + var raw = JsonParser.parseString(json).getAsJsonObject(); + var profile = MixingProfile.parse(raw); + assertEquals("astracauldron/cauldrons.json", profile.soupPath()); + assertEquals("astracauldron:combined_soup", profile.markerTag()); + raw.addProperty("soupPath", "../outside.json"); + assertThrows(IllegalArgumentException.class, () -> MixingProfile.parse(raw)); + } +} diff --git a/src/test/java/online/astradev/cauldron/mixing/MixingTextTest.java b/src/test/java/online/astradev/cauldron/mixing/MixingTextTest.java new file mode 100644 index 0000000..87ae974 --- /dev/null +++ b/src/test/java/online/astradev/cauldron/mixing/MixingTextTest.java @@ -0,0 +1,18 @@ +package online.astradev.cauldron.mixing; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class MixingTextTest { + @Test + void formatsPotionLevelsAsRomanNumerals() { + assertEquals("I", MixingText.roman(1)); + assertEquals("II", MixingText.roman(2)); + assertEquals("IV", MixingText.roman(4)); + assertEquals("IX", MixingText.roman(9)); + assertEquals("XL", MixingText.roman(40)); + assertEquals("XC", MixingText.roman(90)); + assertEquals("CCLVI", MixingText.roman(256)); + } +}