Use standard bundled assets and simplify cauldron interactions

This commit is contained in:
2026-09-13 23:17:48 +03:00
parent 3de2fdf81e
commit 90f8873de2
14 changed files with 245 additions and 349 deletions
+3 -1
View File
@@ -1,8 +1,10 @@
# AstraCauldron # AstraCauldron
Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**. Серверный мод котлов для **Minecraft 26.2 / NeoForge 26.2.0.79 / Java 25+**.
Требуется **AstraPlus 0.9.2+**. Требуется **AstraPlus 0.9.3+**.
Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks. Игроку достаточно ванильного клиента и актуального ресурспака AstraPlus/AstraPacks.
Модели супа зарегистрированы через AstraPlus и берутся из JAR. Пользовательские замены
можно положить в `astraplus/resources/assets/astradev_soups`; мод не переписывает их.
## Режимы котла ## Режимы котла
+5 -2
View File
@@ -3,10 +3,10 @@ plugins {
id("net.neoforged.moddev") version "2.0.146" id("net.neoforged.moddev") version "2.0.146"
} }
group = "online.astradev" group = "online.astradev"
version = "0.3.4" version = "0.3.5"
repositories { mavenCentral() } repositories { mavenCentral() }
val astraPlusApi = providers.gradleProperty("astraPlusApi") val astraPlusApi = providers.gradleProperty("astraPlusApi")
.orElse("../AstraPlus/build/libs/AstraPlus-0.9.2.jar") .orElse("../AstraPlus/build/libs/AstraPlus-0.9.3.jar")
dependencies { dependencies {
compileOnly(files(astraPlusApi)) compileOnly(files(astraPlusApi))
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
@@ -25,9 +25,12 @@ tasks.withType<JavaCompile>().configureEach {
options.release.set(25) options.release.set(25)
} }
tasks.processResources { tasks.processResources {
includeEmptyDirs = false
inputs.property("modVersion", project.version) inputs.property("modVersion", project.version)
filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) } filesMatching("META-INF/neoforge.mods.toml") { expand("version" to project.version) }
} }
tasks.withType<Jar>().configureEach { includeEmptyDirs = false }
tasks.test { useJUnitPlatform() } tasks.test { useJUnitPlatform() }
sourceSets.test { sourceSets.test {
compileClasspath += sourceSets.main.get().compileClasspath compileClasspath += sourceSets.main.get().compileClasspath
@@ -22,9 +22,12 @@ import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent; import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent; import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.level.*; 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.server.*;
import net.neoforged.neoforge.event.tick.ServerTickEvent; import net.neoforged.neoforge.event.tick.ServerTickEvent;
import online.astradev.plus.api.AstraPlusApi;
import org.slf4j.*; import org.slf4j.*;
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER) @Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
@@ -35,7 +38,6 @@ public final class AstraCauldron {
private static LiquidPots liquids; private static LiquidPots liquids;
public AstraCauldron() { public AstraCauldron() {
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
NeoForge.EVENT_BUS.addListener(this::start); NeoForge.EVENT_BUS.addListener(this::start);
NeoForge.EVENT_BUS.addListener(this::stop); NeoForge.EVENT_BUS.addListener(this::stop);
NeoForge.EVENT_BUS.addListener(this::tick); NeoForge.EVENT_BUS.addListener(this::tick);
@@ -48,17 +50,9 @@ public final class AstraCauldron {
NeoForge.EVENT_BUS.addListener(this::commands); NeoForge.EVENT_BUS.addListener(this::commands);
} }
private void resources(ServerAboutToStartEvent event) {
try {
SoupResources.install(FMLPaths.GAMEDIR.get());
} catch (Exception e) {
throw new IllegalStateException("Cannot export AstraCauldron resources", e);
}
}
private void start(ServerStartedEvent event) { private void start(ServerStartedEvent event) {
try { try {
online.astradev.plus.api.AstraPlusApi.current() AstraPlusApi.current()
.orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable")); .orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
pots = pots =
new SoupPots( new SoupPots(
@@ -119,7 +113,7 @@ public final class AstraCauldron {
event.setCancellationResult(InteractionResult.SUCCESS); event.setCancellationResult(InteractionResult.SUCCESS);
} }
private void breakBlock(net.neoforged.neoforge.event.level.block.BreakBlockEvent event) { private void breakBlock(BreakBlockEvent event) {
if (event.isCanceled() || pots == null) return; if (event.isCanceled() || pots == null) return;
if (!(event.getLevel() instanceof ServerLevel level)) return; if (!(event.getLevel() instanceof ServerLevel level)) return;
boolean removed = pots.breakPot(level, event.getPos()); boolean removed = pots.breakPot(level, event.getPos());
@@ -1,13 +1,14 @@
package online.astradev.cauldron; package online.astradev.cauldron;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Set; import java.util.Set;
public final class CombinationRules { public final class CombinationRules {
private CombinationRules() {} private CombinationRules() {}
public static boolean matches(Set<String> tags, String selector) { public static boolean matches(Set<String> tags, String selector) {
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT)); return selector.equals("*") || tags.contains(selector.toLowerCase(Locale.ROOT));
} }
public static String rejection( public static String rejection(
@@ -12,6 +12,7 @@ import net.minecraft.server.level.*;
import net.minecraft.sounds.*; import net.minecraft.sounds.*;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.item.*; import net.minecraft.world.item.*;
import net.minecraft.world.item.alchemy.PotionContents;
import net.minecraft.world.item.alchemy.Potions; import net.minecraft.world.item.alchemy.Potions;
import net.minecraft.world.level.block.*; import net.minecraft.world.level.block.*;
import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.LevelResource;
@@ -64,30 +65,31 @@ public final class LiquidPots implements AutoCloseable {
this.server = server; this.server = server;
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow(); api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json"); file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
if (Files.exists(file)) { if (Files.exists(file)) load();
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject(); }
if (json.get("version").getAsInt() != 1)
throw new IllegalArgumentException("Unknown liquid data version"); private void load() throws IOException {
for (var entry : json.getAsJsonArray("cauldrons")) { var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
var c = entry.getAsJsonObject(); if (json.get("version").getAsInt() != 1) {
var pos = throw new IllegalArgumentException("Unknown liquid data version");
new Position( }
Identifier.parse(c.get("dimension").getAsString()).toString(), for (var entry : json.getAsJsonArray("cauldrons")) {
new BlockPos( var record = entry.getAsJsonObject();
c.get("x").getAsInt(), String dimension = Identifier.parse(record.get("dimension").getAsString()).toString();
c.get("y").getAsInt(), int x = record.get("x").getAsInt();
c.get("z").getAsInt())); int y = record.get("y").getAsInt();
CauldronApi.Potion potion = int z = record.get("z").getAsInt();
c.has("potion") var position = new Position(dimension, new BlockPos(x, y, z));
? api.potion( CauldronApi.Potion potion = null;
SoupFiles.decode( if (record.has("potion")) {
c.get("potion"), server.registryAccess())) ItemStack bottle = SoupFiles.decode(record.get("potion"), server.registryAccess());
.orElseThrow() potion = api.potion(bottle).orElseThrow();
: null; }
var liquid = int levels = record.get("levels").getAsInt();
new Liquid(c.get("levels").getAsInt(), c.get("rgb").getAsInt(), potion); int color = record.get("rgb").getAsInt();
if (liquids.putIfAbsent(pos, liquid) != null) var liquid = new Liquid(levels, color, potion);
throw new IllegalArgumentException("Duplicate liquid cauldron"); if (liquids.putIfAbsent(position, liquid) != null) {
throw new IllegalArgumentException("Duplicate liquid cauldron");
} }
} }
} }
@@ -121,27 +123,7 @@ public final class LiquidPots implements AutoCloseable {
if (next == null) liquids.remove(pos); if (next == null) liquids.remove(pos);
else liquids.put(pos, next); else liquids.put(pos, next);
try { try {
var root = new JsonObject(); save();
root.addProperty("version", 1);
var array = new JsonArray();
root.add("cauldrons", array);
for (var entry : liquids.entrySet()) {
var p = entry.getKey();
var liquid = entry.getValue();
var c = new JsonObject();
c.addProperty("dimension", p.dimension);
c.addProperty("x", p.pos.getX());
c.addProperty("y", p.pos.getY());
c.addProperty("z", p.pos.getZ());
c.addProperty("levels", liquid.levels);
c.addProperty("rgb", liquid.rgb);
if (liquid.potion != null)
c.add(
"potion",
SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess()));
array.add(c);
}
SoupFiles.write(file, root);
if (next == null) removeSurface(pos); if (next == null) removeSurface(pos);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
@@ -152,6 +134,30 @@ public final class LiquidPots implements AutoCloseable {
} }
} }
private void save() throws IOException {
var root = new JsonObject();
root.addProperty("version", 1);
var array = new JsonArray();
root.add("cauldrons", array);
for (var entry : liquids.entrySet()) {
var p = entry.getKey();
var liquid = entry.getValue();
var c = new JsonObject();
c.addProperty("dimension", p.dimension);
c.addProperty("x", p.pos.getX());
c.addProperty("y", p.pos.getY());
c.addProperty("z", p.pos.getZ());
c.addProperty("levels", liquid.levels);
c.addProperty("rgb", liquid.rgb);
if (liquid.potion != null)
c.add(
"potion",
SoupFiles.encode(api.bottle(liquid.potion), server.registryAccess()));
array.add(c);
}
SoupFiles.write(file, root);
}
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) { public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
if (player.isSpectator()) return false; if (player.isSpectator()) return false;
var level = player.level(); var level = player.level();
@@ -159,141 +165,148 @@ public final class LiquidPots implements AutoCloseable {
var liquid = liquids.get(pos); var liquid = liquids.get(pos);
if (hand != InteractionHand.MAIN_HAND) return liquid != null; if (hand != InteractionHand.MAIN_HAND) return liquid != null;
var state = level.getBlockState(blockPos); var state = level.getBlockState(blockPos);
var held = player.getMainHandItem();
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false; if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
if (liquid == null) return fillVanilla(player, pos);
if (liquid.potion == null) return useDyedWater(player, pos, liquid);
return usePotion(player, pos, liquid);
}
private boolean fillVanilla(ServerPlayer player, Position pos) {
var level = player.level();
var blockPos = pos.pos;
var held = player.getMainHandItem();
var state = level.getBlockState(blockPos);
var potion = api.potion(held); var potion = api.potion(held);
if (liquid == null) { if (potion.isPresent() && plainWater(potion.get())) {
if (potion.isPresent() && plainWater(potion.get())) { int current =
int current = state.is(Blocks.WATER_CAULDRON)
state.is(Blocks.WATER_CAULDRON) ? state.getValue(LayeredCauldronBlock.LEVEL)
? state.getValue(LayeredCauldronBlock.LEVEL) : 0;
: 0; if (current < 3) {
if (current < 3) {
level.setBlock(
blockPos,
Blocks.WATER_CAULDRON
.defaultBlockState()
.setValue(LayeredCauldronBlock.LEVEL, current + 1),
3);
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
}
return true;
}
var dye = api.mixDye(OptionalInt.empty(), held);
if (AstraCauldron.config().dyeWater
&& state.is(Blocks.WATER_CAULDRON)
&& dye.isPresent()) {
var next =
new Liquid(
state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
if (!change(pos, next)) {
error(player);
return true;
}
held.consume(1, player);
setVisual(level, pos, next);
say(
player,
"Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно"
+ " смешивать.");
return true;
}
if (AstraCauldron.config().storePotions
&& state.is(Blocks.CAULDRON)
&& potion.isPresent()) {
var next =
new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
if (!change(pos, next)) {
error(player);
return true;
}
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
setVisual(level, pos, next);
say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать.");
return true;
}
return false;
}
if (liquid.potion == null) {
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
if (AstraCauldron.config().dyeWater && dye.isPresent()) {
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
if (!change(pos, next)) {
error(player);
return true;
}
held.consume(1, player);
setVisual(level, pos, next);
return true;
}
var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
var batch = blocks.get();
var result = batch.result();
if (!decrease(level, pos, liquid, batch.levelsUsed())) {
error(player);
return true;
}
int count = result.getCount();
consumeAndGive(player, count, result);
sound(level, blockPos);
say(player, "Окрашено предметов: " + count + ".");
return true;
}
var armor = api.dyeArmor(held, liquid.rgb);
if (AstraCauldron.config().dyeArmor && armor.isPresent()) {
if (!decrease(level, pos, liquid, 1)) {
error(player);
return true;
}
// Transform the equipped item, including Creative, preserving
// enchantments/damage/name.
if (held.getCount() == 1) player.setItemInHand(hand, armor.get());
else consumeAndGive(player, 1, armor.get());
sound(level, blockPos);
say(player, "Броня окрашена. Израсходован один уровень воды.");
return true;
}
if (held.is(Items.WATER_BUCKET)) {
if (!change(pos, null)) {
error(player);
return true;
}
level.setBlock( level.setBlock(
blockPos, blockPos,
Blocks.WATER_CAULDRON Blocks.WATER_CAULDRON
.defaultBlockState() .defaultBlockState()
.setValue(LayeredCauldronBlock.LEVEL, 3), .setValue(LayeredCauldronBlock.LEVEL, current + 1),
3); 3);
consumeAndGive(player, 1, new ItemStack(Items.BUCKET)); consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
return true;
} }
if (held.is(Items.BUCKET) && liquid.levels == 3) {
if (!decrease(level, pos, liquid, 3)) {
error(player);
return true;
}
consumeAndGive(player, 1, new ItemStack(Items.WATER_BUCKET));
return true;
}
if (held.is(Items.GLASS_BOTTLE)) {
if (!decrease(level, pos, liquid, 1)) {
error(player);
return true;
}
consumeAndGive(
player,
1,
api.bottle(
new CauldronApi.Potion(
new net.minecraft.world.item.alchemy.PotionContents(
Potions.WATER),
1)));
return true;
}
say(player, "Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода.");
return true; return true;
} }
var dye = api.mixDye(OptionalInt.empty(), held);
if (AstraCauldron.config().dyeWater && state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) {
var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
if (!change(pos, next)) {
error(player);
return true;
}
held.consume(1, player);
setVisual(level, pos, next);
say(
player,
"Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно"
+ " смешивать.");
return true;
}
if (AstraCauldron.config().storePotions
&& state.is(Blocks.CAULDRON)
&& potion.isPresent()) {
var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
if (!change(pos, next)) {
error(player);
return true;
}
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE));
setVisual(level, pos, next);
say(player, "Зелье налито: 1/3. Бутылочка — забрать, стрелы — обработать.");
return true;
}
return false;
}
private boolean useDyedWater(ServerPlayer player, Position pos, Liquid liquid) {
var level = player.level();
var blockPos = pos.pos;
var held = player.getMainHandItem();
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
if (AstraCauldron.config().dyeWater && dye.isPresent()) {
var next = new Liquid(liquid.levels, dye.getAsInt(), null);
if (!change(pos, next)) {
error(player);
return true;
}
held.consume(1, player);
setVisual(level, pos, next);
return true;
}
var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
var batch = blocks.get();
var result = batch.result();
if (!decrease(level, pos, liquid, batch.levelsUsed())) {
error(player);
return true;
}
int count = result.getCount();
consumeAndGive(player, count, result);
sound(level, blockPos);
say(player, "Окрашено предметов: " + count + ".");
return true;
}
var armor = api.dyeArmor(held, liquid.rgb);
if (AstraCauldron.config().dyeArmor && armor.isPresent()) {
if (!decrease(level, pos, liquid, 1)) {
error(player);
return true;
}
// Transform the equipped item, including Creative, preserving
// enchantments/damage/name.
if (held.getCount() == 1) player.setItemInHand(InteractionHand.MAIN_HAND, armor.get());
else consumeAndGive(player, 1, armor.get());
sound(level, blockPos);
say(player, "Броня окрашена. Израсходован один уровень воды.");
return true;
}
if (held.is(Items.WATER_BUCKET)) {
if (!change(pos, null)) {
error(player);
return true;
}
level.setBlock(
blockPos,
Blocks.WATER_CAULDRON
.defaultBlockState()
.setValue(LayeredCauldronBlock.LEVEL, 3),
3);
consumeAndGive(player, 1, new ItemStack(Items.BUCKET));
return true;
}
if (held.is(Items.BUCKET) && liquid.levels == 3) {
if (!decrease(level, pos, liquid, 3)) {
error(player);
return true;
}
consumeAndGive(player, 1, new ItemStack(Items.WATER_BUCKET));
return true;
}
if (held.is(Items.GLASS_BOTTLE)) {
if (!decrease(level, pos, liquid, 1)) {
error(player);
return true;
}
var water = new CauldronApi.Potion(new PotionContents(Potions.WATER), 1);
consumeAndGive(player, 1, api.bottle(water));
return true;
}
say(player, "Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода.");
return true;
}
private boolean usePotion(ServerPlayer player, Position pos, Liquid liquid) {
var level = player.level();
var blockPos = pos.pos;
var held = player.getMainHandItem();
var potion = api.potion(held);
if (potion.isPresent()) { if (potion.isPresent()) {
if (!AstraCauldron.config().storePotions) return true; if (!AstraCauldron.config().storePotions) return true;
if (!potion.get().equals(liquid.potion)) { if (!potion.get().equals(liquid.potion)) {
@@ -384,12 +397,9 @@ public final class LiquidPots implements AutoCloseable {
} }
private void surface(ServerLevel level, Position pos, Liquid liquid) { private void surface(ServerLevel level, Position pos, Liquid liquid) {
api.water() float height = 0.375f + 0.1875f * liquid.levels;
.show( var surface = new ColoredWaterApi.Surface(OWNER, liquid.rgb, height);
level, api.water().show(level, pos.pos, surface);
pos.pos,
new ColoredWaterApi.Surface(
OWNER, liquid.rgb, .375f + .1875f * liquid.levels));
} }
private ServerLevel level(Position pos) { private ServerLevel level(Position pos) {
@@ -3,6 +3,8 @@ package online.astradev.cauldron;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; 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.InteractionHand;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.Blocks;
@@ -70,13 +72,7 @@ public final class RegisteredRecipes {
held.consume(request.inputCount(), player); held.consume(request.inputCount(), player);
if (held.isEmpty()) player.setItemInHand(hand, output); if (held.isEmpty()) player.setItemInHand(hand, output);
else AstraPlusApi.give(player, output); else AstraPlusApi.give(player, output);
level.playSound( level.playSound(null, pos, SoundEvents.BUCKET_EMPTY, SoundSource.BLOCKS, 0.5F, 1);
null,
pos,
net.minecraft.sounds.SoundEvents.BUCKET_EMPTY,
net.minecraft.sounds.SoundSource.BLOCKS,
0.5F,
1);
player.containerMenu.broadcastChanges(); player.containerMenu.broadcastChanges();
return true; return true;
} }
@@ -18,6 +18,7 @@ import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.LevelResource; import net.minecraft.world.level.storage.LevelResource;
import online.astradev.plus.api.AstraPlusApi; import online.astradev.plus.api.AstraPlusApi;
import online.astradev.plus.api.ColoredWaterApi;
import java.io.IOException; import java.io.IOException;
import java.nio.file.*; import java.nio.file.*;
@@ -51,7 +52,7 @@ public final class SoupPots implements AutoCloseable {
private final MinecraftServer server; private final MinecraftServer server;
private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons"); private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons");
private final online.astradev.plus.api.ColoredWaterApi water; private final ColoredWaterApi water;
private final Path file; private final Path file;
private final Path configFile; private final Path configFile;
private SoupConfig config; private SoupConfig config;
@@ -63,10 +64,7 @@ public final class SoupPots implements AutoCloseable {
public SoupPots(MinecraftServer server, Path configFile) throws IOException { public SoupPots(MinecraftServer server, Path configFile) throws IOException {
this.server = server; this.server = server;
this.water = this.water = AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow();
online.astradev.plus.api.AstraPlusApi.current()
.flatMap(api -> api.coloredWater())
.orElseThrow();
this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json"); this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json");
this.configFile = configFile; this.configFile = configFile;
reload(); reload();
@@ -104,9 +102,7 @@ public final class SoupPots implements AutoCloseable {
var custom = new SoupConfig.Custom(); var custom = new SoupConfig.Custom();
// Resolve by stable AstraPlus identity; definitions can evolve without invalidating the // Resolve by stable AstraPlus identity; definitions can evolve without invalidating the
// registration. // registration.
var plus = var plus = AstraPlusApi.current().flatMap(api -> api.find(player.getMainHandItem()));
online.astradev.plus.api.AstraPlusApi.current()
.flatMap(api -> api.find(player.getMainHandItem()));
if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString(); if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString();
else else
custom.item = custom.item =
@@ -157,20 +153,35 @@ public final class SoupPots implements AutoCloseable {
} }
} }
private static void validate(Pot p) { private static void validate(Pot pot) {
if (p.items.size() > 4 if (pot.items.size() > 4)
|| p.items.stream().anyMatch(i -> i.isEmpty() || i.getCount() != 1) throw new IllegalArgumentException("Too many cauldron ingredients");
|| p.brewTicks < 0 for (ItemStack ingredient : pot.items) {
|| p.brewTicks > 1200 if (ingredient.isEmpty() || ingredient.getCount() != 1) {
|| (p.soup.isEmpty() throw new IllegalArgumentException("Cauldron ingredients must be single items");
? p.servings != 0 || p.capacity != 0 || p.brewing() || p.items.isEmpty() }
: p.soup.getCount() != 1 }
|| !Ingredients.isCombined(p.soup) if (pot.brewTicks < 0 || pot.brewTicks > 1200) {
|| p.servings < 1 throw new IllegalArgumentException("Invalid cauldron brewing time");
|| p.capacity < p.servings }
|| p.capacity > 16 if (pot.soup.isEmpty()) {
|| (p.brewing() ? p.items.isEmpty() : !p.items.isEmpty()))) if (pot.servings != 0 || pot.capacity != 0 || pot.brewing() || pot.items.isEmpty()) {
throw new IllegalArgumentException("Invalid cauldron contents"); throw new IllegalArgumentException("Invalid uncooked cauldron contents");
}
return;
}
if (pot.soup.getCount() != 1 || !Ingredients.isCombined(pot.soup)) {
throw new IllegalArgumentException("Invalid cauldron soup");
}
if (pot.servings < 1 || pot.capacity < pot.servings || pot.capacity > 16) {
throw new IllegalArgumentException("Invalid cauldron servings");
}
if (pot.brewing()) {
if (pot.items.isEmpty())
throw new IllegalArgumentException("Brewing requires ingredients");
} else if (!pot.items.isEmpty()) {
throw new IllegalArgumentException("Finished soup cannot retain ingredients");
}
} }
private boolean change(Position pos, Pot next) { private boolean change(Position pos, Pot next) {
@@ -433,7 +444,7 @@ public final class SoupPots implements AutoCloseable {
water.show( water.show(
level, level,
pos.pos, pos.pos,
new online.astradev.plus.api.ColoredWaterApi.Surface( new ColoredWaterApi.Surface(
WATER_OWNER, WATER_OWNER,
Ingredients.color(pot.soup), Ingredients.color(pot.soup),
(float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity))); (float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity)));
@@ -1,61 +0,0 @@
package online.astradev.cauldron;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.nio.file.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.List;
/** Export before AstraPlus's startup pack build; upgrade only known, unmodified defaults. */
final class SoupResources {
// Bundled flat-colour model in 0.2.0–0.2.3, with normalized newlines and outer whitespace.
private static final String FLAT_MODEL_SHA256 =
"51b5c2b0561ec815e5ddaff5654ce04fffa0995fc3e5972323f385d58842cd2c";
private SoupResources() {}
static void install(Path root) throws IOException {
for (String name : List.of("items/combined_soup.json", "models/item/soup_liquid.json")) {
String relative = "assets/astradev_soups/" + name;
Path target = root.resolve("astraplus/resources").resolve(relative);
Files.createDirectories(target.getParent());
boolean exists = Files.exists(target, LinkOption.NOFOLLOW_LINKS);
if (exists && !(name.equals("models/item/soup_liquid.json") && isFlatDefault(target)))
continue;
try (var input =
SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
if (input == null) throw new IOException("Missing resource " + relative);
if (!exists) Files.copy(input, target);
else {
Path temp = Files.createTempFile(target.getParent(), "soup-model-", ".tmp");
try {
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
Files.move(
temp,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
}
}
}
}
private static boolean isFlatDefault(Path path) throws IOException {
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) > 8192)
return false;
String model = Files.readString(path, UTF_8).replace("\r\n", "\n").trim();
try {
return HexFormat.of()
.formatHex(MessageDigest.getInstance("SHA-256").digest(model.getBytes(UTF_8)))
.equals(FLAT_MODEL_SHA256);
} catch (NoSuchAlgorithmException impossible) {
throw new AssertionError(impossible);
}
}
}
@@ -6,6 +6,8 @@ import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.block.entity.CampfireBlockEntity; import net.minecraft.world.level.block.entity.CampfireBlockEntity;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import online.astradev.cauldron.CauldronHeat;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;
@@ -21,6 +23,6 @@ public abstract class CampfireHeatMixin {
CampfireBlockEntity entity, CampfireBlockEntity entity,
RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes, RecipeManager.CachedCheck<SingleRecipeInput, CampfireCookingRecipe> recipes,
CallbackInfo ci) { CallbackInfo ci) {
online.astradev.cauldron.CauldronHeat.tick(level, pos); CauldronHeat.tick(level, pos);
} }
} }
@@ -5,6 +5,8 @@ import net.minecraft.core.component.*;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import online.astradev.cauldron.AstraCauldron;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*; import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@@ -22,7 +24,7 @@ abstract class SoupStackMixin {
if (key == null || !key.identifier().getNamespace().equals("minecraft")) return; if (key == null || !key.identifier().getNamespace().equals("minecraft")) return;
switch (key.identifier().getPath()) { switch (key.identifier().getPath()) {
case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> { case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> {
var config = online.astradev.cauldron.AstraCauldron.config(); var config = AstraCauldron.config();
if (config.normalizeVanillaSoups) if (config.normalizeVanillaSoups)
components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize); components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
} }
@@ -21,6 +21,6 @@ side="SERVER"
[[dependencies.astracauldron]] [[dependencies.astracauldron]]
modId="astraplus" modId="astraplus"
type="required" type="required"
versionRange="[0.9.2,0.10)" versionRange="[0.9.3,0.10)"
ordering="AFTER" ordering="AFTER"
side="SERVER" side="SERVER"
@@ -1,64 +0,0 @@
package online.astradev.cauldron;
import static org.junit.jupiter.api.Assertions.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
class SoupResourcesTest {
@TempDir Path root;
private static final String MODEL = "assets/astradev_soups/models/item/soup_liquid.json";
@Test
void exportsBundledResourcesAndCanRunAgain() throws Exception {
SoupResources.install(root);
assertArrayEquals(bundled(), Files.readAllBytes(target()));
var modified = Files.getLastModifiedTime(target());
SoupResources.install(root);
assertEquals(modified, Files.getLastModifiedTime(target()));
assertTrue(
Files.exists(
root.resolve(
"astraplus/resources/assets/astradev_soups/items/combined_soup.json")));
}
@Test
void upgradesFlatDefaultWithEitherLineEnding() throws Exception {
try (var input = getClass().getResourceAsStream("/legacy/soup_liquid.json")) {
String legacy = new String(input.readAllBytes(), UTF_8).replace("\r\n", "\n");
Files.createDirectories(target().getParent());
for (String ending : new String[] {"\n", "\r\n"}) {
Files.writeString(target(), legacy.replace("\n", ending));
SoupResources.install(root);
assertArrayEquals(bundled(), Files.readAllBytes(target()));
}
}
}
@Test
void preservesAdministratorCustomizationOfOldModel() throws Exception {
try (var input = getClass().getResourceAsStream("/legacy/soup_liquid.json")) {
String custom =
new String(input.readAllBytes(), UTF_8)
.replace("minecraft:item/bone_meal", "custom:item/soup");
Files.createDirectories(target().getParent());
Files.writeString(target(), custom);
SoupResources.install(root);
assertEquals(custom, Files.readString(target()));
}
}
private Path target() {
return root.resolve("astraplus/resources").resolve(MODEL);
}
private byte[] bundled() throws Exception {
try (var input = getClass().getResourceAsStream("/astra-resources/" + MODEL)) {
return input.readAllBytes();
}
}
}