Configure cauldron operations brewing consumption and feedback

This commit is contained in:
2026-09-12 14:19:03 +03:00
parent cae34a70d5
commit 1ac7dedcb0
10 changed files with 136 additions and 28 deletions
+40
View File
@@ -0,0 +1,40 @@
# Настройки котлов
Файл: `config/astracauldron.json`. Применение через `/astracauldron reload` или перезапуск. Отсутствующие поля сохраняют значения по умолчанию. Существующий файл не перезаписывается при обновлении JAR.
| Поля | Значения по умолчанию | Назначение |
|---|---|---|
| soupsEnabled | true | Разрешить начало новых супов; готовые и сохранённые котлы остаются доступны |
| dyeWater, dyeArmor, dyeBlocks | true | Отдельно окрашивание воды, брони, шерсти/ковров |
| storePotions, tipArrows | true | Добавление зелий и обработка стрел; забирать старые жидкости можно при отключении |
| ingredientCount | 4 | 1–4 ингредиента; при уменьшении можно вернуть лишние пустой рукой |
| servingsPerBrew | 4 | 1–16 порций |
| requireFullWater, requireHeat | true | Полная вода и обязательный нагрев |
| brewSeconds | 4 | Варка, 0.5–60 секунд |
| inheritEffects, alwaysEdible, returnBowl | true | Эффекты ингредиентов, еда при полном голоде, возврат миски |
| consumeSeconds | 1.6 | Употребление, 0.05–60 секунд |
| soupStackSize | 16 | Размер стопки супов, 1–64 |
| normalizeVanillaSoups | true | Применять размер стопки также к ванильным супам |
| particles, ingredientDisplays, sounds, messages | true | Частицы, предметы в котле, звуки и сообщения |
| soundVolume | 0.8 | Громкость, 0–4 |
| messageOverrides | {} | Замена полного исходного текста сообщения на свой текст |
| soupName | Комбинированный суп | Имя приготовленного супа |
| defaultColor | #B77A36 | Цвет ингредиентов без собственной палитры |
| maxNutrition, maxSaturation | 1000 | Верхние пределы питания и насыщения |
| blockedIngredients, incompatible, customIngredients | [], [], {} | Запрещённые ингредиенты, пары несовместимости и собственные определения |
Пример:
```json
{
"ingredientCount": 2,
"servingsPerBrew": 6,
"requireHeat": false,
"tipArrows": false,
"inheritEffects": false,
"particles": false,
"soundVolume": 0.4
}
```
Состав и свойства уже приготовленного супа сохраняются. Изменение рецептурных параметров действует на следующую варку. Формат котла по-прежнему использует три уровня жидкости и до четырёх видимых ингредиентов. Сообщения с числами заменяются по полному тексту, включая число; `messages: false` отключает их все. Ошибка сохранения всегда отменяет действие независимо от показа сообщения.
@@ -27,6 +27,7 @@ import org.slf4j.*;
public final class AstraCauldron { public final class AstraCauldron {
static final Logger LOG = LoggerFactory.getLogger("AstraCauldron"); static final Logger LOG = LoggerFactory.getLogger("AstraCauldron");
private static SoupPots pots; private static SoupPots pots;
private static final SoupConfig DEFAULT_CONFIG = new SoupConfig();
private static LiquidPots liquids; private static LiquidPots liquids;
public AstraCauldron() { public AstraCauldron() {
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources); NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
@@ -56,6 +57,7 @@ public final class AstraCauldron {
private void stop(ServerStoppingEvent event) { if (pots != null) pots.close(); if (liquids != null) liquids.close(); pots = null; liquids = null; } private void stop(ServerStoppingEvent event) { if (pots != null) pots.close(); if (liquids != null) liquids.close(); pots = null; liquids = null; }
private void tick(ServerTickEvent.Post event) { if (pots != null) pots.tick(); if (liquids != null) liquids.tick(); } private void tick(ServerTickEvent.Post event) { if (pots != null) pots.tick(); if (liquids != null) liquids.tick(); }
public static SoupPots pots() { return pots; } public static SoupPots pots() { return pots; }
public static SoupConfig config() { return pots == null ? DEFAULT_CONFIG : pots.config(); }
public static LiquidPots liquids() { return liquids; } public static LiquidPots liquids() { return liquids; }
public static boolean occupied(Level level, BlockPos pos) { public static boolean occupied(Level level, BlockPos pos) {
return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos)) return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos))
@@ -18,6 +18,7 @@ public final class CauldronHeat {
return state.getBlock() instanceof CampfireBlock && state.getValue(CampfireBlock.LIT); return state.getBlock() instanceof CampfireBlock && state.getValue(CampfireBlock.LIT);
} }
public static void tick(ServerLevel level, BlockPos campfire) { public static void tick(ServerLevel level, BlockPos campfire) {
if (!AstraCauldron.config().particles) return;
var pos = campfire.above(); var pos = campfire.above();
if ((level.getGameTime() + pos.asLong()) % 10 != 0 || !heated(level, pos)) return; if ((level.getGameTime() + pos.asLong()) % 10 != 0 || !heated(level, pos)) return;
var state = level.getBlockState(pos); var state = level.getBlockState(pos);
@@ -12,7 +12,10 @@ public final class CombinationRules {
public static String rejection( public static String rejection(
List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) { List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента."; return rejection(ingredients, blocked, pairs, 4);
}
public static String rejection(List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs, int count) {
if (ingredients.size() != count) return "Нужно ровно " + count + " ингредиента.";
for (Set<String> tags : ingredients) { for (Set<String> tags : ingredients) {
for (String selector : blocked) { for (String selector : blocked) {
if (matches(tags, selector)) return "Запрещён ингредиент: " + selector; if (matches(tags, selector)) return "Запрещён ингредиент: " + selector;
@@ -84,7 +84,7 @@ public final class Ingredients {
public String rejection(List<ItemStack> items) { public String rejection(List<ItemStack> items) {
var data = items.stream().map(this::read).toList(); var data = items.stream().map(this::read).toList();
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент."; if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
String error = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), config.blockedIngredients, config.incompatible); String error = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), config.blockedIngredients, config.incompatible, config.ingredientCount);
if (error != null) return error; if (error != null) return error;
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum(); long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum(); double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
@@ -100,7 +100,7 @@ public final class Ingredients {
.sorted(Comparator.comparing(s -> SoupFiles.encode(s, registries).toString())).map(this::read).toList(); .sorted(Comparator.comparing(s -> SoupFiles.encode(s, registries).toString())).map(this::read).toList();
int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum(); int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum();
float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum(); float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum();
var effects = data.stream().flatMap(i -> i.effects.stream()).toList(); List<ConsumeEffect> effects = config.inheritEffects ? data.stream().flatMap(i -> i.effects.stream()).toList() : List.of();
int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray()); int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray());
var soup = new ItemStack(Items.MUSHROOM_STEW); var soup = new ItemStack(Items.MUSHROOM_STEW);
CustomData.update(DataComponents.CUSTOM_DATA, soup, tag -> { CustomData.update(DataComponents.CUSTOM_DATA, soup, tag -> {
@@ -108,10 +108,11 @@ public final class Ingredients {
tag.putInt("astracauldron:soup_color", rgb); tag.putInt("astracauldron:soup_color", rgb);
}); });
soup.set(DataComponents.CUSTOM_NAME, Component.literal(config.soupName).withStyle(s -> s.withColor(rgb).withItalic(false))); soup.set(DataComponents.CUSTOM_NAME, Component.literal(config.soupName).withStyle(s -> s.withColor(rgb).withItalic(false)));
soup.set(DataComponents.FOOD, new FoodProperties(nutrition, saturation, true)); soup.set(DataComponents.FOOD, new FoodProperties(nutrition, saturation, config.alwaysEdible));
var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE)); var base = Objects.requireNonNull(soup.get(DataComponents.CONSUMABLE));
soup.set(DataComponents.CONSUMABLE, new Consumable(base.consumeSeconds(), base.animation(), base.sound(), base.hasConsumeParticles(), effects)); soup.set(DataComponents.CONSUMABLE, new Consumable(config.consumeSeconds, base.animation(), base.sound(), config.particles && base.hasConsumeParticles(), effects));
soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL)))); if (config.returnBowl) soup.set(DataComponents.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
else soup.remove(DataComponents.USE_REMAINDER);
normalize(soup); normalize(soup);
return soup; return soup;
} }
@@ -131,7 +132,7 @@ public final class Ingredients {
} }
public static void normalize(ItemStack stack) { public static void normalize(ItemStack stack) {
if (!(stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW) || stack.is(Items.BEETROOT_SOUP) || stack.is(Items.SUSPICIOUS_STEW))) return; if (!(stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW) || stack.is(Items.BEETROOT_SOUP) || stack.is(Items.SUSPICIOUS_STEW))) return;
stack.set(DataComponents.MAX_STACK_SIZE, 16); if (isCombined(stack) || AstraCauldron.config().normalizeVanillaSoups) stack.set(DataComponents.MAX_STACK_SIZE, AstraCauldron.config().soupStackSize);
if (!isCombined(stack)) return; if (!isCombined(stack)) return;
stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup")); stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup"));
var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY); var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY);
@@ -91,13 +91,13 @@ public final class LiquidPots implements AutoCloseable {
return true; return true;
} }
var dye = api.mixDye(OptionalInt.empty(), held); var dye = api.mixDye(OptionalInt.empty(), held);
if (state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) { if (AstraCauldron.config().dyeWater && state.is(Blocks.WATER_CAULDRON) && dye.isPresent()) {
var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null); var next = new Liquid(state.getValue(LayeredCauldronBlock.LEVEL), dye.getAsInt(), null);
if (!change(pos, next)) { error(player); return true; } if (!change(pos, next)) { error(player); return true; }
held.consume(1, player); setVisual(level, pos, next); held.consume(1, player); setVisual(level, pos, next);
say(player, "Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно смешивать."); return true; say(player, "Вода окрашена. Окуните кожаную броню, шерсть или ковры; красители можно смешивать."); return true;
} }
if (state.is(Blocks.CAULDRON) && potion.isPresent()) { if (AstraCauldron.config().storePotions && state.is(Blocks.CAULDRON) && potion.isPresent()) {
var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get()); var next = new Liquid(1, potion.get().contents().getColor() & 0xFFFFFF, potion.get());
if (!change(pos, next)) { error(player); return true; } if (!change(pos, next)) { error(player); return true; }
consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); setVisual(level, pos, next); consumeAndGive(player, 1, new ItemStack(Items.GLASS_BOTTLE)); setVisual(level, pos, next);
@@ -107,13 +107,13 @@ public final class LiquidPots implements AutoCloseable {
} }
if (liquid.potion == null) { if (liquid.potion == null) {
var dye = api.mixDye(OptionalInt.of(liquid.rgb), held); var dye = api.mixDye(OptionalInt.of(liquid.rgb), held);
if (dye.isPresent()) { if (AstraCauldron.config().dyeWater && dye.isPresent()) {
var next = new Liquid(liquid.levels, dye.getAsInt(), null); var next = new Liquid(liquid.levels, dye.getAsInt(), null);
if (!change(pos, next)) { error(player); return true; } if (!change(pos, next)) { error(player); return true; }
held.consume(1, player); setVisual(level,pos,next); return true; held.consume(1, player); setVisual(level,pos,next); return true;
} }
var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels); var blocks = api.dyeBlocks(held, liquid.rgb, liquid.levels);
if (blocks.isPresent()) { if (AstraCauldron.config().dyeBlocks && blocks.isPresent()) {
var batch = blocks.get(); var result = batch.result(); var batch = blocks.get(); var result = batch.result();
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; } if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
int count = result.getCount(); int count = result.getCount();
@@ -121,7 +121,7 @@ public final class LiquidPots implements AutoCloseable {
say(player,"Окрашено предметов: " + count + "."); return true; say(player,"Окрашено предметов: " + count + "."); return true;
} }
var armor = api.dyeArmor(held, liquid.rgb); var armor = api.dyeArmor(held, liquid.rgb);
if (armor.isPresent()) { if (AstraCauldron.config().dyeArmor && armor.isPresent()) {
if (!decrease(level,pos,liquid,1)) { error(player); return true; } if (!decrease(level,pos,liquid,1)) { error(player); return true; }
// Transform the equipped item, including Creative, preserving enchantments/damage/name. // 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()); if (held.getCount() == 1) player.setItemInHand(hand, armor.get()); else consumeAndGive(player,1,armor.get());
@@ -143,6 +143,7 @@ public final class LiquidPots implements AutoCloseable {
say(player,"Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); return true; say(player,"Цветная вода: " + liquid.levels + "/3. Для варки супа нужна чистая вода."); return true;
} }
if (potion.isPresent()) { if (potion.isPresent()) {
if (!AstraCauldron.config().storePotions) return true;
if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; } if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; }
if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; } if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; }
var next = liquid.withLevels(liquid.levels + 1); var next = liquid.withLevels(liquid.levels + 1);
@@ -155,7 +156,7 @@ public final class LiquidPots implements AutoCloseable {
consumeAndGive(player,1,bottle); sound(level,blockPos); return true; consumeAndGive(player,1,bottle); sound(level,blockPos); return true;
} }
var arrows = api.tipArrows(held,liquid.potion,liquid.levels); var arrows = api.tipArrows(held,liquid.potion,liquid.levels);
if (arrows.isPresent()) { if (AstraCauldron.config().tipArrows && arrows.isPresent()) {
var batch = arrows.get(); var result = batch.result(); var batch = arrows.get(); var result = batch.result();
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; } if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
int count = result.getCount(); int count = result.getCount();
@@ -197,7 +198,7 @@ public final class LiquidPots implements AutoCloseable {
player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false); player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false);
player.containerMenu.broadcastChanges(); player.containerMenu.broadcastChanges();
} }
private static void sound(ServerLevel level,BlockPos pos) { level.playSound(null,pos,SoundEvents.BOTTLE_FILL,SoundSource.BLOCKS,.8f,1); } private static void sound(ServerLevel level,BlockPos pos) { var config = AstraCauldron.config(); if (config.sounds) level.playSound(null,pos,SoundEvents.BOTTLE_FILL,SoundSource.BLOCKS,config.soundVolume,1); }
private static void say(ServerPlayer player,String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD),true); } private static void say(ServerPlayer player,String text) { var config = AstraCauldron.config(); if (config.messages) player.sendSystemMessage(Component.literal(config.messageOverrides.getOrDefault(text,text)).withStyle(ChatFormatting.GOLD),true); }
private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); } private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); }
} }
@@ -6,6 +6,26 @@ import java.nio.file.*;
import java.util.*; import java.util.*;
public final class SoupConfig { public final class SoupConfig {
public boolean soupsEnabled = true;
public boolean dyeWater = true;
public boolean dyeArmor = true;
public boolean dyeBlocks = true;
public boolean storePotions = true;
public boolean tipArrows = true;
public boolean requireHeat = true;
public boolean particles = true;
public boolean ingredientDisplays = true;
public boolean sounds = true;
public float soundVolume = .8f;
public boolean messages = true;
public int ingredientCount = 4;
public boolean inheritEffects = true;
public boolean alwaysEdible = true;
public float consumeSeconds = 1.6f;
public boolean returnBowl = true;
public int soupStackSize = 16;
public boolean normalizeVanillaSoups = true;
public Map<String, String> messageOverrides = new LinkedHashMap<>();
public int servingsPerBrew = 4; public int servingsPerBrew = 4;
public boolean requireFullWater = true; public boolean requireFullWater = true;
public double brewSeconds = 4; public double brewSeconds = 4;
@@ -38,6 +58,10 @@ public final class SoupConfig {
return config; return config;
} }
public void validate() { public void validate() {
if (ingredientCount < 1 || ingredientCount > 4 || soupStackSize < 1 || soupStackSize > 64 || !Float.isFinite(consumeSeconds) || consumeSeconds < .05 || consumeSeconds > 60)
throw new IllegalArgumentException("Invalid ingredients/consumption settings");
if (!Float.isFinite(soundVolume) || soundVolume < 0 || soundVolume > 4 || messageOverrides == null
|| messageOverrides.containsValue(null)) throw new IllegalArgumentException("Invalid sound/messages");
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds) if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0 || brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank()) || !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
@@ -50,6 +50,7 @@ public final class SoupPots implements AutoCloseable {
load(); load();
} }
public Ingredients ingredients() { return ingredients; } public Ingredients ingredients() { return ingredients; }
public SoupConfig config() { return config; }
public boolean contains(ServerLevel level, BlockPos pos) { return pots.containsKey(Position.at(level, pos)); } public 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 Pot get(ServerLevel level, BlockPos pos) { return pots.get(Position.at(level, pos)); }
public void reload() throws IOException { public void reload() throws IOException {
@@ -95,7 +96,7 @@ public final class SoupPots implements AutoCloseable {
|| p.brewTicks < 0 || p.brewTicks > 1200 || p.brewTicks < 0 || p.brewTicks > 1200
|| (p.soup.isEmpty() ? p.servings != 0 || p.capacity != 0 || p.brewing() || p.items.isEmpty() || (p.soup.isEmpty() ? p.servings != 0 || p.capacity != 0 || p.brewing() || p.items.isEmpty()
: p.soup.getCount() != 1 || !Ingredients.isCombined(p.soup) || p.servings < 1 || p.capacity < p.servings || p.capacity > 16 : p.soup.getCount() != 1 || !Ingredients.isCombined(p.soup) || p.servings < 1 || p.capacity < p.servings || p.capacity > 16
|| (p.brewing() ? p.items.size() != 4 : !p.items.isEmpty()))) || (p.brewing() ? p.items.isEmpty() : !p.items.isEmpty())))
throw new IllegalArgumentException("Invalid cauldron contents"); throw new IllegalArgumentException("Invalid cauldron contents");
} }
private boolean change(Position pos, Pot next) { private boolean change(Position pos, Pot next) {
@@ -126,6 +127,7 @@ public final class SoupPots implements AutoCloseable {
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) { public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
var level = player.level(); var pos = Position.at(level, blockPos); var pot = pots.get(pos); var level = player.level(); var pos = Position.at(level, blockPos); var pot = pots.get(pos);
if (player.isSpectator()) return false; if (player.isSpectator()) return false;
if (!config.soupsEnabled && pot == null) return false;
if (hand != InteractionHand.MAIN_HAND) return pot != null; if (hand != InteractionHand.MAIN_HAND) return pot != null;
var state = level.getBlockState(blockPos); var state = level.getBlockState(blockPos);
if (!valid(state, pot)) return false; if (!valid(state, pot)) return false;
@@ -137,7 +139,7 @@ public final class SoupPots implements AutoCloseable {
} }
pot = Pot.raw(List.of()); pot = Pot.raw(List.of());
} }
if (pot.brewing()) { say(player, CauldronHeat.heated(level, blockPos) ? "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с." : "Варка приостановлена. Зажгите костёр под котлом."); return true; } if (pot.brewing()) { say(player, (!config.requireHeat || CauldronHeat.heated(level, blockPos)) ? "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с." : "Варка приостановлена. Зажгите костёр под котлом."); return true; }
if (pot.ready()) { if (pot.ready()) {
if (!held.is(Items.BOWL)) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return true; } if (!held.is(Items.BOWL)) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return true; }
int left = pot.servings - 1; var result = pot.soup.copy(); int left = pot.servings - 1; var result = pot.soup.copy();
@@ -148,8 +150,8 @@ public final class SoupPots implements AutoCloseable {
sound(level, blockPos, SoundEvents.BOTTLE_FILL); sound(level, blockPos, SoundEvents.BOTTLE_FILL);
say(player, left == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + left + "."); return true; say(player, left == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + left + "."); return true;
} }
if (pot.items.size() == 4 && (player.isShiftKeyDown() || !held.isEmpty())) { if (pot.items.size() >= config.ingredientCount && (player.isShiftKeyDown() || !held.isEmpty())) {
if (!CauldronHeat.heated(level, blockPos)) { say(player, "Для варки нужен горящий костёр прямо под котлом."); return true; } if (config.requireHeat && !CauldronHeat.heated(level, blockPos)) { say(player, "Для варки нужен горящий костёр прямо под котлом."); return true; }
String rejection = ingredients.rejection(pot.items); String rejection = ingredients.rejection(pot.items);
if (rejection != null) { say(player, rejection + " ПКМ пустой рукой возвращает последний ингредиент."); return true; } 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); var next = new Pot(pot.items, ingredients.brew(pot.items), (int)Math.round(config.brewSeconds * 20), config.servingsPerBrew, config.servingsPerBrew);
@@ -160,13 +162,13 @@ public final class SoupPots implements AutoCloseable {
if (pot.items.isEmpty()) return true; if (pot.items.isEmpty()) return true;
var remaining = new ArrayList<>(pot.items); var last = remaining.removeLast(); var remaining = new ArrayList<>(pot.items); var last = remaining.removeLast();
if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { saveError(player); return true; } if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { saveError(player); return true; }
give(player, last.copy()); say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4."); return true; give(player, last.copy()); say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/" + config.ingredientCount + "."); return true;
} }
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); 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)); var items = new ArrayList<>(pot.items); items.add(held.copyWithCount(1));
if (!change(pos, Pot.raw(items))) { saveError(player); return true; } if (!change(pos, Pot.raw(items))) { saveError(player); return true; }
held.consume(1, player); show(level, pos, pots.get(pos)); sound(level, blockPos, SoundEvents.GENERIC_SPLASH); held.consume(1, player); show(level, pos, pots.get(pos)); sound(level, blockPos, SoundEvents.GENERIC_SPLASH);
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : "")); say(player, "Ингредиенты: " + items.size() + "/" + config.ingredientCount + "." + (items.size() == config.ingredientCount ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
return true; return true;
} }
public boolean breakPot(ServerLevel level, BlockPos blockPos) { public boolean breakPot(ServerLevel level, BlockPos blockPos) {
@@ -186,7 +188,7 @@ public final class SoupPots implements AutoCloseable {
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension))); var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
if (level == null || !level.hasChunkAt(pos.pos)) { removeVisuals(pos); continue; } if (level == null || !level.hasChunkAt(pos.pos)) { removeVisuals(pos); continue; }
if (!valid(level.getBlockState(pos.pos), pot)) { breakPot(level, pos.pos); continue; } if (!valid(level.getBlockState(pos.pos), pot)) { breakPot(level, pos.pos); continue; }
boolean heated = CauldronHeat.heated(level, pos.pos); boolean heated = !config.requireHeat || CauldronHeat.heated(level, pos.pos);
if (pot.brewing() && heated) { if (pot.brewing() && heated) {
int time = elapsed.merge(pos, 1, Integer::sum); int time = elapsed.merge(pos, 1, Integer::sum);
if (time >= pot.brewTicks && (time - pot.brewTicks) % 20 == 0 if (time >= pot.brewTicks && (time - pot.brewTicks) % 20 == 0
@@ -194,11 +196,11 @@ public final class SoupPots implements AutoCloseable {
pot = pots.get(pos); pot = pots.get(pos);
level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3); level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3);
sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP); sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP);
level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01); if (config.particles) level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
} }
} }
show(level, pos, pot); show(level, pos, pot);
if (ticks % 2 == 0 && !pot.ready()) { if (config.ingredientDisplays && ticks % 2 == 0 && !pot.ready()) {
var displays = visuals.get(pos); var displays = visuals.get(pos);
int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL); int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL);
for (int i = 0; i < displays.size(); i++) displays.get(i).ingredient(i, water, ticks + 2, elapsed.getOrDefault(pos, 0) + (heated ? 2 : 0), pot.brewTicks); for (int i = 0; i < displays.size(); i++) displays.get(i).ingredient(i, water, ticks + 2, elapsed.getOrDefault(pos, 0) + (heated ? 2 : 0), pot.brewTicks);
@@ -217,6 +219,7 @@ public final class SoupPots implements AutoCloseable {
Ingredients.color(pot.soup), (float)CauldronAnimation.liquidHeight(pot.servings, pot.capacity))); Ingredients.color(pot.soup), (float)CauldronAnimation.liquidHeight(pot.servings, pot.capacity)));
return; return;
} }
if (!config.ingredientDisplays) { removeVisuals(pos); return; }
var existing = visuals.get(pos); var existing = visuals.get(pos);
if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; } if (existing != null && existing.stream().anyMatch(d -> d.isRemoved())) { removeVisuals(pos); existing = null; }
if (existing != null) return; if (existing != null) return;
@@ -241,8 +244,8 @@ public final class SoupPots implements AutoCloseable {
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos); for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
water.removeAll(WATER_OWNER); water.removeAll(WATER_OWNER);
} }
private static void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { level.playSound(null, pos, sound, SoundSource.BLOCKS, .8f, 1f); } private void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { if (config.sounds) level.playSound(null, pos, sound, SoundSource.BLOCKS, config.soundVolume, 1f); }
private static void give(ServerPlayer player, ItemStack item) { Ingredients.normalize(item); player.getInventory().add(item); if (!item.isEmpty()) player.drop(item, false); player.containerMenu.broadcastChanges(); } private static void give(ServerPlayer player, ItemStack item) { Ingredients.normalize(item); player.getInventory().add(item); if (!item.isEmpty()) player.drop(item, false); player.containerMenu.broadcastChanges(); }
private static void say(ServerPlayer player, String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD), true); } private static void say(ServerPlayer player, String text) { var config = AstraCauldron.config(); if (config.messages) player.sendSystemMessage(Component.literal(config.messageOverrides.getOrDefault(text, text)).withStyle(ChatFormatting.GOLD), true); }
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); } private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
} }
@@ -16,7 +16,10 @@ abstract class SoupStackMixin {
var key = item.unwrapKey().orElse(null); var key = item.unwrapKey().orElse(null);
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" -> components.set(DataComponents.MAX_STACK_SIZE, 16); case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> {
var config = online.astradev.cauldron.AstraCauldron.config();
if (config.normalizeVanillaSoups) components.set(DataComponents.MAX_STACK_SIZE, config.soupStackSize);
}
default -> { } default -> { }
} }
} }
@@ -0,0 +1,30 @@
package online.astradev.cauldron;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.*;
import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
class ConfigurationPolicyTest {
@TempDir Path root;
@Test void oldConfigKeepsDefaultsAndNewFieldsAreValidated() throws Exception {
Path file = root.resolve("cauldron.json");
Files.writeString(file, "{\"servingsPerBrew\":2,\"ingredientCount\":2,\"requireHeat\":false,\"soupStackSize\":8}");
var config = SoupConfig.load(file);
assertEquals(2, config.servingsPerBrew);
assertEquals(2, config.ingredientCount);
assertEquals(8, config.soupStackSize);
assertFalse(config.requireHeat);
assertTrue(config.tipArrows);
config.ingredientCount = 5;
assertThrows(IllegalArgumentException.class, config::validate);
}
@Test void ingredientCountStillChecksForbiddenCombinations() {
var ingredients = List.of(Set.of("material:carrot"), Set.of("material:potato"));
assertNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 2));
assertNotNull(CombinationRules.rejection(ingredients, List.of("material:carrot"), List.of(), 2));
assertNotNull(CombinationRules.rejection(ingredients, List.of(), List.of(List.of("material:carrot", "material:potato")), 2));
assertNotNull(CombinationRules.rejection(ingredients, List.of(), List.of(), 3));
}
}