Add submerged whirlpool brewing, four servings and mixed soup colors
This commit is contained in:
@@ -34,6 +34,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
private Ingredients ingredients;
|
||||
private final Map<Position, Pot> pots = new LinkedHashMap<>();
|
||||
private final Map<Position, List<Entity>> visuals = new HashMap<>();
|
||||
private final Map<Position, Integer> brewElapsed = new HashMap<>();
|
||||
private File dataFile;
|
||||
private int ticks;
|
||||
|
||||
@@ -50,10 +51,16 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
|
||||
}
|
||||
}
|
||||
record Pot(List<ItemStack> items, ItemStack soup) { Pot { items = List.copyOf(items); } }
|
||||
record Pot(List<ItemStack> items, ItemStack soup, int brewTicks, int servings) {
|
||||
Pot { items = List.copyOf(items); }
|
||||
Pot(List<ItemStack> items, ItemStack soup) { this(items, soup, 0, soup == null ? 0 : 1); }
|
||||
boolean brewing() { return brewTicks > 0; }
|
||||
}
|
||||
|
||||
@Override public void onEnable() {
|
||||
pots.clear();
|
||||
brewElapsed.clear();
|
||||
ticks = 0;
|
||||
soupKey = new NamespacedKey(this, "combined_soup");
|
||||
colorKey = new NamespacedKey(this, "soup_color");
|
||||
visualKey = new NamespacedKey(this, "cauldron_visual");
|
||||
@@ -75,7 +82,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
else if (entity instanceof Item item) normalizeEntity(item);
|
||||
}
|
||||
for (Player p : Bukkit.getOnlinePlayers()) normalizeInventory(p.getInventory());
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 10);
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 1);
|
||||
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
||||
}
|
||||
|
||||
@@ -100,9 +107,16 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
items.add(item);
|
||||
}
|
||||
ItemStack soup = c.getItemStack("soup");
|
||||
if (items.size() > 4 || (soup != null && (!items.isEmpty() || soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||
|| (items.isEmpty() && soup == null)) throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||
pots.put(Position.parse(id), new Pot(items, soup));
|
||||
int brewTicks = c.getInt("brew-ticks", 0);
|
||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||
if (items.size() > 4 || brewTicks < 0 || brewTicks > 1200
|
||||
|| (soup == null ? servings != 0 : servings < 1 || servings > 16)
|
||||
|| (soup != null && (soup.getAmount() != 1 || !ingredients.isCombined(soup)))
|
||||
|| (brewTicks > 0 ? items.size() != 4 || soup == null
|
||||
: (soup != null ? !items.isEmpty() : items.isEmpty()))) {
|
||||
throw new IllegalArgumentException("Invalid cauldron at " + id);
|
||||
}
|
||||
pots.put(Position.parse(id), new Pot(items, soup, brewTicks, servings));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,12 +131,15 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
String prefix = "cauldrons." + entry.getKey().id();
|
||||
data.set(prefix + ".items", entry.getValue().items);
|
||||
data.set(prefix + ".soup", entry.getValue().soup);
|
||||
if (entry.getValue().brewing()) data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
||||
if (entry.getValue().soup != null) data.set(prefix + ".servings", entry.getValue().servings);
|
||||
}
|
||||
Path temp = dataFile.toPath().resolveSibling("cauldrons.yml.tmp");
|
||||
Files.writeString(temp, data.saveToString());
|
||||
try { Files.move(temp, dataFile.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); }
|
||||
catch (AtomicMoveNotSupportedException e) { Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
|
||||
removeVisuals(pos);
|
||||
brewElapsed.remove(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||
@@ -157,14 +174,22 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
pot = new Pot(List.of(), null);
|
||||
}
|
||||
if (pot.brewing()) {
|
||||
int remaining = Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
||||
say(player, "Суп варится… Осталось: " + remaining + " с.");
|
||||
return;
|
||||
}
|
||||
if (pot.soup != null) {
|
||||
if (!bowl) { say(player, "Суп готов. Возьмите его миской — ПКМ."); return; }
|
||||
if (!bowl) { say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return; }
|
||||
ItemStack result = pot.soup.clone();
|
||||
if (!change(pos, null)) { saveError(player); return; }
|
||||
int remaining = pot.servings - 1;
|
||||
if (!change(pos, remaining == 0 ? null : new Pot(List.of(), pot.soup, 0, remaining))) { saveError(player); return; }
|
||||
takeOne(player);
|
||||
give(player, result);
|
||||
block.setType(Material.CAULDRON);
|
||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||
else show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||
say(player, remaining == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + remaining + ".");
|
||||
return;
|
||||
}
|
||||
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
|
||||
@@ -172,11 +197,11 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
String error = ingredients.rejection(pot.items);
|
||||
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
|
||||
ItemStack soup = ingredients.brew(pot.items);
|
||||
if (!change(pos, new Pot(List.of(), soup))) { saveError(player); return; }
|
||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, getConfig().getInt("servings-per-brew", 4)))) { saveError(player); return; }
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
|
||||
say(player, "Суп готов! Соберите его миской.");
|
||||
say(player, "Варка началась! Дождитесь окончания водоворота.");
|
||||
return;
|
||||
}
|
||||
if (empty) {
|
||||
@@ -212,7 +237,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
|
||||
private void refresh() {
|
||||
ticks += 10;
|
||||
ticks++;
|
||||
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
||||
Position pos = entry.getKey();
|
||||
Block block = pos.loadedBlock();
|
||||
@@ -222,13 +247,32 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
if (change(pos, null)) for (ItemStack item : entry.getValue().items) block.getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item.clone());
|
||||
continue;
|
||||
}
|
||||
Pot pot = entry.getValue();
|
||||
if (pot.brewing()) {
|
||||
int elapsed = brewElapsed.merge(pos, 1, Integer::sum);
|
||||
// On a save failure keep ingredients locked and retry once per second.
|
||||
if (elapsed >= pot.brewTicks && (elapsed - pot.brewTicks) % 20 == 0
|
||||
&& change(pos, new Pot(List.of(), pot.soup, 0, pot.servings))) {
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BUBBLE_COLUMN_BUBBLE_POP, .8f, 1.2f);
|
||||
block.getWorld().spawnParticle(Particle.CLOUD, block.getLocation().add(.5, 1.05, .5), 12, .2, .12, .2, .01);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
List<Entity> entities = visuals.get(pos);
|
||||
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
||||
removeVisuals(pos); show(pos, entry.getValue(), block);
|
||||
} else {
|
||||
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof Item item) {
|
||||
item.teleport(itemLocation(block, i));
|
||||
Location location = itemLocation(block, i, pot);
|
||||
item.teleport(location);
|
||||
item.setVelocity(new Vector());
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
double height = .375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld().spawnParticle(Particle.SPLASH,
|
||||
new Location(block.getWorld(), location.getX(), block.getY() + height + .01, location.getZ()),
|
||||
1, .015, 0, .015, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,31 +284,38 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
private Location itemLocation(Block block, int i) {
|
||||
double[][] offsets = {{.32, .32}, {.68, .32}, {.32, .68}, {.68, .68}};
|
||||
private Location itemLocation(Block block, int i, Pot pot) {
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
double height = .375 + .1875 * waterLevel;
|
||||
return block.getLocation().add(offsets[i][0], height - .11 + Math.sin(ticks * .06 + i) * .025, offsets[i][1]);
|
||||
CauldronAnimation.Offset frame = CauldronAnimation.frame(i, waterLevel, ticks,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0), pot.brewTicks);
|
||||
return block.getLocation().add(frame.x(), frame.y(), frame.z());
|
||||
}
|
||||
|
||||
private void show(Position pos, Pot pot, Block block) {
|
||||
if (visuals.containsKey(pos)) return;
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
visuals.put(pos, entities);
|
||||
if (pot.soup != null) {
|
||||
if (pot.soup != null && !pot.brewing()) {
|
||||
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
BlockDisplay display = block.getWorld().spawn(block.getLocation().add(.125, .375 + .1875 * waterLevel + .005, .125), BlockDisplay.class, d -> {
|
||||
TextDisplay display = block.getWorld().spawn(block.getLocation().add(.5, .375 + .1875 * waterLevel + .005, .5), TextDisplay.class, d -> {
|
||||
markVisual(d);
|
||||
d.setBlock(surface(rgb).createBlockData());
|
||||
d.setTransformation(new Transformation(new Vector3f(), new Quaternionf(), new Vector3f(.75f, .012f, .75f), new Quaternionf()));
|
||||
// One default-font space: native background spans 5x10 pixels at 0.025 blocks/pixel.
|
||||
// Center the rectangle, scale to 0.75x0.75 and face upwards inside the cauldron.
|
||||
d.text(Component.text(" ").font(net.kyori.adventure.key.Key.key("minecraft:default")));
|
||||
d.setDefaultBackground(false);
|
||||
d.setBackgroundColor(Color.fromARGB(0xFF000000 | rgb));
|
||||
d.setShadowed(false);
|
||||
d.setSeeThrough(false);
|
||||
d.setTransformation(new Transformation(new Vector3f(-.075f, 0, .375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)), new Vector3f(6, 3, 1), new Quaternionf()));
|
||||
d.setBrightness(new Display.Brightness(12, 12));
|
||||
d.setViewRange(.5f);
|
||||
});
|
||||
entities.add(display);
|
||||
} else for (int i = 0; i < pot.items.size(); i++) {
|
||||
ItemStack stack = pot.items.get(i).clone();
|
||||
Item item = block.getWorld().spawn(itemLocation(block, i), Item.class, e -> {
|
||||
Item item = block.getWorld().spawn(itemLocation(block, i, pot), Item.class, e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setCanPlayerPickup(false);
|
||||
@@ -277,23 +328,6 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
private Material surface(int rgb) {
|
||||
Material[] materials = {Material.ORANGE_TERRACOTTA, Material.YELLOW_TERRACOTTA, Material.RED_TERRACOTTA,
|
||||
Material.BROWN_TERRACOTTA, Material.GREEN_TERRACOTTA, Material.LIME_TERRACOTTA,
|
||||
Material.BLUE_TERRACOTTA, Material.CYAN_TERRACOTTA, Material.PURPLE_TERRACOTTA,
|
||||
Material.PINK_TERRACOTTA, Material.WHITE_TERRACOTTA, Material.BLACK_TERRACOTTA};
|
||||
int[] colors = {0xA15325, 0xBA8523, 0x8E3C2E, 0x4D3323, 0x4C532A, 0x677535,
|
||||
0x4A3B5B, 0x565B5B, 0x764656, 0xA14E4E, 0xD1B2A1, 0x251610};
|
||||
Color wanted = Color.fromRGB(rgb);
|
||||
int best = 0, distance = Integer.MAX_VALUE;
|
||||
for (int i = 0; i < colors.length; i++) {
|
||||
Color candidate = Color.fromRGB(colors[i]);
|
||||
int r = candidate.getRed() - wanted.getRed(), g = candidate.getGreen() - wanted.getGreen(), b = candidate.getBlue() - wanted.getBlue();
|
||||
int d = r * r + g * g + b * b;
|
||||
if (d < distance) { best = i; distance = d; }
|
||||
}
|
||||
return materials[best];
|
||||
}
|
||||
private void markVisual(Entity entity) {
|
||||
entity.getPersistentDataContainer().set(visualKey, PersistentDataType.BYTE, (byte) 1);
|
||||
entity.setPersistent(false);
|
||||
@@ -313,7 +347,7 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
if (pot == null) return;
|
||||
if (!change(pos, null)) { e.setCancelled(true); saveError(e.getPlayer()); return; }
|
||||
for (ItemStack item : pot.items) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(.5, .5, .5), item.clone());
|
||||
if (pot.soup != null) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||
if (pot.soup != null && !pot.brewing()) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void cauldronChange(CauldronLevelChangeEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
/** Coordinates relative to a cauldron; item renderers add their own bob above the entity origin. */
|
||||
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 progress = duration > 0 ? Math.clamp((double) elapsed / duration, 0, 1) : 0;
|
||||
double eased = progress * progress * (3 - 2 * progress);
|
||||
double[] phases = {-3 * Math.PI / 4, -Math.PI / 4, 3 * Math.PI / 4, Math.PI / 4};
|
||||
double angle = phases[slot] + 2 * Math.PI * (2 * progress + 2 * progress * progress);
|
||||
double radius = .255 * (1 - .85 * eased);
|
||||
double surface = .375 + .1875 * waterLevel;
|
||||
double bob = Math.sin(tick * .06 + slot) * .01 * (1 - progress);
|
||||
return new Offset(.5 + Math.cos(angle) * radius,
|
||||
Math.max(.26, surface - .28 - .14 * eased + bob), .5 + Math.sin(angle) * radius);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.Material;
|
||||
|
||||
/** Representative food colors; potion contents and custom food overrides are read separately. */
|
||||
final class IngredientColors {
|
||||
private IngredientColors() {}
|
||||
static Color food(Material material, Color 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.asRGB();
|
||||
};
|
||||
return Color.fromRGB(rgb);
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ 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) {}
|
||||
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;
|
||||
@@ -36,6 +36,12 @@ public final class Ingredients {
|
||||
|
||||
public Ingredients(AstraSoupsPlugin plugin) {
|
||||
this.plugin = plugin;
|
||||
double seconds = plugin.getConfig().getDouble("brew-seconds", 4.0);
|
||||
if (!Double.isFinite(seconds) || seconds < .5 || seconds > 60) {
|
||||
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));
|
||||
blocked = plugin.getConfig().getStringList("blocked-ingredients");
|
||||
for (Object value : plugin.getConfig().getList("incompatible", List.of())) {
|
||||
@@ -68,7 +74,8 @@ public final class Ingredients {
|
||||
effects.add(new PotionEffect(type, duration, amplifier));
|
||||
}
|
||||
normalize(sample);
|
||||
custom.add(new Custom(id, sample.asOne(), nutrition, saturation, List.copyOf(effects)));
|
||||
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 {
|
||||
@@ -95,7 +102,8 @@ public final class Ingredients {
|
||||
List<ConsumeEffect> effects = new ArrayList<>();
|
||||
Consumable consumable = item.getData(DataComponentTypes.CONSUMABLE);
|
||||
if (consumable != null) effects.addAll(consumable.consumeEffects());
|
||||
Color color = defaultColor;
|
||||
Color color = IngredientColors.food(item.getType(), defaultColor);
|
||||
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));
|
||||
color = pm.computeEffectiveColor();
|
||||
@@ -111,6 +119,7 @@ public final class Ingredients {
|
||||
saturation = match.saturation;
|
||||
tags.add("custom:" + match.id.toLowerCase(Locale.ROOT));
|
||||
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);
|
||||
@@ -150,24 +159,9 @@ public final class Ingredients {
|
||||
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", "Комбинированный суп"), NamedTextColor.GOLD).decoration(TextDecoration.ITALIC, false));
|
||||
List<Component> lore = new ArrayList<>();
|
||||
lore.add(line("Голод: +" + nutrition, NamedTextColor.YELLOW));
|
||||
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(" " + (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));
|
||||
}
|
||||
meta.lore(lore);
|
||||
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());
|
||||
soup.setItemMeta(meta);
|
||||
@@ -178,7 +172,27 @@ public final class Ingredients {
|
||||
return soup;
|
||||
}
|
||||
|
||||
private Component line(String s, NamedTextColor color) { return Component.text(s, color).decoration(TextDecoration.ITALIC, false); }
|
||||
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));
|
||||
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));
|
||||
}
|
||||
} 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 Color color(List<Ingredient> ingredients) {
|
||||
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),
|
||||
@@ -189,11 +203,20 @@ public final class Ingredients {
|
||||
}
|
||||
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; }
|
||||
&& !Objects.equals(item.getData(DataComponentTypes.MAX_STACK_SIZE), 16)) {
|
||||
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);
|
||||
return true;
|
||||
changed = true;
|
||||
}
|
||||
return false;
|
||||
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; }
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package online.astracraft.soups;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
# Ровно четыре предмета, по одной единице каждого. Повторы разрешены.
|
||||
# Одна варка дает одну миску: питание и эффекты не размножаются.
|
||||
# Одна варка даёт четыре порции; каждая получает питание и эффекты всего состава.
|
||||
servings-per-brew: 4
|
||||
require-full-water: true
|
||||
# Варка с водоворотом, в секундах (0.5–60). 20 тиков = 1 секунда.
|
||||
brew-seconds: 4.0
|
||||
soup-name: 'Комбинированный суп'
|
||||
# Цвет поверхности — ближайший оттенок терракоты без ресурспака.
|
||||
# Резервный цвет неизвестной еды. Известные продукты имеют собственные цвета,
|
||||
# зелья передают свой RGB. Поверхность супа показывает среднее RGB четырёх ингредиентов.
|
||||
default-color: '#B77A36'
|
||||
# Ограничения предотвращают переполнение при многократной варке супов из супов.
|
||||
max-nutrition: 1000
|
||||
@@ -20,4 +24,5 @@ incompatible: []
|
||||
# nutrition — единицы голода (2 = один значок), saturation — очки насыщения.
|
||||
# Необязательные effects: [{type: 'minecraft:strength', duration: 3600, amplifier: 1}]
|
||||
# duration в тиках; amplifier: 0 = I, 1 = II. Эффекты добавляются к исходным.
|
||||
# Необязательный color: '#D45B37' задаёт цвет уникальной еды для смешивания.
|
||||
custom-ingredients: {}
|
||||
|
||||
Reference in New Issue
Block a user