Simplify ingredient matching and clean up source and config comments

This commit is contained in:
2026-09-05 16:47:42 +03:00
parent 2eb4ca02d0
commit 1f08010db6
10 changed files with 869 additions and 326 deletions
@@ -5,9 +5,11 @@ import io.papermc.paper.datacomponent.item.Consumable;
import io.papermc.paper.datacomponent.item.FoodProperties;
import io.papermc.paper.datacomponent.item.UseRemainder;
import io.papermc.paper.datacomponent.item.consumable.ConsumeEffect;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
@@ -25,8 +27,21 @@ import java.lang.reflect.Method;
import java.util.*;
public final class Ingredients {
public record Ingredient(int nutrition, float saturation, List<ConsumeEffect> effects, Set<String> tags, Color color) {}
private record Custom(String id, ItemStack sample, int nutrition, float saturation, List<PotionEffect> effects, Color color) {}
public record Ingredient(
int nutrition,
float saturation,
List<ConsumeEffect> effects,
Set<String> tags,
Color color) {}
private record Custom(
String id,
ItemStack sample,
int nutrition,
float saturation,
List<PotionEffect> effects,
Color color) {}
private final AstraSoupsPlugin plugin;
private final List<Custom> custom = new ArrayList<>();
private List<String> blocked;
@@ -41,12 +56,22 @@ public final class Ingredients {
throw new IllegalArgumentException("brew-seconds должно быть от 0.5 до 60");
}
int servings = plugin.getConfig().getInt("servings-per-brew", 4);
if (servings < 1 || servings > 16) throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
defaultColor = Color.fromRGB(Integer.parseInt(plugin.getConfig().getString("default-color", "#B77A36").replace("#", ""), 16));
if (servings < 1 || servings > 16)
throw new IllegalArgumentException("servings-per-brew должно быть от 1 до 16");
defaultColor =
Color.fromRGB(
Integer.parseInt(
plugin.getConfig()
.getString("default-color", "#B77A36")
.replace("#", ""),
16));
blocked = plugin.getConfig().getStringList("blocked-ingredients");
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
if (!(value instanceof List<?> list) || list.size() != 2 || list.stream().anyMatch(x -> !(x instanceof String))) {
throw new IllegalArgumentException("Каждое правило incompatible должно содержать два селектора");
if (!(value instanceof List<?> list)
|| list.size() != 2
|| list.stream().anyMatch(x -> !(x instanceof String))) {
throw new IllegalArgumentException(
"Каждое правило incompatible должно содержать два селектора");
}
pairs.add(List.of((String) list.get(0), (String) list.get(1)));
}
@@ -55,28 +80,52 @@ public final class Ingredients {
|| plugin.getConfig().getDouble("max-saturation", 1000) < 0) {
throw new IllegalArgumentException("Некорректные ограничения питания");
}
ConfigurationSection section = plugin.getConfig().getConfigurationSection("custom-ingredients");
if (section != null) for (String id : section.getKeys(false)) {
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
ItemStack sample = c.getItemStack("item");
int nutrition = c.getInt("nutrition");
float saturation = (float) c.getDouble("saturation");
if (sample == null || sample.getType().isAir() || nutrition < 0 || saturation < 0 || !Float.isFinite(saturation)) {
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
ConfigurationSection section =
plugin.getConfig().getConfigurationSection("custom-ingredients");
if (section != null)
for (String id : section.getKeys(false)) {
ConfigurationSection c =
Objects.requireNonNull(section.getConfigurationSection(id));
ItemStack sample = c.getItemStack("item");
int nutrition = c.getInt("nutrition");
float saturation = (float) c.getDouble("saturation");
if (sample == null
|| sample.getType().isAir()
|| nutrition < 0
|| saturation < 0
|| !Float.isFinite(saturation)) {
throw new IllegalArgumentException("Некорректный custom-ingredients." + id);
}
List<PotionEffect> effects = new ArrayList<>();
for (Map<?, ?> map : c.getMapList("effects")) {
PotionEffectType type =
Registry.EFFECT.get(
Objects.requireNonNull(
NamespacedKey.fromString(
String.valueOf(map.get("type")))));
if (type == null)
throw new IllegalArgumentException("Неизвестный эффект в " + id);
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255)
throw new IllegalArgumentException("Некорректный эффект в " + id);
effects.add(new PotionEffect(type, duration, amplifier));
}
normalize(sample);
Color customColor =
c.isString("color")
? Color.fromRGB(
Integer.parseInt(c.getString("color").replace("#", ""), 16))
: null;
custom.add(
new Custom(
id,
sample.asOne(),
nutrition,
saturation,
List.copyOf(effects),
customColor));
}
List<PotionEffect> effects = new ArrayList<>();
for (Map<?, ?> map : c.getMapList("effects")) {
PotionEffectType type = Registry.EFFECT.get(Objects.requireNonNull(NamespacedKey.fromString(String.valueOf(map.get("type")))));
if (type == null) throw new IllegalArgumentException("Неизвестный эффект в " + id);
int duration = Integer.parseInt(String.valueOf(map.get("duration")));
int amplifier = Integer.parseInt(String.valueOf(map.get("amplifier")));
if (duration < -1 || duration == 0 || amplifier < 0 || amplifier > 255) throw new IllegalArgumentException("Некорректный эффект в " + id);
effects.add(new PotionEffect(type, duration, amplifier));
}
normalize(sample);
Color customColor = c.isString("color") ? Color.fromRGB(Integer.parseInt(c.getString("color").replace("#", ""), 16)) : null;
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects), customColor));
}
if (plugin.getServer().getPluginManager().isPluginEnabled("ItemsAdder")) {
try {
Class<?> cls = Class.forName("dev.lone.itemsadder.api.CustomStack");
@@ -92,8 +141,13 @@ public final class Ingredients {
if (item == null || item.getType().isAir()) return null;
FoodProperties food = item.getData(DataComponentTypes.FOOD);
ItemMeta meta = item.getItemMeta();
Custom match = custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
boolean potion = switch (item.getType()) { case POTION, SPLASH_POTION, LINGERING_POTION -> true; default -> false; };
Custom match =
custom.stream().filter(c -> c.sample.isSimilar(item)).findFirst().orElse(null);
boolean potion =
switch (item.getType()) {
case POTION, SPLASH_POTION, LINGERING_POTION -> true;
default -> false;
};
// Cake is edible as a placed block and has no FOOD component.
boolean cake = item.getType() == Material.CAKE;
if (food == null && !potion && match == null && !cake) return null;
@@ -103,9 +157,17 @@ public final class Ingredients {
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
if (consumable != null) effects.addAll(consumable.consumeEffects());
Color color = IngredientColors.food(item.getType(), defaultColor);
if (isCombined(item)) color = Color.fromRGB(meta.getPersistentDataContainer().getOrDefault(plugin.colorKey, PersistentDataType.INTEGER, defaultColor.asRGB()));
if (isCombined(item))
color =
Color.fromRGB(
meta.getPersistentDataContainer()
.getOrDefault(
plugin.colorKey,
PersistentDataType.INTEGER,
defaultColor.asRGB()));
if (potion && meta instanceof PotionMeta pm) {
if (!pm.getAllEffects().isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
if (!pm.getAllEffects().isEmpty())
effects.add(ConsumeEffect.applyStatusEffects(pm.getAllEffects(), 1));
color = pm.computeEffectiveColor();
}
if (meta instanceof SuspiciousStewMeta stew && stew.hasCustomEffects()) {
@@ -118,31 +180,39 @@ public final class Ingredients {
nutrition = match.nutrition;
saturation = match.saturation;
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
if (!match.effects.isEmpty()) effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
if (!match.effects.isEmpty())
effects.add(ConsumeEffect.applyStatusEffects(match.effects, 1));
if (match.color != null) color = match.color;
}
if (iaLookup != null) try {
Object ia = iaLookup.invoke(null, item);
if (ia != null) tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
}
for (ConsumeEffect effect : effects) if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
}
if (iaLookup != null)
try {
Object ia = iaLookup.invoke(null, item);
if (ia != null)
tags.add("itemsadder:" + iaId.invoke(ia).toString().toLowerCase(Locale.ROOT));
} catch (ReflectiveOperationException e) {
throw new IllegalStateException("Ошибка чтения уникальной еды ItemsAdder", e);
}
for (ConsumeEffect effect : effects)
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
for (PotionEffect pe : apply.effects()) tags.add("effect:" + pe.getType().getKey());
}
return new Ingredient(nutrition, saturation, List.copyOf(effects), Set.copyOf(tags), color);
}
public String rejection(List<ItemStack> items) {
List<Ingredient> data = items.stream().map(this::read).toList();
if (data.contains(null)) return "Предмет больше не зарегистрирован как ингредиент.";
String rule = CombinationRules.rejection(data.stream().map(Ingredient::tags).toList(), blocked, pairs);
String rule =
CombinationRules.rejection(
data.stream().map(Ingredient::tags).toList(), blocked, pairs);
if (rule != null) return rule;
long nutrition = data.stream().mapToLong(Ingredient::nutrition).sum();
double saturation = data.stream().mapToDouble(Ingredient::saturation).sum();
if (nutrition > plugin.getConfig().getInt("max-nutrition", 1000)
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000)) return "Превышен лимит питания супа.";
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256) return "В супе слишком много эффектов.";
|| saturation > plugin.getConfig().getDouble("max-saturation", 1000))
return "Превышен лимит питания супа.";
if (data.stream().mapToInt(i -> i.effects.size()).sum() > 256)
return "В супе слишком много эффектов.";
return null;
}
@@ -150,60 +220,131 @@ public final class Ingredients {
String error = rejection(items);
if (error != null) throw new IllegalArgumentException(error);
// Stable order makes the same recipe stack regardless of insertion order.
List<Ingredient> ingredients = items.stream().map(ItemStack::asOne)
.peek(Ingredients::normalize)
.sorted(Comparator.comparing(stack -> Base64.getEncoder().encodeToString(stack.serializeAsBytes())))
.map(this::read).toList();
List<Ingredient> ingredients =
items.stream()
.map(ItemStack::asOne)
.peek(Ingredients::normalize)
.sorted(
Comparator.comparing(
stack ->
Base64.getEncoder()
.encodeToString(stack.serializeAsBytes())))
.map(this::read)
.toList();
int nutrition = ingredients.stream().mapToInt(Ingredient::nutrition).sum();
float saturation = (float) ingredients.stream().mapToDouble(Ingredient::saturation).sum();
List<ConsumeEffect> effects = ingredients.stream().flatMap(i -> i.effects.stream()).toList();
List<ConsumeEffect> effects =
ingredients.stream().flatMap(i -> i.effects.stream()).toList();
ItemStack soup = new ItemStack(Material.MUSHROOM_STEW);
ItemMeta meta = soup.getItemMeta();
meta.displayName(Component.text(plugin.getConfig().getString("soup-name", "Комбинированный суп"),
net.kyori.adventure.text.format.TextColor.color(color(ingredients).asRGB())).decoration(TextDecoration.ITALIC, false));
meta.displayName(
Component.text(
plugin.getConfig().getString("soup-name", "Комбинированный суп"),
net.kyori.adventure.text.format.TextColor.color(
color(ingredients).asRGB()))
.decoration(TextDecoration.ITALIC, false));
meta.lore(soupLore(nutrition, saturation, effects));
meta.getPersistentDataContainer().set(plugin.soupKey, PersistentDataType.BYTE, (byte) 1);
meta.getPersistentDataContainer().set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
meta.getPersistentDataContainer()
.set(plugin.colorKey, PersistentDataType.INTEGER, color(ingredients).asRGB());
soup.setItemMeta(meta);
soup.setData(DataComponentTypes.FOOD, FoodProperties.food().nutrition(nutrition).saturation(saturation).canAlwaysEat(true).build());
soup.setData(DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
soup.setData(DataComponentTypes.USE_REMAINDER, UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
soup.setData(
DataComponentTypes.FOOD,
FoodProperties.food()
.nutrition(nutrition)
.saturation(saturation)
.canAlwaysEat(true)
.build());
soup.setData(
DataComponentTypes.CONSUMABLE, Consumable.consumable().effects(effects).build());
soup.setData(
DataComponentTypes.USE_REMAINDER,
UseRemainder.useRemainder(new ItemStack(Material.BOWL)));
normalize(soup);
return soup;
}
private static List<Component> soupLore(int nutrition, float saturation, List<ConsumeEffect> effects) {
private static List<Component> soupLore(
int nutrition, float saturation, List<ConsumeEffect> effects) {
List<Component> lore = new ArrayList<>();
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
lore.add(line(String.format(Locale.ROOT, "Насыщение: +%.1f", saturation), NamedTextColor.GOLD));
lore.add(
line(
String.format(Locale.ROOT, "Насыщение: +%.1f", saturation),
NamedTextColor.GOLD));
for (ConsumeEffect effect : effects) {
if (effect instanceof ConsumeEffect.ApplyStatusEffects apply) {
for (PotionEffect pe : apply.effects()) {
String duration = pe.isInfinite() ? "∞" : (pe.getDuration() / 1200) + ":" + String.format(Locale.ROOT, "%02d", (pe.getDuration() / 20) % 60);
lore.add(Component.translatable(pe.getType().translationKey()).color(NamedTextColor.AQUA)
.append(Component.text(" " + SoupText.roman(pe.getAmplifier() + 1) + " (" + duration + ")"
+ (apply.probability() < 1 ? " " + Math.round(apply.probability() * 100) + "%" : "")))
.decoration(TextDecoration.ITALIC, false));
String duration =
pe.isInfinite()
? "∞"
: (pe.getDuration() / 1200)
+ ":"
+ String.format(
Locale.ROOT,
"%02d",
(pe.getDuration() / 20) % 60);
lore.add(
Component.translatable(pe.getType().translationKey())
.color(NamedTextColor.AQUA)
.append(
Component.text(
" "
+ SoupText.roman(pe.getAmplifier() + 1)
+ " ("
+ duration
+ ")"
+ (apply.probability() < 1
? " "
+ Math.round(
apply
.probability()
* 100)
+ "%"
: "")))
.decoration(TextDecoration.ITALIC, false));
}
} else lore.add(line(effect instanceof ConsumeEffect.TeleportRandomly ? "Случайная телепортация"
: effect instanceof ConsumeEffect.ClearAllStatusEffects ? "Снятие всех эффектов"
: effect instanceof ConsumeEffect.RemoveStatusEffects ? "Снятие эффектов" : "Звук при употреблении", NamedTextColor.GRAY));
} else
lore.add(
line(
effect instanceof ConsumeEffect.TeleportRandomly
? "Случайная телепортация"
: effect instanceof ConsumeEffect.ClearAllStatusEffects
? "Снятие всех эффектов"
: effect
instanceof
ConsumeEffect.RemoveStatusEffects
? "Снятие эффектов"
: "Звук при употреблении",
NamedTextColor.GRAY));
}
return lore;
}
private static Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
private static Component line(String s, NamedTextColor color) {
return Component.text(s, color).decoration(TextDecoration.ITALIC, false);
}
private Color color(List<Ingredient> ingredients) {
return Color.fromRGB((int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
return Color.fromRGB(
(int) ingredients.stream().mapToInt(i -> i.color.getRed()).average().orElse(183),
(int) ingredients.stream().mapToInt(i -> i.color.getGreen()).average().orElse(122),
(int) ingredients.stream().mapToInt(i -> i.color.getBlue()).average().orElse(54));
}
public boolean isCombined(ItemStack item) {
return item.hasItemMeta() && item.getItemMeta().getPersistentDataContainer().has(plugin.soupKey, PersistentDataType.BYTE);
return item.hasItemMeta()
&& item.getItemMeta()
.getPersistentDataContainer()
.has(plugin.soupKey, PersistentDataType.BYTE);
}
public static boolean normalize(ItemStack item) {
if (item == null) return false;
if (!switch (item.getType()) { case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true; default -> false; }) return false;
if (!switch (item.getType()) {
case MUSHROOM_STEW, RABBIT_STEW, BEETROOT_SOUP, SUSPICIOUS_STEW -> true;
default -> false;
}) return false;
boolean changed = false;
if (!Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
item.setData(DataComponentTypes.MAX_STACK_SIZE, 16);
@@ -212,10 +353,19 @@ public final class Ingredients {
ItemMeta meta = item.getItemMeta();
FoodProperties food = item.getData(DataComponentTypes.FOOD);
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
if (meta.getPersistentDataContainer().has(new NamespacedKey("astrasoups", "combined_soup"), PersistentDataType.BYTE)
&& food != null && consumable != null) {
List<Component> lore = soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
if (!Objects.equals(meta.lore(), lore)) { meta.lore(lore); item.setItemMeta(meta); changed = true; }
if (meta.getPersistentDataContainer()
.has(
new NamespacedKey("astrasoups", "combined_soup"),
PersistentDataType.BYTE)
&& food != null
&& consumable != null) {
List<Component> lore =
soupLore(food.nutrition(), food.saturation(), consumable.consumeEffects());
if (!Objects.equals(meta.lore(), lore)) {
meta.lore(lore);
item.setItemMeta(meta);
changed = true;
}
}
return changed;
}