Simplify ingredient matching and clean up source and config comments
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
package online.astradev.soups;
|
||||
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.Levelled;
|
||||
@@ -20,8 +23,6 @@ import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.util.Transformation;
|
||||
import org.joml.Quaternionf;
|
||||
import org.joml.Vector3f;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.*;
|
||||
@@ -38,25 +39,46 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
private int ticks;
|
||||
|
||||
record Position(UUID world, int x, int y, int z) {
|
||||
static Position at(Block b) { return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ()); }
|
||||
static Position at(Block b) {
|
||||
return new Position(b.getWorld().getUID(), b.getX(), b.getY(), b.getZ());
|
||||
}
|
||||
|
||||
Block loadedBlock() {
|
||||
World w = Bukkit.getWorld(world);
|
||||
return w == null || !w.isChunkLoaded(x >> 4, z >> 4) ? null : w.getBlockAt(x, y, z);
|
||||
}
|
||||
String id() { return world + "," + x + "," + y + "," + z; }
|
||||
|
||||
String id() {
|
||||
return world + "," + x + "," + y + "," + z;
|
||||
}
|
||||
|
||||
static Position parse(String s) {
|
||||
String[] p = s.split(",");
|
||||
if (p.length != 4) throw new IllegalArgumentException("Invalid cauldron position " + s);
|
||||
return new Position(UUID.fromString(p[0]), Integer.parseInt(p[1]), Integer.parseInt(p[2]), Integer.parseInt(p[3]));
|
||||
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, int brewTicks, int servings, int capacity) {
|
||||
Pot { items = List.copyOf(items); }
|
||||
Pot(List<ItemStack> items, ItemStack soup) { this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1); }
|
||||
boolean brewing() { return brewTicks > 0; }
|
||||
Pot {
|
||||
items = List.copyOf(items);
|
||||
}
|
||||
|
||||
Pot(List<ItemStack> items, ItemStack soup) {
|
||||
this(items, soup, 0, soup == null ? 0 : 1, soup == null ? 0 : 1);
|
||||
}
|
||||
|
||||
boolean brewing() {
|
||||
return brewTicks > 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void onEnable() {
|
||||
@Override
|
||||
public void onEnable() {
|
||||
pots.clear();
|
||||
brewElapsed.clear();
|
||||
ticks = 0;
|
||||
@@ -66,55 +88,77 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
saveDefaultConfig();
|
||||
dataFile = new File(getDataFolder(), "cauldrons.yml");
|
||||
try {
|
||||
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using defaults.
|
||||
// Unlike loadConfiguration(), load() reports malformed YAML instead of silently using
|
||||
// defaults.
|
||||
new YamlConfiguration().load(new File(getDataFolder(), "config.yml"));
|
||||
ingredients = new Ingredients(this);
|
||||
loadPots();
|
||||
} catch (Exception e) {
|
||||
getLogger().log(Level.SEVERE, "Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений", e);
|
||||
getLogger()
|
||||
.log(
|
||||
Level.SEVERE,
|
||||
"Не удалось прочитать конфигурацию/котлы; данные оставлены без изменений",
|
||||
e);
|
||||
Bukkit.getPluginManager().disablePlugin(this);
|
||||
return;
|
||||
}
|
||||
Bukkit.getPluginManager().registerEvents(this, this);
|
||||
for (World world : Bukkit.getWorlds()) for (Entity entity : world.getEntities()) {
|
||||
if (isVisual(entity)) entity.remove();
|
||||
else if (entity instanceof Item item) normalizeEntity(item);
|
||||
}
|
||||
for (World world : Bukkit.getWorlds())
|
||||
for (Entity entity : world.getEntities()) {
|
||||
if (isVisual(entity)) entity.remove();
|
||||
else if (entity instanceof Item item) normalizeEntity(item);
|
||||
}
|
||||
for (Player p : Bukkit.getOnlinePlayers()) normalizeInventory(p.getInventory());
|
||||
Bukkit.getScheduler().runTaskTimer(this, this::refresh, 1, 1);
|
||||
getLogger().info("AstraSoups: загружено котлов: " + pots.size());
|
||||
}
|
||||
|
||||
@Override public void onDisable() {
|
||||
@Override
|
||||
public void onDisable() {
|
||||
for (Position pos : new ArrayList<>(visuals.keySet())) removeVisuals(pos);
|
||||
}
|
||||
|
||||
public Ingredients ingredients() { return ingredients; }
|
||||
public Ingredients ingredients() {
|
||||
return ingredients;
|
||||
}
|
||||
|
||||
private void loadPots() throws Exception {
|
||||
if (!dataFile.exists()) return;
|
||||
YamlConfiguration data = new YamlConfiguration();
|
||||
data.load(dataFile);
|
||||
ConfigurationSection section = data.getConfigurationSection("cauldrons");
|
||||
if (section == null && !data.getKeys(false).isEmpty()) throw new IllegalArgumentException("Invalid cauldrons.yml");
|
||||
if (section == null && !data.getKeys(false).isEmpty())
|
||||
throw new IllegalArgumentException("Invalid cauldrons.yml");
|
||||
if (section == null) return;
|
||||
for (String id : section.getKeys(false)) {
|
||||
ConfigurationSection c = Objects.requireNonNull(section.getConfigurationSection(id));
|
||||
List<ItemStack> items = new ArrayList<>();
|
||||
for (Object value : c.getList("items", List.of())) {
|
||||
if (!(value instanceof ItemStack item) || item.getAmount() != 1 || item.getType().isAir()) throw new IllegalArgumentException("Invalid ingredient at " + id);
|
||||
if (!(value instanceof ItemStack item)
|
||||
|| item.getAmount() != 1
|
||||
|| item.getType().isAir())
|
||||
throw new IllegalArgumentException("Invalid ingredient at " + id);
|
||||
items.add(item);
|
||||
}
|
||||
ItemStack soup = c.getItemStack("soup");
|
||||
int brewTicks = c.getInt("brew-ticks", 0);
|
||||
int servings = c.getInt("servings", soup == null ? 0 : 1);
|
||||
int capacity = c.getInt("capacity", soup == null ? 0 : Math.max(servings, getConfig().getInt("servings-per-brew", 4)));
|
||||
if (items.size() > 4 || brewTicks < 0 || brewTicks > 1200
|
||||
int capacity =
|
||||
c.getInt(
|
||||
"capacity",
|
||||
soup == null
|
||||
? 0
|
||||
: Math.max(
|
||||
servings, getConfig().getInt("servings-per-brew", 4)));
|
||||
if (items.size() > 4
|
||||
|| brewTicks < 0
|
||||
|| brewTicks > 1200
|
||||
|| (soup == null ? capacity != 0 : capacity < servings || capacity > 16)
|
||||
|| (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()))) {
|
||||
|| (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, capacity));
|
||||
@@ -124,7 +168,8 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
/** Save before transferring real items. A failed save rolls back the in-memory change. */
|
||||
private boolean change(Position pos, Pot next) {
|
||||
Pot old = pots.get(pos);
|
||||
if (next == null) pots.remove(pos); else pots.put(pos, next);
|
||||
if (next == null) pots.remove(pos);
|
||||
else pots.put(pos, next);
|
||||
try {
|
||||
YamlConfiguration data = new YamlConfiguration();
|
||||
data.createSection("cauldrons");
|
||||
@@ -132,20 +177,31 @@ 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);
|
||||
if (entry.getValue().soup != null) data.set(prefix + ".capacity", entry.getValue().capacity);
|
||||
if (entry.getValue().brewing())
|
||||
data.set(prefix + ".brew-ticks", entry.getValue().brewTicks);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".servings", entry.getValue().servings);
|
||||
if (entry.getValue().soup != null)
|
||||
data.set(prefix + ".capacity", entry.getValue().capacity);
|
||||
}
|
||||
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); }
|
||||
try {
|
||||
Files.move(
|
||||
temp,
|
||||
dataFile.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (AtomicMoveNotSupportedException e) {
|
||||
Files.move(temp, dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
// Keep the same visuals when starting a brew or taking a portion: no respawn flash.
|
||||
if (old == null || next == null || !old.items.equals(next.items)) removeVisuals(pos);
|
||||
brewElapsed.remove(pos);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
if (old == null) pots.remove(pos); else pots.put(pos, old);
|
||||
if (old == null) pots.remove(pos);
|
||||
else pots.put(pos, old);
|
||||
getLogger().log(Level.SEVERE, "Ошибка сохранения котла; действие отменено", e);
|
||||
return false;
|
||||
}
|
||||
@@ -153,7 +209,8 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void interact(PlayerInteractEvent event) {
|
||||
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null) return;
|
||||
if (event.getAction() != Action.RIGHT_CLICK_BLOCK || event.getClickedBlock() == null)
|
||||
return;
|
||||
Block block = event.getClickedBlock();
|
||||
Position pos = Position.at(block);
|
||||
Pot pot = pots.get(pos);
|
||||
@@ -161,10 +218,12 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
if (pot != null) event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
if (event.useInteractedBlock() == Event.Result.DENY || event.useItemInHand() == Event.Result.DENY) return;
|
||||
if (event.useInteractedBlock() == Event.Result.DENY
|
||||
|| event.useItemInHand() == Event.Result.DENY) return;
|
||||
if (!validBlock(block, pot)) return;
|
||||
Player player = event.getPlayer();
|
||||
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR) return;
|
||||
if (!player.hasPermission("astrasoups.use") || player.getGameMode() == GameMode.SPECTATOR)
|
||||
return;
|
||||
ItemStack held = player.getInventory().getItemInMainHand();
|
||||
boolean empty = held.getType().isAir();
|
||||
boolean bowl = held.getType() == Material.BOWL;
|
||||
@@ -172,37 +231,63 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
event.setCancelled(true);
|
||||
if (pot == null) {
|
||||
if (getConfig().getBoolean("require-full-water", true)
|
||||
&& block.getBlockData() instanceof Levelled level && level.getLevel() != level.getMaximumLevel()) {
|
||||
say(player, "Сначала наполните котёл водой доверху."); return;
|
||||
&& block.getBlockData() instanceof Levelled level
|
||||
&& level.getLevel() != level.getMaximumLevel()) {
|
||||
say(player, "Сначала наполните котёл водой доверху.");
|
||||
return;
|
||||
}
|
||||
pot = new Pot(List.of(), null);
|
||||
}
|
||||
if (pot.brewing()) {
|
||||
int remaining = Math.max(1, (pot.brewTicks - brewElapsed.getOrDefault(pos, 0) + 19) / 20);
|
||||
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, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ."); return; }
|
||||
if (!bowl) {
|
||||
say(player, "Суп готов. Порций: " + pot.servings + ". Возьмите его миской — ПКМ.");
|
||||
return;
|
||||
}
|
||||
ItemStack result = pot.soup.clone();
|
||||
int remaining = pot.servings - 1;
|
||||
if (!change(pos, remaining == 0 ? null : new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) { saveError(player); return; }
|
||||
if (!change(
|
||||
pos,
|
||||
remaining == 0
|
||||
? null
|
||||
: new Pot(List.of(), pot.soup, 0, remaining, pot.capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
takeOne(player);
|
||||
give(player, result);
|
||||
if (remaining == 0) block.setType(Material.CAULDRON);
|
||||
else { syncWater(block, pots.get(pos)); show(pos, pots.get(pos), block); }
|
||||
else {
|
||||
syncWater(block, pots.get(pos));
|
||||
show(pos, pots.get(pos), block);
|
||||
}
|
||||
block.getWorld().playSound(block.getLocation(), Sound.ITEM_BOTTLE_FILL, 0.8f, 0.7f);
|
||||
say(player, remaining == 0 ? "Последняя порция собрана. Котёл пуст." : "Осталось порций: " + remaining + ".");
|
||||
say(
|
||||
player,
|
||||
remaining == 0
|
||||
? "Последняя порция собрана. Котёл пуст."
|
||||
: "Осталось порций: " + remaining + ".");
|
||||
return;
|
||||
}
|
||||
boolean cook = pot.items.size() == 4 && (player.isSneaking() || !empty);
|
||||
if (cook) {
|
||||
String error = ingredients.rejection(pot.items);
|
||||
if (error != null) { say(player, error + " ПКМ пустой рукой возвращает последний ингредиент."); return; }
|
||||
if (error != null) {
|
||||
say(player, error + " ПКМ пустой рукой возвращает последний ингредиент.");
|
||||
return;
|
||||
}
|
||||
ItemStack soup = ingredients.brew(pot.items);
|
||||
int duration = (int) Math.round(getConfig().getDouble("brew-seconds", 4.0) * 20);
|
||||
int capacity = getConfig().getInt("servings-per-brew", 4);
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) { saveError(player); return; }
|
||||
if (!change(pos, new Pot(pot.items, soup, duration, capacity, capacity))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BREWING_STAND_BREW, 1, 1);
|
||||
say(player, "Варка началась! Дождитесь окончания водоворота.");
|
||||
@@ -212,20 +297,39 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
if (pot.items.isEmpty()) return;
|
||||
List<ItemStack> remaining = new ArrayList<>(pot.items);
|
||||
ItemStack last = remaining.removeLast();
|
||||
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) { saveError(player); return; }
|
||||
if (!change(pos, remaining.isEmpty() ? null : new Pot(remaining, null))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
give(player, last.clone());
|
||||
say(player, "Возвращён последний ингредиент. В котле: " + remaining.size() + "/4.");
|
||||
return;
|
||||
}
|
||||
if (pot.items.size() == 4) { say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке."); return; }
|
||||
if (ingredients.read(held) == null) { say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4."); return; }
|
||||
if (pot.items.size() == 4) {
|
||||
say(player, "Для варки: Shift+ПКМ или ПКМ с предметом в руке.");
|
||||
return;
|
||||
}
|
||||
if (ingredients.read(held) == null) {
|
||||
say(player, "Добавьте еду или зелье. В котле: " + pot.items.size() + "/4.");
|
||||
return;
|
||||
}
|
||||
List<ItemStack> items = new ArrayList<>(pot.items);
|
||||
items.add(held.asOne());
|
||||
if (!change(pos, new Pot(items, null))) { saveError(player); return; }
|
||||
if (!change(pos, new Pot(items, null))) {
|
||||
saveError(player);
|
||||
return;
|
||||
}
|
||||
takeOne(player);
|
||||
show(pos, pots.get(pos), block);
|
||||
block.getWorld().playSound(block.getLocation(), Sound.ENTITY_GENERIC_SPLASH, .3f, 1.6f);
|
||||
say(player, "Ингредиенты: " + items.size() + "/4." + (items.size() == 4 ? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний." : ""));
|
||||
say(
|
||||
player,
|
||||
"Ингредиенты: "
|
||||
+ items.size()
|
||||
+ "/4."
|
||||
+ (items.size() == 4
|
||||
? " Shift+ПКМ — сварить, ПКМ пустой рукой — забрать последний."
|
||||
: ""));
|
||||
}
|
||||
|
||||
private void takeOne(Player p) {
|
||||
@@ -233,132 +337,228 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
ItemStack held = p.getInventory().getItemInMainHand();
|
||||
p.getInventory().setItemInMainHand(held.getAmount() == 1 ? null : held.subtract(1));
|
||||
}
|
||||
|
||||
private void give(Player p, ItemStack item) {
|
||||
Ingredients.normalize(item);
|
||||
p.getInventory().addItem(item).values().forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
|
||||
p.getInventory()
|
||||
.addItem(item)
|
||||
.values()
|
||||
.forEach(left -> p.getWorld().dropItemNaturally(p.getLocation(), left));
|
||||
}
|
||||
|
||||
private void say(Player p, String text) {
|
||||
p.sendActionBar(Component.text(text, NamedTextColor.GOLD));
|
||||
}
|
||||
|
||||
private void saveError(Player p) {
|
||||
say(p, "Не удалось сохранить котёл. Обратитесь к администратору.");
|
||||
}
|
||||
private void say(Player p, String text) { p.sendActionBar(Component.text(text, NamedTextColor.GOLD)); }
|
||||
private void saveError(Player p) { say(p, "Не удалось сохранить котёл. Обратитесь к администратору."); }
|
||||
|
||||
private void refresh() {
|
||||
ticks++;
|
||||
for (Map.Entry<Position, Pot> entry : new ArrayList<>(pots.entrySet())) {
|
||||
Position pos = entry.getKey();
|
||||
Block block = pos.loadedBlock();
|
||||
if (block == null) { removeVisuals(pos); continue; }
|
||||
if (block == null) {
|
||||
removeVisuals(pos);
|
||||
continue;
|
||||
}
|
||||
if (!validBlock(block, entry.getValue())) {
|
||||
// External block editing: return raw ingredients only once, never resurrect a missing block.
|
||||
if (change(pos, null)) for (ItemStack item : entry.getValue().items) block.getWorld().dropItemNaturally(block.getLocation().add(.5, .5, .5), item.clone());
|
||||
// External block editing: return raw ingredients only once, never resurrect a
|
||||
// missing block.
|
||||
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, pot.capacity))) {
|
||||
if (elapsed >= pot.brewTicks
|
||||
&& (elapsed - pot.brewTicks) % 20 == 0
|
||||
&& change(
|
||||
pos, new Pot(List.of(), pot.soup, 0, pot.servings, pot.capacity))) {
|
||||
syncWater(block, pots.get(pos));
|
||||
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);
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (pot.soup != null && !pot.brewing()) syncWater(block, pot);
|
||||
List<Entity> entities = visuals.get(pos);
|
||||
if (entities == null || entities.stream().anyMatch(e -> !e.isValid())) {
|
||||
removeVisuals(pos); show(pos, entry.getValue(), block);
|
||||
removeVisuals(pos);
|
||||
show(pos, entry.getValue(), block);
|
||||
} else {
|
||||
for (int i = 0; i < entities.size(); i++) if (entities.get(i) instanceof ItemDisplay item && ticks % 2 == 0) {
|
||||
// Client interpolates the local transform; the entity itself never teleports.
|
||||
item.setInterpolationDelay(0);
|
||||
item.setTransformation(itemTransform(block, i, pot, 2));
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
Vector3f offset = item.getTransformation().getTranslation();
|
||||
double height = .375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld().spawnParticle(Particle.SPLASH,
|
||||
block.getLocation().add(.5 + offset.x, height + .01, .5 + offset.z),
|
||||
1, .015, 0, .015, 0);
|
||||
for (int i = 0; i < entities.size(); i++)
|
||||
if (entities.get(i) instanceof ItemDisplay item && ticks % 2 == 0) {
|
||||
// Client interpolates the local transform; the entity itself never
|
||||
// teleports.
|
||||
item.setInterpolationDelay(0);
|
||||
item.setTransformation(itemTransform(block, i, pot, 2));
|
||||
if (pot.brewing() && ticks % 5 == 0) {
|
||||
Vector3f offset = item.getTransformation().getTranslation();
|
||||
double height =
|
||||
.375 + .1875 * ((Levelled) block.getBlockData()).getLevel();
|
||||
block.getWorld()
|
||||
.spawnParticle(
|
||||
Particle.SPLASH,
|
||||
block.getLocation()
|
||||
.add(
|
||||
.5 + offset.x,
|
||||
height + .01,
|
||||
.5 + offset.z),
|
||||
1,
|
||||
.015,
|
||||
0,
|
||||
.015,
|
||||
0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (ticks % 20 == 0) for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
normalizeInventory(player.getInventory());
|
||||
normalizeInventory(player.getOpenInventory().getTopInventory());
|
||||
ItemStack cursor = player.getItemOnCursor();
|
||||
if (Ingredients.normalize(cursor)) player.setItemOnCursor(cursor);
|
||||
}
|
||||
if (ticks % 20 == 0)
|
||||
for (Player player : Bukkit.getOnlinePlayers()) {
|
||||
normalizeInventory(player.getInventory());
|
||||
normalizeInventory(player.getOpenInventory().getTopInventory());
|
||||
ItemStack cursor = player.getItemOnCursor();
|
||||
if (Ingredients.normalize(cursor)) player.setItemOnCursor(cursor);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validBlock(Block block, Pot pot) {
|
||||
return block.getType() == Material.WATER_CAULDRON
|
||||
|| (block.getType() == Material.CAULDRON && pot != null && pot.soup != null && !pot.brewing());
|
||||
|| (block.getType() == Material.CAULDRON
|
||||
&& pot != null
|
||||
&& pot.soup != null
|
||||
&& !pot.brewing());
|
||||
}
|
||||
|
||||
private void syncWater(Block block, Pot pot) {
|
||||
int level = CauldronAnimation.waterLevel(pot.servings, pot.capacity);
|
||||
if (level == 0) { if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON); }
|
||||
else {
|
||||
if (level == 0) {
|
||||
if (block.getType() != Material.CAULDRON) block.setType(Material.CAULDRON);
|
||||
} else {
|
||||
if (block.getType() != Material.WATER_CAULDRON) block.setType(Material.WATER_CAULDRON);
|
||||
Levelled water = (Levelled) block.getBlockData();
|
||||
if (water.getLevel() != level) { water.setLevel(level); block.setBlockData(water); }
|
||||
if (water.getLevel() != level) {
|
||||
water.setLevel(level);
|
||||
block.setBlockData(water);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Transformation itemTransform(Block block, int i, Pot pot, int ahead) {
|
||||
int waterLevel = block.getBlockData() instanceof Levelled l ? l.getLevel() : 3;
|
||||
CauldronAnimation.Offset frame = CauldronAnimation.frame(i, waterLevel, ticks + ahead,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0) + ahead, pot.brewTicks);
|
||||
return 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 + ahead) * .035f + i));
|
||||
CauldronAnimation.Offset frame =
|
||||
CauldronAnimation.frame(
|
||||
i,
|
||||
waterLevel,
|
||||
ticks + ahead,
|
||||
brewElapsed.getOrDefault(Position.at(block), 0) + ahead,
|
||||
pot.brewTicks);
|
||||
return 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 + ahead) * .035f + i));
|
||||
}
|
||||
|
||||
private Transformation liquidTransform(Pot pot) {
|
||||
return new Transformation(new Vector3f(-.075f, (float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity) + .005f - .5f, .375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)), new Vector3f(6, 3, 1), new Quaternionf());
|
||||
return new Transformation(
|
||||
new Vector3f(
|
||||
-.075f,
|
||||
(float) CauldronAnimation.liquidHeight(pot.servings, pot.capacity)
|
||||
+ .005f
|
||||
- .5f,
|
||||
.375f),
|
||||
new Quaternionf().rotationX((float) (-Math.PI / 2)),
|
||||
new Vector3f(6, 3, 1),
|
||||
new Quaternionf());
|
||||
}
|
||||
|
||||
private void show(Position pos, Pot pot, Block block) {
|
||||
if (visuals.containsKey(pos)) {
|
||||
if (pot.soup != null && !pot.brewing()) for (Entity entity : visuals.get(pos)) if (entity instanceof TextDisplay display) {
|
||||
display.setInterpolationDelay(0);
|
||||
display.setTransformation(liquidTransform(pot));
|
||||
}
|
||||
if (pot.soup != null && !pot.brewing())
|
||||
for (Entity entity : visuals.get(pos))
|
||||
if (entity instanceof TextDisplay display) {
|
||||
display.setInterpolationDelay(0);
|
||||
display.setTransformation(liquidTransform(pot));
|
||||
}
|
||||
return;
|
||||
}
|
||||
List<Entity> entities = new ArrayList<>();
|
||||
visuals.put(pos, entities);
|
||||
if (pot.soup != null && !pot.brewing()) {
|
||||
int rgb = pot.soup.getItemMeta().getPersistentDataContainer().getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
TextDisplay display = block.getWorld().spawn(block.getLocation().add(.5, .5, .5), TextDisplay.class, d -> {
|
||||
markVisual(d);
|
||||
// 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(liquidTransform(pot));
|
||||
d.setInterpolationDuration(5);
|
||||
d.setBrightness(new Display.Brightness(12, 12));
|
||||
d.setViewRange(.5f);
|
||||
});
|
||||
int rgb =
|
||||
pot.soup
|
||||
.getItemMeta()
|
||||
.getPersistentDataContainer()
|
||||
.getOrDefault(colorKey, PersistentDataType.INTEGER, 0xB77A36);
|
||||
TextDisplay display =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
TextDisplay.class,
|
||||
d -> {
|
||||
markVisual(d);
|
||||
// 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(liquidTransform(pot));
|
||||
d.setInterpolationDuration(5);
|
||||
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();
|
||||
int slot = i;
|
||||
ItemDisplay item = block.getWorld().spawn(block.getLocation().add(.5, .5, .5), ItemDisplay.class, e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.FIXED);
|
||||
e.setTransformation(itemTransform(block, slot, pot, 0));
|
||||
e.setInterpolationDuration(2);
|
||||
e.setViewRange(.5f);
|
||||
});
|
||||
entities.add(item);
|
||||
}
|
||||
} else
|
||||
for (int i = 0; i < pot.items.size(); i++) {
|
||||
ItemStack stack = pot.items.get(i).clone();
|
||||
int slot = i;
|
||||
ItemDisplay item =
|
||||
block.getWorld()
|
||||
.spawn(
|
||||
block.getLocation().add(.5, .5, .5),
|
||||
ItemDisplay.class,
|
||||
e -> {
|
||||
markVisual(e);
|
||||
e.setItemStack(stack);
|
||||
e.setItemDisplayTransform(
|
||||
ItemDisplay.ItemDisplayTransform.FIXED);
|
||||
e.setTransformation(itemTransform(block, slot, pot, 0));
|
||||
e.setInterpolationDuration(2);
|
||||
e.setViewRange(.5f);
|
||||
});
|
||||
entities.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
private void markVisual(Entity entity) {
|
||||
@@ -368,7 +568,11 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
entity.setInvulnerable(true);
|
||||
entity.setSilent(true);
|
||||
}
|
||||
private boolean isVisual(Entity entity) { return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE); }
|
||||
|
||||
private boolean isVisual(Entity entity) {
|
||||
return entity.getPersistentDataContainer().has(visualKey, PersistentDataType.BYTE);
|
||||
}
|
||||
|
||||
private void removeVisuals(Position pos) {
|
||||
List<Entity> entities = visuals.remove(pos);
|
||||
if (entities != null) entities.forEach(Entity::remove);
|
||||
@@ -376,79 +580,168 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void breakBlock(BlockBreakEvent e) {
|
||||
Position pos = Position.at(e.getBlock()); Pot pot = pots.get(pos);
|
||||
Position pos = Position.at(e.getBlock());
|
||||
Pot pot = pots.get(pos);
|
||||
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 && !pot.brewing()) say(e.getPlayer(), "Суп вылился из разбитого котла.");
|
||||
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 && !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); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void blockExplode(BlockExplodeEvent e) { e.blockList().removeIf(b -> pots.containsKey(Position.at(b))); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void piston(BlockPistonExtendEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void pistonRetract(BlockPistonRetractEvent e) { if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b)))) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void entityBlock(EntityChangeBlockEvent e) { if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void pickup(EntityPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void hopperPickup(InventoryPickupItemEvent e) { if (isVisual(e.getItem())) e.setCancelled(true); else normalizeEntity(e.getItem()); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void merge(ItemMergeEvent e) { if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void damage(EntityDamageEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void portal(EntityPortalEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void despawn(ItemDespawnEvent e) { if (isVisual(e.getEntity())) e.setCancelled(true); }
|
||||
@EventHandler public void unload(ChunkUnloadEvent e) {
|
||||
for (Position p : new ArrayList<>(visuals.keySet())) if (p.world.equals(e.getWorld().getUID()) && (p.x >> 4) == e.getChunk().getX() && (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
|
||||
public void cauldronChange(CauldronLevelChangeEvent e) {
|
||||
if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true);
|
||||
}
|
||||
@EventHandler public void entitiesLoad(EntitiesLoadEvent e) {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void explode(EntityExplodeEvent e) {
|
||||
e.blockList().removeIf(b -> pots.containsKey(Position.at(b)));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void blockExplode(BlockExplodeEvent e) {
|
||||
e.blockList().removeIf(b -> pots.containsKey(Position.at(b)));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void piston(BlockPistonExtendEvent e) {
|
||||
if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b))))
|
||||
e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void pistonRetract(BlockPistonRetractEvent e) {
|
||||
if (e.getBlocks().stream().anyMatch(b -> pots.containsKey(Position.at(b))))
|
||||
e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void entityBlock(EntityChangeBlockEvent e) {
|
||||
if (pots.containsKey(Position.at(e.getBlock()))) e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void pickup(EntityPickupItemEvent e) {
|
||||
if (isVisual(e.getItem())) e.setCancelled(true);
|
||||
else normalizeEntity(e.getItem());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void hopperPickup(InventoryPickupItemEvent e) {
|
||||
if (isVisual(e.getItem())) e.setCancelled(true);
|
||||
else normalizeEntity(e.getItem());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void merge(ItemMergeEvent e) {
|
||||
if (isVisual(e.getEntity()) || isVisual(e.getTarget())) e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void damage(EntityDamageEvent e) {
|
||||
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void portal(EntityPortalEvent e) {
|
||||
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void despawn(ItemDespawnEvent e) {
|
||||
if (isVisual(e.getEntity())) e.setCancelled(true);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void unload(ChunkUnloadEvent e) {
|
||||
for (Position p : new ArrayList<>(visuals.keySet()))
|
||||
if (p.world.equals(e.getWorld().getUID())
|
||||
&& (p.x >> 4) == e.getChunk().getX()
|
||||
&& (p.z >> 4) == e.getChunk().getZ()) removeVisuals(p);
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void entitiesLoad(EntitiesLoadEvent e) {
|
||||
for (Entity entity : e.getEntities()) {
|
||||
if (isVisual(entity) && visuals.values().stream().noneMatch(list -> list.contains(entity))) entity.remove();
|
||||
if (isVisual(entity)
|
||||
&& visuals.values().stream().noneMatch(list -> list.contains(entity)))
|
||||
entity.remove();
|
||||
else if (entity instanceof Item item && !isVisual(entity)) normalizeEntity(item);
|
||||
}
|
||||
}
|
||||
|
||||
private void normalizeEntity(Item item) { ItemStack stack = item.getItemStack(); if (Ingredients.normalize(stack)) item.setItemStack(stack); }
|
||||
private void normalizeEntity(Item item) {
|
||||
ItemStack stack = item.getItemStack();
|
||||
if (Ingredients.normalize(stack)) item.setItemStack(stack);
|
||||
}
|
||||
|
||||
private void normalizeInventory(Inventory inv) {
|
||||
for (int i = 0; i < inv.getSize(); i++) {
|
||||
ItemStack item = inv.getItem(i);
|
||||
if (Ingredients.normalize(item)) inv.setItem(i, item);
|
||||
}
|
||||
}
|
||||
@EventHandler public void join(PlayerJoinEvent e) { normalizeInventory(e.getPlayer().getInventory()); }
|
||||
|
||||
@EventHandler
|
||||
public void join(PlayerJoinEvent e) {
|
||||
normalizeInventory(e.getPlayer().getInventory());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void open(InventoryOpenEvent e) { normalizeInventory(e.getInventory()); normalizeInventory(e.getPlayer().getInventory()); }
|
||||
public void open(InventoryOpenEvent e) {
|
||||
normalizeInventory(e.getInventory());
|
||||
normalizeInventory(e.getPlayer().getInventory());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void spawn(ItemSpawnEvent e) { normalizeEntity(e.getEntity()); }
|
||||
public void spawn(ItemSpawnEvent e) {
|
||||
normalizeEntity(e.getEntity());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void craft(PrepareItemCraftEvent e) {
|
||||
ItemStack result = e.getInventory().getResult();
|
||||
if (Ingredients.normalize(result)) e.getInventory().setResult(result);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void crafted(CraftItemEvent e) {
|
||||
ItemStack result = e.getCurrentItem();
|
||||
if (Ingredients.normalize(result)) e.setCurrentItem(result);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void loot(LootGenerateEvent e) { e.getLoot().forEach(Ingredients::normalize); }
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void transfer(InventoryMoveItemEvent e) { ItemStack item = e.getItem(); if (Ingredients.normalize(item)) e.setItem(item); }
|
||||
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void loot(LootGenerateEvent e) {
|
||||
e.getLoot().forEach(Ingredients::normalize);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void transfer(InventoryMoveItemEvent e) {
|
||||
ItemStack item = e.getItem();
|
||||
if (Ingredients.normalize(item)) e.setItem(item);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (args.length == 0) {
|
||||
sender.sendMessage(Component.text("ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.", NamedTextColor.GOLD));
|
||||
sender.sendMessage(
|
||||
Component.text(
|
||||
"ПКМ с едой/зельем: добавить (4 предмета). ПКМ пустой рукой: забрать последний. Shift+ПКМ или ПКМ с предметом после заполнения: сварить. ПКМ миской по готовому супу: собрать.",
|
||||
NamedTextColor.GOLD));
|
||||
return true;
|
||||
}
|
||||
if (!sender.hasPermission("astrasoups.admin")) {
|
||||
sender.sendMessage("Недостаточно прав.");
|
||||
return true;
|
||||
}
|
||||
if (!sender.hasPermission("astrasoups.admin")) { sender.sendMessage("Недостаточно прав."); return true; }
|
||||
if (args[0].equalsIgnoreCase("reload") && args.length == 1) {
|
||||
String previous = getConfig().saveToString();
|
||||
try {
|
||||
@@ -459,21 +752,38 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
ingredients = next;
|
||||
sender.sendMessage("AstraSoups: конфигурация перезагружена.");
|
||||
} catch (Exception ex) {
|
||||
// Restore prior settings in memory; leave the invalid file for the administrator to fix.
|
||||
// Restore prior settings in memory; leave the invalid file for the administrator to
|
||||
// fix.
|
||||
restoreConfig(previous);
|
||||
sender.sendMessage("Ошибка конфигурации: " + ex.getMessage() + ". Продолжают действовать прежние настройки.");
|
||||
sender.sendMessage(
|
||||
"Ошибка конфигурации: "
|
||||
+ ex.getMessage()
|
||||
+ ". Продолжают действовать прежние настройки.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (args[0].equalsIgnoreCase("register") && args.length == 4 && sender instanceof Player player) {
|
||||
if (!args[1].matches("[a-z0-9_-]+")) { sender.sendMessage("ID: только a-z, 0-9, _ и -."); return true; }
|
||||
if (args[0].equalsIgnoreCase("register")
|
||||
&& args.length == 4
|
||||
&& sender instanceof Player player) {
|
||||
if (!args[1].matches("[a-z0-9_-]+")) {
|
||||
sender.sendMessage("ID: только a-z, 0-9, _ и -.");
|
||||
return true;
|
||||
}
|
||||
ItemStack item = player.getInventory().getItemInMainHand().asOne();
|
||||
if (item.getType().isAir()) { sender.sendMessage("Возьмите уникальную еду в основную руку."); return true; }
|
||||
if (item.getType().isAir()) {
|
||||
sender.sendMessage("Возьмите уникальную еду в основную руку.");
|
||||
return true;
|
||||
}
|
||||
String previous = getConfig().saveToString();
|
||||
try {
|
||||
int nutrition = Integer.parseInt(args[2]); float saturation = Float.parseFloat(args[3]);
|
||||
if (nutrition < 0 || nutrition > getConfig().getInt("max-nutrition", 1000) || saturation < 0 || !Float.isFinite(saturation)
|
||||
|| saturation > getConfig().getDouble("max-saturation", 1000)) throw new IllegalArgumentException();
|
||||
int nutrition = Integer.parseInt(args[2]);
|
||||
float saturation = Float.parseFloat(args[3]);
|
||||
if (nutrition < 0
|
||||
|| nutrition > getConfig().getInt("max-nutrition", 1000)
|
||||
|| saturation < 0
|
||||
|| !Float.isFinite(saturation)
|
||||
|| saturation > getConfig().getDouble("max-saturation", 1000))
|
||||
throw new IllegalArgumentException();
|
||||
String path = "custom-ingredients." + args[1];
|
||||
getConfig().set(path + ".item", item);
|
||||
getConfig().set(path + ".nutrition", nutrition);
|
||||
@@ -484,18 +794,31 @@ public final class AstraSoupsPlugin extends JavaPlugin implements Listener {
|
||||
sender.sendMessage("Зарегистрирован ингредиент: " + args[1]);
|
||||
} catch (Exception ex) {
|
||||
restoreConfig(previous);
|
||||
sender.sendMessage("Не удалось зарегистрировать: проверьте числа и конфигурацию. " + ex.getMessage());
|
||||
sender.sendMessage(
|
||||
"Не удалось зарегистрировать: проверьте числа и конфигурацию. "
|
||||
+ ex.getMessage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void restoreConfig(String yaml) {
|
||||
try { getConfig().loadFromString(yaml); }
|
||||
catch (org.bukkit.configuration.InvalidConfigurationException ex) { throw new IllegalStateException("Cannot restore validated config", ex); }
|
||||
try {
|
||||
getConfig().loadFromString(yaml);
|
||||
} catch (org.bukkit.configuration.InvalidConfigurationException ex) {
|
||||
throw new IllegalStateException("Cannot restore validated config", ex);
|
||||
}
|
||||
}
|
||||
@Override public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
|
||||
|
||||
@Override
|
||||
public List<String> onTabComplete(
|
||||
CommandSender sender, Command command, String alias, String[] args) {
|
||||
if (!sender.hasPermission("astrasoups.admin")) return List.of();
|
||||
return args.length == 1 ? List.of("reload", "register").stream().filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList() : List.of();
|
||||
return args.length == 1
|
||||
? List.of("reload", "register").stream()
|
||||
.filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT)))
|
||||
.toList()
|
||||
: List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package online.astradev.soups;
|
||||
/** 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) {
|
||||
@@ -11,8 +12,8 @@ public final class CauldronAnimation {
|
||||
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);
|
||||
return new Offset(
|
||||
.5 + Math.cos(angle) * radius, surface - .055 + bob, .5 + Math.sin(angle) * radius);
|
||||
}
|
||||
|
||||
public static double liquidHeight(int servings, int capacity) {
|
||||
|
||||
@@ -3,7 +3,6 @@ package online.astradev.soups;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/** Pure matching logic: incompatible selectors must occur in distinct slots. */
|
||||
public final class CombinationRules {
|
||||
private CombinationRules() {}
|
||||
|
||||
@@ -11,7 +10,8 @@ public final class CombinationRules {
|
||||
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) {
|
||||
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) {
|
||||
@@ -20,8 +20,9 @@ public final class CombinationRules {
|
||||
}
|
||||
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(i), pair.get(0)) && matches(ingredients.get(j), pair.get(1))) {
|
||||
if (i != j && matches(ingredients.get(j), pair.get(1))) {
|
||||
return "Несовместимые ингредиенты: " + String.join(" + ", pair);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,38 +3,39 @@ package online.astradev.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();
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -2,14 +2,18 @@ package online.astradev.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);
|
||||
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];
|
||||
}
|
||||
for (int i = 0; i < values.length; i++)
|
||||
while (level >= values[i]) {
|
||||
text.append(numerals[i]);
|
||||
level -= values[i];
|
||||
}
|
||||
return text.toString();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user