Migrate AstraSoups to NeoForge as AstraCauldron

This commit is contained in:
2026-09-08 19:44:45 +03:00
parent 8391dfe739
commit a82c2aa0f9
52 changed files with 2095 additions and 2010 deletions
@@ -0,0 +1,114 @@
package online.astradev.cauldron;
import com.mojang.brigadier.arguments.*;
import net.minecraft.commands.Commands;
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.minecraft.core.BlockPos;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.EventPriority;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.loading.FMLPaths;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.EntityJoinLevelEvent;
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
import net.neoforged.neoforge.event.level.*;
import net.neoforged.neoforge.event.server.*;
import net.neoforged.neoforge.event.tick.ServerTickEvent;
import org.slf4j.*;
@Mod(value = "astracauldron", dist = Dist.DEDICATED_SERVER)
public final class AstraCauldron {
static final Logger LOG = LoggerFactory.getLogger("AstraCauldron");
private static SoupPots pots;
private static LiquidPots liquids;
public AstraCauldron() {
NeoForge.EVENT_BUS.addListener(EventPriority.HIGHEST, this::resources);
NeoForge.EVENT_BUS.addListener(this::start);
NeoForge.EVENT_BUS.addListener(this::stop);
NeoForge.EVENT_BUS.addListener(this::tick);
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::interact);
NeoForge.EVENT_BUS.addListener(EventPriority.LOWEST, this::breakBlock);
NeoForge.EVENT_BUS.addListener(this::explosion);
NeoForge.EVENT_BUS.addListener(this::piston);
NeoForge.EVENT_BUS.addListener(this::unload);
NeoForge.EVENT_BUS.addListener(this::join);
NeoForge.EVENT_BUS.addListener(this::commands);
}
private void 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) {
try {
online.astradev.plus.api.AstraPlusApi.current().orElseThrow(() -> new IllegalStateException("AstraPlus API unavailable"));
pots = new SoupPots(event.getServer(), FMLPaths.CONFIGDIR.get().resolve("astracauldron.json"));
liquids = new LiquidPots(event.getServer());
LOG.info("AstraCauldron ready: NeoForge 26.2, AstraPlus API");
} catch (Exception e) { throw new IllegalStateException("Cannot initialize AstraCauldron; existing data preserved", e); }
}
private void stop(ServerStoppingEvent event) { if (pots != null) pots.close(); if (liquids != null) liquids.close(); pots = null; liquids = null; }
private void tick(ServerTickEvent.Post event) { if (pots != null) pots.tick(); if (liquids != null) liquids.tick(); }
public static SoupPots pots() { return pots; }
public static LiquidPots liquids() { return liquids; }
public static boolean occupied(Level level, BlockPos pos) {
return level instanceof ServerLevel serverLevel && ((pots != null && pots.contains(serverLevel, pos))
|| (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 && ((!pots.contains(player.level(),event.getPos()) && liquids != null
&& liquids.interact(player,event.getPos(),event.getHand())) || pots.interact(player, event.getPos(), event.getHand()))) {
event.setCanceled(true); event.setCancellationResult(InteractionResult.SUCCESS);
}
}
private void breakBlock(net.neoforged.neoforge.event.level.block.BreakBlockEvent event) {
if (!event.isCanceled() && pots != null && event.getLevel() instanceof ServerLevel level
&& (!pots.breakPot(level, event.getPos()) || (liquids != null && !liquids.breakPot(level,event.getPos())))) { 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() && (resolver.getToPush().stream().anyMatch(p -> occupied(level, p))
|| resolver.getToDestroy().stream().anyMatch(p -> occupied(level, p)))) event.setCanceled(true);
}
private void unload(ChunkEvent.Unload event) {
if (pots != null && event.getLevel() instanceof ServerLevel level)
pots.unload(level, event.getChunk().getPos().x(), event.getChunk().getPos().z());
}
private void join(EntityJoinLevelEvent event) {
if (event.loadedFromDisk() && event.getEntity().entityTags().contains(SoupDisplay.TAG)) event.setCanceled(true);
else if (event.getEntity() instanceof ItemEntity item) Ingredients.normalize(item.getItem());
}
private void commands(RegisterCommandsEvent event) {
var command = Commands.literal("cauldron").executes(c -> {
c.getSource().sendSuccess(() -> Component.literal("Краситель + вода: окрашивание брони. Зелье + пустой котёл: хранение и стрелы с эффектом. Еда/зелья + полный котёл воды: 4 ингредиента супа, Shift+ПКМ — варка, миска — порция."), false); return 1;
});
command.then(Commands.literal("reload").requires(Commands.hasPermission(Commands.LEVEL_ADMINS)).executes(c -> {
try { requirePots().reload(); c.getSource().sendSuccess(() -> Component.literal("AstraCauldron: настройки применены."), true); return 1; }
catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка: " + e.getMessage() + ". Прежние настройки сохранены.")); return 0; }
}));
command.then(Commands.literal("register").requires(Commands.hasPermission(Commands.LEVEL_ADMINS))
.then(Commands.argument("id", StringArgumentType.word()).then(Commands.argument("nutrition", IntegerArgumentType.integer(0))
.then(Commands.argument("saturation", FloatArgumentType.floatArg(0)).executes(c -> {
try {
requirePots().register(StringArgumentType.getString(c, "id"), c.getSource().getPlayerOrException(),
IntegerArgumentType.getInteger(c, "nutrition"), FloatArgumentType.getFloat(c, "saturation"));
c.getSource().sendSuccess(() -> Component.literal("Ингредиент зарегистрирован."), true); return 1;
} catch (Exception e) { c.getSource().sendFailure(Component.literal("Ошибка регистрации: " + e.getMessage())); return 0; }
})))));
var root = event.getDispatcher().register(command);
event.getDispatcher().register(Commands.literal("soups").redirect(root).executes(root.getCommand()));
}
private static SoupPots requirePots() { if (pots == null) throw new IllegalStateException("AstraCauldron ещё не запущен"); return pots; }
}
@@ -0,0 +1,29 @@
package online.astradev.cauldron;
/** ItemDisplay centers relative to the cauldron, without native dropped-item physics or bobbing. */
public final class CauldronAnimation {
private CauldronAnimation() {}
public record Offset(double x, double y, double z) {}
public static Offset frame(int slot, int waterLevel, int tick, int elapsed, int duration) {
double[] phases = {-3 * Math.PI / 4, -Math.PI / 4, 3 * Math.PI / 4, Math.PI / 4};
double angle = phases[slot] + (duration > 0 ? elapsed * .1 : 0);
double radius = .23;
double surface = .375 + .1875 * waterLevel;
double bob = Math.sin(tick * .04 + slot) * .004;
return new Offset(
.5 + Math.cos(angle) * radius, surface - .055 + bob, .5 + Math.sin(angle) * radius);
}
public static double liquidHeight(int servings, int capacity) {
return .25 + .6875 * Math.clamp((double) servings / capacity, 0, 1);
}
public static int waterLevel(int servings, int capacity) {
double height = liquidHeight(servings, capacity);
int level = 0;
for (int i = 1; i <= 3; i++) if (.375 + .1875 * i <= height + .00001) level = i;
return level;
}
}
@@ -0,0 +1,33 @@
package online.astradev.cauldron;
import java.util.List;
import java.util.Set;
public final class CombinationRules {
private CombinationRules() {}
public static boolean matches(Set<String> tags, String selector) {
return selector.equals("*") || tags.contains(selector.toLowerCase(java.util.Locale.ROOT));
}
public static String rejection(
List<Set<String>> ingredients, List<String> blocked, List<List<String>> pairs) {
if (ingredients.size() != 4) return "Нужно ровно 4 ингредиента.";
for (Set<String> tags : ingredients) {
for (String selector : blocked) {
if (matches(tags, selector)) return "Запрещён ингредиент: " + selector;
}
}
for (List<String> 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;
}
}
@@ -0,0 +1,41 @@
package online.astradev.cauldron;
final class IngredientColors {
private IngredientColors() {}
static int food(String material, int fallback) {
int rgb =
switch (material) {
case "spider_eye", "fermented_spider_eye" -> 0xB52B38;
case "golden_apple", "enchanted_golden_apple", "golden_carrot" -> 0xF2C94C;
case "apple", "sweet_berries" -> 0xC73735;
case "beetroot", "beetroot_soup" -> 0xA52B4B;
case "carrot", "pumpkin_pie", "glow_berries" -> 0xE99032;
case "dried_kelp" -> 0x47733B;
case "poisonous_potato" -> 0x91A340;
case "melon_slice" -> 0xD94E58;
case "chorus_fruit" -> 0x9C6C9D;
case "beef", "mutton", "porkchop", "rabbit" -> 0xC76B70;
case "chicken" -> 0xE2A6A0;
case "cooked_beef", "cooked_mutton" -> 0x815033;
case "cooked_porkchop", "cooked_rabbit", "cooked_chicken" -> 0xBA8551;
case "salmon", "cooked_salmon", "tropical_fish" -> 0xD98262;
case "cod" -> 0xB0A07B;
case "cooked_cod" -> 0xC4B486;
case "pufferfish" -> 0xD3B54D;
case "bread", "cookie", "baked_potato" -> 0xBA873F;
case "potato" -> 0xC7A76B;
case "rotten_flesh" -> 0x8F6540;
case "honey_bottle" -> 0xE9AC32;
case "cake" -> 0xE8CCBA;
case "mushroom_stew" -> 0xA37A53;
case "rabbit_stew" -> 0xAC8854;
case "suspicious_stew" -> 0x867743;
default -> fallback;
};
return rgb;
}
}
@@ -0,0 +1,164 @@
package online.astradev.cauldron;
import java.util.*;
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;
public final class Ingredients {
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, int color) {}
private record Custom(String id, ItemStack sample, SoupConfig.Custom definition, List<MobEffectInstance> effects) {}
private final SoupConfig config;
private final HolderLookup.Provider registries;
private final List<Custom> custom = new ArrayList<>();
public Ingredients(SoupConfig config, HolderLookup.Provider registries) {
config.validate();
this.config = config;
this.registries = registries;
for (var entry : config.customIngredients.entrySet()) {
var c = entry.getValue();
ItemStack sample = c.item == null ? ItemStack.EMPTY : SoupFiles.decode(c.item, registries);
if (c.item != null && (sample.isEmpty() || sample.getCount() != 1))
throw new IllegalArgumentException("Некорректный образец " + entry.getKey());
normalize(sample);
List<MobEffectInstance> effects = new ArrayList<>();
for (var e : c.effects) {
var type = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(e.type)).orElseThrow();
effects.add(new MobEffectInstance(type, e.duration, e.amplifier));
}
custom.add(new Custom(entry.getKey(), sample, c, List.copyOf(effects)));
}
}
public Ingredient read(ItemStack stack) {
if (stack.isEmpty()) return null;
var plus = AstraPlusApi.current().flatMap(api -> api.find(stack));
Custom match = custom.stream().filter(c -> c.definition.astraPlusId != null
? plus.map(p -> p.id().toString().equals(c.definition.astraPlusId)).orElse(false)
: ItemStack.isSameItemSameComponents(c.sample, normalizedCopy(stack))).findFirst().orElse(null);
var food = stack.get(DataComponents.FOOD);
boolean potion = stack.is(Items.POTION) || stack.is(Items.SPLASH_POTION) || stack.is(Items.LINGERING_POTION);
boolean cake = stack.is(Items.CAKE);
if (food == null && !potion && !cake && match == null) return null;
int nutrition = food == null ? (cake ? 14 : 0) : food.nutrition();
float saturation = food == null ? (cake ? 2.8f : 0) : food.saturation();
var effects = new ArrayList<ConsumeEffect>();
var consumable = stack.get(DataComponents.CONSUMABLE);
if (consumable != null) effects.addAll(consumable.onConsumeEffects());
String material = BuiltInRegistries.ITEM.getKey(stack.getItem()).getPath();
int color = IngredientColors.food(material, SoupConfig.rgb(config.defaultColor));
if (isCombined(stack)) color = color(stack);
var contents = stack.get(DataComponents.POTION_CONTENTS);
if (potion && contents != null) {
List<MobEffectInstance> potionEffects = new ArrayList<>();
contents.forEachEffect(potionEffects::add, stack.transmuteCopy(Items.POTION, 1).getOrDefault(DataComponents.POTION_DURATION_SCALE, 1f));
if (!potionEffects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(potionEffects));
color = contents.getColor() & 0xFFFFFF;
}
var stew = stack.get(DataComponents.SUSPICIOUS_STEW_EFFECTS);
if (stew != null && !stew.effects().isEmpty())
effects.add(new ApplyStatusEffectsConsumeEffect(stew.effects().stream().map(SuspiciousStewEffects.Entry::createEffectInstance).toList()));
Set<String> tags = new HashSet<>();
tags.add("material:" + material);
if (isCombined(stack)) tags.add("soup:combined");
plus.ifPresent(p -> tags.add("astraplus:" + p.id()));
if (match != null) {
nutrition = match.definition.nutrition;
saturation = match.definition.saturation;
if (match.definition.color != null) color = SoupConfig.rgb(match.definition.color);
if (!match.effects.isEmpty()) effects.add(new ApplyStatusEffectsConsumeEffect(match.effects));
tags.add("custom:" + match.id);
}
for (var effect : effects) if (effect instanceof ApplyStatusEffectsConsumeEffect apply)
for (var e : apply.effects()) tags.add("effect:" + BuiltInRegistries.MOB_EFFECT.getKey(e.getEffect().value()));
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
}
public String rejection(List<ItemStack> items) {
var data = items.stream().map(this::read).toList();
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
String error = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), config.blockedIngredients, config.incompatible);
if (error != null) return error;
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
if (nutrition < 0 || nutrition > config.maxNutrition || !Double.isFinite(saturation)
|| saturation < 0 || saturation > config.maxSaturation) return "Превышен лимит питания супа.";
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) return "В супе слишком много эффектов.";
return null;
}
public ItemStack brew(List<ItemStack> items) {
String error = rejection(items);
if (error != null) throw new IllegalArgumentException(error);
var data = items.stream().map(Ingredients::normalizedCopy)
.sorted(Comparator.comparing(s -> SoupFiles.encode(s, registries).toString())).map(this::read).toList();
int nutrition = data.stream().mapToInt(Ingredient::nutrition).sum();
float saturation = (float) data.stream().mapToDouble(Ingredient::saturation).sum();
var effects = data.stream().flatMap(i -> i.effects.stream()).toList();
int rgb = averageColor(data.stream().mapToInt(Ingredient::color).toArray());
var soup = new ItemStack(Items.MUSHROOM_STEW);
CustomData.update(DataComponents.CUSTOM_DATA, soup, tag -> {
tag.putBoolean("astracauldron:combined_soup", true);
tag.putInt("astracauldron:soup_color", rgb);
});
soup.set(DataComponents.CUSTOM_NAME, Component.literal(config.soupName).withStyle(s -> s.withColor(rgb).withItalic(false)));
soup.set(DataComponents.FOOD, new FoodProperties(nutrition, saturation, true));
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.USE_REMAINDER, new UseRemainder(ItemStackTemplate.fromNonEmptyStack(new ItemStack(Items.BOWL))));
normalize(soup);
return soup;
}
static int averageColor(int[] colors) {
int r = 0, g = 0, b = 0;
for (int c : colors) { r += (c >> 16) & 255; g += (c >> 8) & 255; b += c & 255; }
return ((r / colors.length) << 16) | ((g / colors.length) << 8) | (b / colors.length);
}
public static boolean isCombined(ItemStack stack) {
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getBooleanOr("astracauldron:combined_soup", false);
}
public static int color(ItemStack stack) {
return stack.getOrDefault(DataComponents.CUSTOM_DATA, CustomData.EMPTY).copyTag().getIntOr("astracauldron:soup_color", 0xB77A36) & 0xFFFFFF;
}
static ItemStack normalizedCopy(ItemStack stack) {
var copy = stack.copyWithCount(1); normalize(copy); return copy;
}
public static void normalize(ItemStack stack) {
if (!(stack.is(Items.MUSHROOM_STEW) || stack.is(Items.RABBIT_STEW) || stack.is(Items.BEETROOT_SOUP) || stack.is(Items.SUSPICIOUS_STEW))) return;
stack.set(DataComponents.MAX_STACK_SIZE, 16);
if (!isCombined(stack)) return;
stack.set(DataComponents.ITEM_MODEL, Identifier.parse("astradev_soups:combined_soup"));
var data = stack.getOrDefault(DataComponents.CUSTOM_MODEL_DATA, CustomModelData.EMPTY);
var colors = new ArrayList<>(data.colors());
if (colors.isEmpty()) colors.add(color(stack)); else colors.set(0, color(stack));
stack.set(DataComponents.CUSTOM_MODEL_DATA, new CustomModelData(data.floats(), data.flags(), data.strings(), colors));
var food = stack.get(DataComponents.FOOD);
var consumable = stack.get(DataComponents.CONSUMABLE);
if (food != null && consumable != null) stack.set(DataComponents.LORE, new ItemLore(lore(food, consumable.onConsumeEffects())));
}
private static List<Component> lore(FoodProperties food, List<ConsumeEffect> effects) {
var lines = new ArrayList<Component>();
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 e : apply.effects()) {
String duration = e.isInfiniteDuration() ? "∞" : String.format(Locale.ROOT, "%d:%02d", e.getDuration() / 1200, (e.getDuration() / 20) % 60);
lines.add(Component.translatable(e.getDescriptionId()).append(" " + SoupText.roman(e.getAmplifier() + 1) + " (" + duration + ")"
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : ""))
.withStyle(s -> s.withColor(ChatFormatting.AQUA).withItalic(false)));
} else lines.add(line(effect instanceof TeleportRandomlyConsumeEffect ? "Случайная телепортация"
: effect instanceof ClearAllStatusEffectsConsumeEffect ? "Снятие всех эффектов"
: effect instanceof RemoveStatusEffectsConsumeEffect ? "Снятие эффектов" : "Звук при употреблении", ChatFormatting.GRAY));
}
return lines;
}
private static Component line(String text, ChatFormatting color) {
return Component.literal(text).withStyle(s -> s.withColor(color).withItalic(false));
}
}
@@ -0,0 +1,195 @@
package online.astradev.cauldron;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
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.Potions;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.storage.LevelResource;
import online.astradev.plus.api.*;
/** Persistent dyed water and potion storage; all item transformations and rendering use AstraPlus API. */
public final class LiquidPots implements AutoCloseable {
private record Position(String dimension, BlockPos pos) {
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
}
public record Liquid(int levels, int rgb, CauldronApi.Potion potion) {
public Liquid {
if (levels < 1 || levels > 3 || rgb < 0 || rgb > 0xFFFFFF) throw new IllegalArgumentException("Invalid liquid");
}
Liquid withLevels(int value) { return new Liquid(value, rgb, potion); }
}
private static final Identifier OWNER = Identifier.parse("astracauldron:liquids");
private final MinecraftServer server;
private final CauldronApi api;
private final Path file;
private final Map<Position, Liquid> liquids = new LinkedHashMap<>();
public LiquidPots(MinecraftServer server) throws IOException {
this.server = server;
api = AstraPlusApi.current().flatMap(AstraPlusApi::cauldrons).orElseThrow();
file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/liquids.json");
if (Files.exists(file)) {
var json = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
if (json.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown liquid data version");
for (var entry : json.getAsJsonArray("cauldrons")) {
var c = entry.getAsJsonObject();
var pos = new Position(Identifier.parse(c.get("dimension").getAsString()).toString(), new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
CauldronApi.Potion potion = c.has("potion") ? api.potion(SoupFiles.decode(c.get("potion"), server.registryAccess())).orElseThrow() : null;
var liquid = new Liquid(c.get("levels").getAsInt(), c.get("rgb").getAsInt(), potion);
if (liquids.putIfAbsent(pos, 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; }
private boolean change(Position pos, Liquid next) {
var old = liquids.get(pos);
if (next == null) liquids.remove(pos); else liquids.put(pos, next);
try {
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);
if (next == null) removeSurface(pos);
return true;
} catch (Exception e) {
if (old == null) liquids.remove(pos); else liquids.put(pos, old);
AstraCauldron.LOG.error("Не удалось сохранить жидкость; действие отменено", e); return false;
}
}
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); var held = player.getMainHandItem();
if (!state.is(Blocks.CAULDRON) && !state.is(Blocks.WATER_CAULDRON)) return false;
var potion = api.potion(held);
if (liquid == null) {
if (potion.isPresent() && plainWater(potion.get())) {
int current = state.is(Blocks.WATER_CAULDRON) ? state.getValue(LayeredCauldronBlock.LEVEL) : 0;
if (current < 3) {
level.setBlock(blockPos,Blocks.WATER_CAULDRON.defaultBlockState().setValue(LayeredCauldronBlock.LEVEL,current+1),3);
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE));
}
return true;
}
var dye = api.mixDye(OptionalInt.empty(), held);
if (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 (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 (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 armor = api.dyeArmor(held, liquid.rgb);
if (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(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; }
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;
}
if (potion.isPresent()) {
if (!potion.get().equals(liquid.potion)) { say(player,"В котле другое зелье. Сначала заберите его бутылочками."); return true; }
if (liquid.levels == 3) { say(player,"Котёл уже полон."); return true; }
var next = liquid.withLevels(liquid.levels + 1);
if (!change(pos,next)) { error(player); return true; }
consumeAndGive(player,1,new ItemStack(Items.GLASS_BOTTLE)); setVisual(level,pos,next); return true;
}
if (held.is(Items.GLASS_BOTTLE)) {
var bottle = api.bottle(liquid.potion);
if (!decrease(level,pos,liquid,1)) { error(player); return true; }
consumeAndGive(player,1,bottle); sound(level,blockPos); return true;
}
var arrows = api.tipArrows(held,liquid.potion,liquid.levels);
if (arrows.isPresent()) {
var batch = arrows.get(); var result = batch.result();
if (!decrease(level,pos,liquid,batch.levelsUsed())) { error(player); return true; }
int count = result.getCount();
consumeAndGive(player,count,result); sound(level,blockPos);
say(player,"Обработано стрел: " + count + "."); return true;
}
say(player,"Зелье: " + liquid.levels + "/3. Окуните обычные стрелы или наберите бутылочку."); return true;
}
private boolean decrease(ServerLevel level, Position pos, Liquid old, int used) {
int remaining = old.levels - used; var next = remaining == 0 ? null : old.withLevels(remaining);
if (!change(pos,next)) return false;
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3);
if (next != null) setVisual(level,pos,next); return true;
}
private static boolean plainWater(CauldronApi.Potion potion) {
var contents = potion.contents();
return contents.is(Potions.WATER) && contents.customColor().isEmpty() && contents.customName().isEmpty() && potion.durationScale()==1f;
}
public boolean breakPot(ServerLevel level,BlockPos pos) { var position = Position.at(level,pos); return !liquids.containsKey(position) || change(position,null); }
public void tick() {
for (var entry : new ArrayList<>(liquids.entrySet())) {
var pos=entry.getKey(); var level=level(pos);
if (level==null || !level.hasChunkAt(pos.pos)) continue;
if (!level.getBlockState(pos.pos).is(Blocks.CAULDRON)) { change(pos,null); continue; }
surface(level,pos,entry.getValue());
}
}
private void setVisual(ServerLevel level,Position pos,Liquid liquid) {
level.setBlock(pos.pos,Blocks.CAULDRON.defaultBlockState(),3); surface(level,pos,liquid);
}
private void surface(ServerLevel level,Position pos,Liquid liquid) {
api.water().show(level,pos.pos,new ColoredWaterApi.Surface(OWNER,liquid.rgb,.375f+.1875f*liquid.levels));
}
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);
player.getInventory().add(result); if(!result.isEmpty()) player.drop(result,false);
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 say(ServerPlayer player,String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD),true); }
private static void error(ServerPlayer player) { say(player,"Не удалось сохранить котёл. Действие отменено."); }
}
@@ -0,0 +1,74 @@
package online.astradev.cauldron;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public final class SoupConfig {
public int servingsPerBrew = 4;
public boolean requireFullWater = true;
public double brewSeconds = 4;
public String soupName = "Комбинированный суп";
public String defaultColor = "#B77A36";
public int maxNutrition = 1000;
public float maxSaturation = 1000;
public List<String> blockedIngredients = new ArrayList<>();
public List<List<String>> incompatible = new ArrayList<>();
public Map<String, Custom> customIngredients = new LinkedHashMap<>();
public static final class Custom {
public JsonElement item;
public String astraPlusId;
public int nutrition;
public float saturation;
public String color;
public List<Effect> effects = new ArrayList<>();
}
public static final class Effect {
public String type;
public int duration;
public int amplifier;
}
public static SoupConfig load(Path file) throws IOException {
SoupConfig config = Files.exists(file)
? SoupFiles.JSON.fromJson(Files.readString(file), SoupConfig.class) : new SoupConfig();
if (config == null) throw new IllegalArgumentException("Пустая конфигурация");
config.validate();
if (!Files.exists(file)) SoupFiles.write(file, SoupFiles.JSON.toJsonTree(config));
return config;
}
public void validate() {
if (servingsPerBrew < 1 || servingsPerBrew > 16 || !Double.isFinite(brewSeconds)
|| brewSeconds < .5 || brewSeconds > 60 || maxNutrition < 0
|| !Float.isFinite(maxSaturation) || maxSaturation < 0 || soupName == null || soupName.isBlank())
throw new IllegalArgumentException("Некорректные настройки варки/питания");
rgb(defaultColor);
if (blockedIngredients == null || incompatible == null || customIngredients == null)
throw new IllegalArgumentException("Списки настроек не могут быть null");
blockedIngredients.forEach(SoupConfig::selector);
for (var pair : incompatible) {
if (pair == null || pair.size() != 2) throw new IllegalArgumentException("В incompatible нужны пары");
pair.forEach(SoupConfig::selector);
}
for (var entry : customIngredients.entrySet()) {
var c = entry.getValue();
if (!entry.getKey().matches("[a-z0-9_-]+") || c == null || (c.item == null) == (c.astraPlusId == null)
|| c.nutrition < 0 || c.nutrition > maxNutrition || !Float.isFinite(c.saturation)
|| c.saturation < 0 || c.saturation > maxSaturation || c.effects == null)
throw new IllegalArgumentException("Некорректный ингредиент " + entry.getKey());
if (c.astraPlusId != null && !c.astraPlusId.matches("[a-z0-9_.-]+:[a-z0-9/._-]+"))
throw new IllegalArgumentException("Некорректный AstraPlus ID");
if (c.color != null) rgb(c.color);
for (var e : c.effects) if (e == null || e.type == null || e.duration < -1 || e.duration == 0
|| e.amplifier < 0 || e.amplifier > 255) throw new IllegalArgumentException("Некорректный эффект");
}
}
private static void selector(String s) {
if (s == null || !s.toLowerCase(Locale.ROOT).matches("\\*|(?:material|effect|custom|astraplus|soup):[a-z0-9_:./-]+"))
throw new IllegalArgumentException("Неизвестный селектор: " + s);
}
static int rgb(String s) {
if (s == null || !s.matches("#[0-9a-fA-F]{6}")) throw new IllegalArgumentException("Цвет: #RRGGBB");
return Integer.parseInt(s.substring(1), 16);
}
}
@@ -0,0 +1,38 @@
package online.astradev.cauldron;
import com.mojang.math.Transformation;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.EntityTypes;
import net.minecraft.world.item.*;
import net.minecraft.world.level.storage.ValueOutput;
import org.joml.Quaternionf;
import org.joml.Vector3f;
final class SoupDisplay extends Display.ItemDisplay {
static final String TAG = "astracauldron:cauldron_visual";
SoupDisplay(ServerLevel level, BlockPos pos, ItemStack stack) {
super(EntityTypes.ITEM_DISPLAY, level);
setPos(pos.getX() + .5, pos.getY() + .5, pos.getZ() + .5);
getSlot(0).set(stack.copy());
setItemTransform(ItemDisplayContext.FIXED);
setNoGravity(true);
setInvulnerable(true);
setSilent(true);
addTag(TAG);
setTransformationInterpolationDuration(2);
}
void ingredient(int slot, int water, int ticks, int elapsed, int duration) {
var frame = CauldronAnimation.frame(slot, water, ticks, elapsed, duration);
setTransformationInterpolationDelay(0);
setTransformation(new Transformation(new Vector3f((float)frame.x() - .5f, (float)frame.y() - .5f, (float)frame.z() - .5f),
new Quaternionf(), new Vector3f(.3f), new Quaternionf().rotationY(ticks * .035f + slot)));
}
@Override public boolean shouldBeSaved() { return false; }
@Override public boolean saveAsPassenger(ValueOutput output) { return false; }
}
@@ -0,0 +1,29 @@
package online.astradev.cauldron;
import com.google.gson.*;
import com.mojang.serialization.JsonOps;
import java.io.IOException;
import java.nio.file.*;
import net.minecraft.core.HolderLookup;
import net.minecraft.resources.RegistryOps;
import net.minecraft.world.item.ItemStack;
final class SoupFiles {
static final Gson JSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
private SoupFiles() {}
static void write(Path path, JsonElement json) throws IOException {
Files.createDirectories(path.getParent());
Path temp = Files.createTempFile(path.getParent(), "soups-", ".tmp");
try {
Files.writeString(temp, JSON.toJson(json));
try { Files.move(temp, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
catch (AtomicMoveNotSupportedException e) { Files.move(temp, path, StandardCopyOption.REPLACE_EXISTING); }
} finally { Files.deleteIfExists(temp); }
}
static JsonElement encode(ItemStack stack, HolderLookup.Provider registries) {
return ItemStack.CODEC.encodeStart(RegistryOps.create(JsonOps.INSTANCE, registries), stack).getOrThrow();
}
static ItemStack decode(JsonElement json, HolderLookup.Provider registries) {
return ItemStack.CODEC.parse(RegistryOps.create(JsonOps.INSTANCE, registries), json).getOrThrow();
}
}
@@ -0,0 +1,248 @@
package online.astradev.cauldron;
import com.google.gson.*;
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
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.Level;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.LevelResource;
public final class SoupPots implements AutoCloseable {
record Position(String dimension, BlockPos pos) {
static Position at(ServerLevel level, BlockPos pos) { return new Position(level.dimension().identifier().toString(), pos.immutable()); }
}
public record Pot(List<ItemStack> 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<ItemStack> items) { return new Pot(items, ItemStack.EMPTY, 0, 0, 0); }
}
private final MinecraftServer server;
private static final Identifier WATER_OWNER = Identifier.parse("astracauldron:cauldrons");
private final online.astradev.plus.api.ColoredWaterApi water;
private final Path file;
private final Path configFile;
private SoupConfig config;
private Ingredients ingredients;
private final Map<Position, Pot> pots = new LinkedHashMap<>();
private final Map<Position, List<SoupDisplay>> visuals = new HashMap<>();
private final Map<Position, Integer> elapsed = new HashMap<>();
private int ticks;
public SoupPots(MinecraftServer server, Path configFile) throws IOException {
this.server = server;
this.water = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.coloredWater()).orElseThrow();
this.file = server.getWorldPath(LevelResource.ROOT).resolve("astracauldron/cauldrons.json");
this.configFile = configFile;
reload();
load();
}
public Ingredients ingredients() { return ingredients; }
public boolean contains(ServerLevel level, BlockPos pos) { return pots.containsKey(Position.at(level, pos)); }
public Pot get(ServerLevel level, BlockPos pos) { return pots.get(Position.at(level, pos)); }
public void reload() throws IOException {
var next = SoupConfig.load(configFile);
var nextIngredients = new Ingredients(next, server.registryAccess());
config = next;
ingredients = nextIngredients;
}
public void register(String id, ServerPlayer player, int nutrition, float saturation) throws IOException {
if (!id.matches("[a-z0-9_-]+") || player.getMainHandItem().isEmpty()) throw new IllegalArgumentException("Нужны ID и предмет в руке");
var next = SoupFiles.JSON.fromJson(SoupFiles.JSON.toJson(config), SoupConfig.class);
var custom = new SoupConfig.Custom();
// Resolve by stable AstraPlus identity; definitions can evolve without invalidating the registration.
var plus = online.astradev.plus.api.AstraPlusApi.current().flatMap(api -> api.find(player.getMainHandItem()));
if (plus.isPresent()) custom.astraPlusId = plus.get().id().toString();
else custom.item = SoupFiles.encode(Ingredients.normalizedCopy(player.getMainHandItem()), server.registryAccess());
custom.nutrition = nutrition;
custom.saturation = saturation;
next.customIngredients.put(id, custom);
var validated = new Ingredients(next, server.registryAccess());
SoupFiles.write(configFile, SoupFiles.JSON.toJsonTree(next));
config = next;
ingredients = validated;
}
private void load() throws IOException {
if (!Files.exists(file)) return;
var root = JsonParser.parseString(Files.readString(file)).getAsJsonObject();
if (root.get("version").getAsInt() != 1) throw new IllegalArgumentException("Unknown cauldron data version");
for (var value : root.getAsJsonArray("cauldrons")) {
var c = value.getAsJsonObject();
String dimension = Identifier.parse(c.get("dimension").getAsString()).toString();
var pos = new Position(dimension, new BlockPos(c.get("x").getAsInt(), c.get("y").getAsInt(), c.get("z").getAsInt()));
var items = new ArrayList<ItemStack>();
for (var i : c.getAsJsonArray("items")) items.add(SoupFiles.decode(i, server.registryAccess()));
var soup = c.has("soup") ? SoupFiles.decode(c.get("soup"), server.registryAccess()) : ItemStack.EMPTY;
var pot = new Pot(items, soup, c.get("brewTicks").getAsInt(), c.get("servings").getAsInt(), c.get("capacity").getAsInt());
validate(pot);
if (pots.putIfAbsent(pos, pot) != null) throw new IllegalArgumentException("Duplicate cauldron " + pos);
}
}
private static void validate(Pot p) {
if (p.items.size() > 4 || p.items.stream().anyMatch(i -> i.isEmpty() || i.getCount() != 1)
|| p.brewTicks < 0 || p.brewTicks > 1200
|| (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.brewing() ? p.items.size() != 4 : !p.items.isEmpty())))
throw new IllegalArgumentException("Invalid cauldron contents");
}
private boolean change(Position pos, Pot next) {
Pot old = pots.get(pos);
if (next == null) pots.remove(pos); else { validate(next); pots.put(pos, next); }
try {
var root = new JsonObject(); root.addProperty("version", 1);
var array = new JsonArray(); root.add("cauldrons", array);
for (var e : pots.entrySet()) {
var c = new JsonObject(); var p = e.getKey(); var pot = e.getValue();
c.addProperty("dimension", p.dimension); c.addProperty("x", p.pos.getX()); c.addProperty("y", p.pos.getY()); c.addProperty("z", p.pos.getZ());
var items = new JsonArray(); pot.items.forEach(i -> items.add(SoupFiles.encode(i, server.registryAccess()))); c.add("items", items);
if (!pot.soup.isEmpty()) c.add("soup", SoupFiles.encode(pot.soup, server.registryAccess()));
c.addProperty("brewTicks", pot.brewTicks); c.addProperty("servings", pot.servings); c.addProperty("capacity", pot.capacity);
array.add(c);
}
SoupFiles.write(file, root);
if (old == null || next == null || old.ready() != next.ready() || old.items.size() != next.items.size()) removeVisuals(pos);
elapsed.remove(pos);
return true;
} catch (Exception e) {
if (old == null) pots.remove(pos); else pots.put(pos, old);
AstraCauldron.LOG.error("Не удалось сохранить котёл; действие отменено", e);
return false;
}
}
/** Returns whether vanilla interaction should be consumed. Saves before taking/giving items. */
public boolean interact(ServerPlayer player, BlockPos blockPos, InteractionHand hand) {
var level = player.level(); var pos = Position.at(level, blockPos); var pot = pots.get(pos);
if (player.isSpectator()) return false;
if (hand != InteractionHand.MAIN_HAND) return pot != null;
var state = level.getBlockState(blockPos);
if (!valid(state, pot)) return false;
var held = player.getMainHandItem();
if (pot == null && ingredients.read(held) == null) return false;
if (pot == null) {
if (config.requireFullWater && state.getValue(LayeredCauldronBlock.LEVEL) != 3) {
say(player, "Сначала наполните котёл водой доверху."); return true;
}
pot = Pot.raw(List.of());
}
if (pot.brewing()) { say(player, "Суп варится… Осталось: " + Math.max(1, (pot.brewTicks - elapsed.getOrDefault(pos, 0) + 19) / 20) + " с."); return true; }
if (pot.ready()) {
if (!held.is(Items.BOWL)) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return true; }
int left = pot.servings - 1; var result = pot.soup.copy();
if (!change(pos, left == 0 ? null : new Pot(List.of(), pot.soup, 0, left, pot.capacity))) { saveError(player); return true; }
held.consume(1, player); give(player, result);
level.setBlock(blockPos, Blocks.CAULDRON.defaultBlockState(), 3);
if (left > 0) show(level, pos, pots.get(pos));
sound(level, blockPos, SoundEvents.BOTTLE_FILL);
say(player, left == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + left + "."); return true;
}
if (pot.items.size() == 4 && (player.isShiftKeyDown() || !held.isEmpty())) {
String rejection = ingredients.rejection(pot.items);
if (rejection != null) { say(player, rejection + " ПКМ пустой рукой возвращает последний ингредиент."); return true; }
var next = new Pot(pot.items, ingredients.brew(pot.items), (int)Math.round(config.brewSeconds * 20), config.servingsPerBrew, config.servingsPerBrew);
if (!change(pos, next)) { saveError(player); return true; }
sound(level, blockPos, SoundEvents.BREWING_STAND_BREW); say(player, "Варка началась! Дождитесь окончания водоворота."); return true;
}
if (held.isEmpty()) {
if (pot.items.isEmpty()) return true;
var remaining = new ArrayList<>(pot.items); var last = remaining.removeLast();
if (!change(pos, remaining.isEmpty() ? null : Pot.raw(remaining))) { saveError(player); return true; }
give(player, last.copy()); say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4."); return true;
}
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return true; }
var items = new ArrayList<>(pot.items); items.add(held.copyWithCount(1));
if (!change(pos, Pot.raw(items))) { saveError(player); return true; }
held.consume(1, player); show(level, pos, pots.get(pos)); sound(level, blockPos, SoundEvents.GENERIC_SPLASH);
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
return true;
}
public boolean breakPot(ServerLevel level, BlockPos blockPos) {
var pos = Position.at(level, blockPos); var old = pots.get(pos);
if (old == null) return true;
if (!change(pos, null)) return false;
old.items.forEach(i -> Block.popResource(level, blockPos, i.copy()));
return true;
}
private static boolean valid(BlockState state, Pot pot) {
return state.is(Blocks.WATER_CAULDRON) || (state.is(Blocks.CAULDRON) && pot != null && pot.ready());
}
public void tick() {
ticks++;
for (var entry : new ArrayList<>(pots.entrySet())) {
var pos = entry.getKey(); var pot = entry.getValue();
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
if (level == null || !level.hasChunkAt(pos.pos)) { removeVisuals(pos); continue; }
if (!valid(level.getBlockState(pos.pos), pot)) { breakPot(level, pos.pos); continue; }
if (pot.brewing()) {
int time = elapsed.merge(pos, 1, Integer::sum);
if (time >= pot.brewTicks && (time - pot.brewTicks) % 20 == 0
&& change(pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
pot = pots.get(pos);
level.setBlock(pos.pos, Blocks.CAULDRON.defaultBlockState(), 3);
sound(level, pos.pos, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP);
level.sendParticles(ParticleTypes.CLOUD, pos.pos.getX() + .5, pos.pos.getY() + 1.05, pos.pos.getZ() + .5, 12, .2, .12, .2, .01);
}
}
show(level, pos, pot);
if (ticks % 2 == 0 && !pot.ready()) {
var displays = visuals.get(pos);
int water = level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL);
for (int i = 0; i < displays.size(); i++) displays.get(i).ingredient(i, water, ticks + 2, elapsed.getOrDefault(pos, 0) + 2, pot.brewTicks);
if (pot.brewing() && ticks % 10 == 0)
level.sendParticles(ParticleTypes.SPLASH, pos.pos.getX() + .5, pos.pos.getY() + .95, pos.pos.getZ() + .5, 2, .2, 0, .2, 0);
}
}
if (ticks % 20 == 0) for (var player : server.getPlayerList().getPlayers()) {
for (var slot : player.containerMenu.slots) Ingredients.normalize(slot.getItem());
for (int i = 0; i < player.getInventory().getContainerSize(); i++) Ingredients.normalize(player.getInventory().getItem(i));
Ingredients.normalize(player.containerMenu.getCarried());
player.containerMenu.broadcastChanges();
}
}
private void show(ServerLevel level, Position pos, Pot pot) {
if (pot.ready()) {
water.show(level, pos.pos, new online.astradev.plus.api.ColoredWaterApi.Surface(WATER_OWNER,
Ingredients.color(pot.soup), (float)CauldronAnimation.liquidHeight(pot.servings, pot.capacity)));
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<SoupDisplay>();
for (int i = 0; i < pot.items.size(); i++) {
var display = new SoupDisplay(level, pos.pos, pot.items.get(i));
display.ingredient(i, level.getBlockState(pos.pos).getValue(LayeredCauldronBlock.LEVEL), ticks, elapsed.getOrDefault(pos, 0), pot.brewTicks);
displays.add(display);
}
displays.forEach(level::addFreshEntity); visuals.put(pos, displays);
}
public void unload(ServerLevel level, int chunkX, int chunkZ) {
for (var pos : new ArrayList<>(visuals.keySet())) if (pos.dimension.equals(level.dimension().identifier().toString())
&& (pos.pos.getX() >> 4) == chunkX && (pos.pos.getZ() >> 4) == chunkZ) removeVisuals(pos);
}
private void removeVisuals(Position pos) {
var list = visuals.remove(pos); if (list != null) list.forEach(SoupDisplay::discard);
var level = server.getLevel(ResourceKey.create(Registries.DIMENSION, Identifier.parse(pos.dimension)));
if (level != null) water.remove(level, pos.pos, WATER_OWNER);
}
@Override public void close() {
for (var pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
water.removeAll(WATER_OWNER);
}
private static void sound(ServerLevel level, BlockPos pos, SoundEvent sound) { level.playSound(null, pos, sound, SoundSource.BLOCKS, .8f, 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 say(ServerPlayer player, String text) { player.sendSystemMessage(Component.literal(text).withStyle(ChatFormatting.GOLD), true); }
private static void saveError(ServerPlayer player) { say(player, "Не удалось сохранить котёл. Обратитесь к администратору."); }
}
@@ -0,0 +1,23 @@
package online.astradev.cauldron;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
/** Export before AstraPlus's startup pack build; never overwrite administrator resources. */
final class SoupResources {
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());
if (Files.exists(target)) continue;
try (var input = SoupResources.class.getResourceAsStream("/astra-resources/" + relative)) {
if (input == null) throw new IOException("Missing resource " + relative);
Files.copy(input, target);
}
}
}
}
@@ -0,0 +1,19 @@
package online.astradev.cauldron;
final class SoupText {
private SoupText() {}
static String roman(int level) {
if (level < 1 || level > 256)
throw new IllegalArgumentException("Potion level out of range: " + level);
int[] values = {100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] numerals = {"C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder text = new StringBuilder();
for (int i = 0; i < values.length; i++)
while (level >= values[i]) {
text.append(numerals[i]);
level -= values[i];
}
return text.toString();
}
}
@@ -0,0 +1,25 @@
package online.astradev.cauldron.mixin;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Fluid;
import online.astradev.cauldron.AstraCauldron;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** NeoForge has no cancellable event for these vanilla cauldron mutations. */
@Mixin({CauldronBlock.class, LayeredCauldronBlock.class})
abstract class CauldronWeatherMixin {
@Inject(method = "handlePrecipitation", at = @At("HEAD"), cancellable = true)
private void soups$rain(BlockState state, Level level, BlockPos pos, Biome.Precipitation precipitation, CallbackInfo ci) {
if (AstraCauldron.occupied(level, pos)) ci.cancel();
}
@Inject(method = "receiveStalactiteDrip", at = @At("HEAD"), cancellable = true)
private void soups$drip(BlockState state, Level level, BlockPos pos, Fluid fluid, CallbackInfo ci) {
if (AstraCauldron.occupied(level, pos)) ci.cancel();
}
}
@@ -0,0 +1,18 @@
package online.astradev.cauldron.mixin;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.LayeredCauldronBlock;
import net.minecraft.world.level.block.state.BlockState;
import online.astradev.cauldron.AstraCauldron;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(LayeredCauldronBlock.class)
abstract class LayeredCauldronMixin {
@Inject(method = "lowerFillLevel", at = @At("HEAD"), cancellable = true)
private static void soups$lower(BlockState state, Level level, BlockPos pos, CallbackInfo ci) {
if (AstraCauldron.occupied(level, pos)) ci.cancel();
}
}
@@ -0,0 +1,23 @@
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 org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.*;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/** Per-stack patch is sent to vanilla clients; no change to their assumed item defaults. */
@Mixin(ItemStack.class)
abstract class SoupStackMixin {
@Inject(method = "<init>(Lnet/minecraft/core/Holder;ILnet/minecraft/core/component/PatchedDataComponentMap;)V", at = @At("RETURN"))
private void soups$stackSize(Holder<Item> item, int count, PatchedDataComponentMap components, CallbackInfo ci) {
var key = item.unwrapKey().orElse(null);
if (key == null || !key.identifier().getNamespace().equals("minecraft")) return;
switch (key.identifier().getPath()) {
case "mushroom_stew", "rabbit_stew", "beetroot_soup", "suspicious_stew" -> components.set(DataComponents.MAX_STACK_SIZE, 16);
default -> { }
}
}
}