Initial commit: LoChat v1.0.0 with Gradient module

This commit is contained in:
Loki 2025-12-29 14:57:49 +01:00
commit 252b0a60db
86 changed files with 8922 additions and 0 deletions

View file

@ -0,0 +1,20 @@
package ru.lovar.gradientnick.util;
/**
* Константы плагина
*/
public final class Constants {
private Constants() {}
// Время
public static final long MILLIS_PER_SECOND = 1000L;
// GUI слоты
public static final int GUI_CONFIRM_SLOT = 11;
public static final int GUI_CANCEL_SLOT = 15;
public static final int GUI_PREVIEW_SLOT = 13;
// LuckPerms
public static final int LUCKPERMS_PREFIX_PRIORITY = 100;
}

View file

@ -0,0 +1,115 @@
package ru.lovar.gradientnick.util;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.entity.Player;
import ru.lovar.gradientnick.GradientNick;
import ru.lovar.gradientnick.config.ConfigManager;
import ru.lovar.gradientnick.data.PlayerData;
/**
* Утилита для обновления отображаемого имени игрока
*/
public final class DisplayNameUtil {
private static final LegacyComponentSerializer SERIALIZER = LegacyComponentSerializer.builder()
.character('&')
.hexCharacter('#')
.hexColors()
.build();
private DisplayNameUtil() {}
/**
* Обновляет displayName и playerListName игрока
*/
public static void updateDisplayName(GradientNick plugin, Player player, PlayerData data) {
ConfigManager cfg = plugin.getConfigManager();
// Определяем префикс: кастомный или групповой от LuckPerms
String prefix = null;
String prefixFormat = cfg.getPrefixFormat();
if (data.isPrefixEnabled() && data.hasPrefix()) {
// Кастомный префикс включён
prefix = data.getPrefix();
} else {
// Кастомный выключен — берём групповой из LuckPerms
String lpPrefix = plugin.getLuckPermsHook().getActivePrefix(player);
if (lpPrefix != null && !lpPrefix.isEmpty()) {
// Групповой префикс — применяем градиент на всё (префикс + ник)
String displayName = buildWithLuckPermsPrefix(
lpPrefix,
player.getName(),
data.isColorEnabled() ? data.getColors() : null,
cfg.isUseLegacyRgbFormat(),
cfg.isContinuousGradient()
);
var component = SERIALIZER.deserialize(displayName);
player.displayName(component);
player.playerListName(component);
return;
}
}
String displayName = GradientUtil.buildDisplayName(
prefix,
player.getName(),
data.isColorEnabled() ? data.getColors() : null,
cfg.isGradientOnPrefix(),
cfg.isContinuousGradient(),
prefixFormat,
cfg.isUseLegacyRgbFormat()
);
var component = SERIALIZER.deserialize(displayName);
player.displayName(component);
player.playerListName(component);
}
/**
* Строит displayName с префиксом от LuckPerms
* Если есть цвета и continuousGradient — применяем единый градиент на всё
*/
private static String buildWithLuckPermsPrefix(String lpPrefix, String nick,
java.util.List<String> colors,
boolean useLegacyFormat,
boolean continuousGradient) {
if (colors == null || colors.isEmpty()) {
// Нет цветов — просто префикс + ник
return lpPrefix + nick;
}
if (continuousGradient) {
// Единый градиент на префикс + ник
// Убираем цветовые коды из LP префикса чтобы применить наш градиент
String cleanPrefix = stripColors(lpPrefix);
String fullText = cleanPrefix + nick;
return GradientUtil.applyGradient(fullText, colors, useLegacyFormat);
} else {
// Градиент только на ник, префикс от LP оставляем
return lpPrefix + GradientUtil.applyGradient(nick, colors, useLegacyFormat);
}
}
/**
* Убирает цветовые коды из строки
*/
private static String stripColors(String text) {
if (text == null) return null;
// Убираем §x§R§R§G§G§B§B, §c, &c, &#RRGGBB форматы
return text.replaceAll("(?i)(§x(§[0-9a-f]){6}|§[0-9a-fk-or]|&[0-9a-fk-or]|&#[0-9a-f]{6})", "");
}
/**
* Строит цветной префикс для LuckPerms
*/
public static String buildColoredPrefix(GradientNick plugin, PlayerData data) {
if (!data.hasPrefix() || !data.isPrefixEnabled()) return null;
ConfigManager cfg = plugin.getConfigManager();
String prefix = cfg.getPrefixFormat().replace("{prefix}", data.getPrefix()).stripTrailing();
return (data.hasColors() && data.isColorEnabled() && cfg.isGradientOnPrefix())
? GradientUtil.applyGradient(prefix, data.getColors(), cfg.isUseLegacyRgbFormat())
: prefix;
}
}

View file

@ -0,0 +1,101 @@
package ru.lovar.gradientnick.util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.plugin.Plugin;
import java.util.concurrent.TimeUnit;
/**
* Утилита для работы с Folia и Paper 1.21.8+
* Обеспечивает потокобезопасность при работе с игроками
*/
public final class FoliaUtil {
private static final boolean IS_FOLIA;
static {
IS_FOLIA = checkFolia();
}
private FoliaUtil() {}
private static boolean checkFolia() {
try {
Class.forName("io.papermc.paper.threadedregions.RegionizedServer");
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
public static boolean isFolia() {
return IS_FOLIA;
}
/**
* Выполняет задачу в контексте сущности (потокобезопасно для Folia)
*/
public static void runEntityTask(Plugin plugin, Entity entity, Runnable task) {
if (IS_FOLIA) {
entity.getScheduler().run(plugin, scheduledTask -> task.run(), null);
} else {
Bukkit.getScheduler().runTask(plugin, task);
}
}
/**
* Выполняет задачу в контексте сущности с задержкой
*/
public static void runEntityTaskLater(Plugin plugin, Entity entity, Runnable task, long delayTicks) {
if (IS_FOLIA) {
entity.getScheduler().runDelayed(plugin, scheduledTask -> task.run(), null, delayTicks);
} else {
Bukkit.getScheduler().runTaskLater(plugin, task, delayTicks);
}
}
/**
* Выполняет задачу асинхронно
*/
public static void runAsync(Plugin plugin, Runnable task) {
if (IS_FOLIA) {
Bukkit.getAsyncScheduler().runNow(plugin, scheduledTask -> task.run());
} else {
Bukkit.getScheduler().runTaskAsynchronously(plugin, task);
}
}
/**
* Выполняет задачу асинхронно с задержкой
*/
public static void runAsyncLater(Plugin plugin, Runnable task, long delayMs) {
if (IS_FOLIA) {
Bukkit.getAsyncScheduler().runDelayed(plugin, scheduledTask -> task.run(), delayMs, TimeUnit.MILLISECONDS);
} else {
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, task, delayMs / 50);
}
}
/**
* Выполняет глобальную задачу (для Folia — на глобальном регионе)
*/
public static void runGlobalTask(Plugin plugin, Runnable task) {
if (IS_FOLIA) {
Bukkit.getGlobalRegionScheduler().run(plugin, scheduledTask -> task.run());
} else {
Bukkit.getScheduler().runTask(plugin, task);
}
}
/**
* Выполняет глобальную задачу с задержкой
*/
public static void runGlobalTaskLater(Plugin plugin, Runnable task, long delayTicks) {
if (IS_FOLIA) {
Bukkit.getGlobalRegionScheduler().runDelayed(plugin, scheduledTask -> task.run(), delayTicks);
} else {
Bukkit.getScheduler().runTaskLater(plugin, task, delayTicks);
}
}
}

View file

@ -0,0 +1,129 @@
package ru.lovar.gradientnick.util;
import java.awt.Color;
import java.util.List;
import java.util.regex.Pattern;
public class GradientUtil {
private static final Pattern HEX_PATTERN = Pattern.compile("^#[0-9A-Fa-f]{6}$");
public static boolean isValidHex(String color) {
return HEX_PATTERN.matcher(color).matches();
}
public static String applyGradient(String text, List<String> hexColors, boolean useLegacyFormat) {
if (text == null || text.isEmpty() || hexColors == null || hexColors.isEmpty()) {
return text;
}
char[] chars = text.toCharArray();
int length = chars.length;
if (length == 0) return text;
StringBuilder result = new StringBuilder();
if (hexColors.size() == 1) {
// Один цвет — весь текст одним цветом
String colorCode = formatHex(hexColors.get(0), useLegacyFormat);
for (char c : chars) {
result.append(colorCode).append(c);
}
} else {
// Градиент из нескольких цветов
Color[] colors = hexColors.stream()
.map(GradientUtil::parseHex)
.toArray(Color[]::new);
for (int i = 0; i < length; i++) {
Color interpolated = interpolateMultiColor(colors, (double) i / Math.max(1, length - 1));
String hex = String.format("#%02x%02x%02x",
interpolated.getRed(), interpolated.getGreen(), interpolated.getBlue());
result.append(formatHex(hex, useLegacyFormat)).append(chars[i]);
}
}
return result.toString();
}
private static Color interpolateMultiColor(Color[] colors, double ratio) {
if (colors.length == 1) return colors[0];
if (ratio <= 0) return colors[0];
if (ratio >= 1) return colors[colors.length - 1];
// Определяем между какими двумя цветами находимся
double scaledRatio = ratio * (colors.length - 1);
int index = (int) scaledRatio;
double localRatio = scaledRatio - index;
if (index >= colors.length - 1) {
return colors[colors.length - 1];
}
return interpolate(colors[index], colors[index + 1], localRatio);
}
private static Color interpolate(Color c1, Color c2, double ratio) {
int r = (int) (c1.getRed() + (c2.getRed() - c1.getRed()) * ratio);
int g = (int) (c1.getGreen() + (c2.getGreen() - c1.getGreen()) * ratio);
int b = (int) (c1.getBlue() + (c2.getBlue() - c1.getBlue()) * ratio);
return new Color(
Math.max(0, Math.min(255, r)),
Math.max(0, Math.min(255, g)),
Math.max(0, Math.min(255, b))
);
}
private static Color parseHex(String hex) {
hex = hex.replace("#", "");
return new Color(
Integer.parseInt(hex.substring(0, 2), 16),
Integer.parseInt(hex.substring(2, 4), 16),
Integer.parseInt(hex.substring(4, 6), 16)
);
}
private static String formatHex(String hex, boolean useLegacyFormat) {
hex = hex.replace("#", "").toLowerCase();
if (useLegacyFormat) {
// &#RRGGBB формат
return "&#" + hex;
} else {
// <#RRGGBB> формат для MiniMessage
return "<#" + hex + ">";
}
}
public static String buildDisplayName(String prefix, String nick, List<String> colors,
boolean gradientOnPrefix, boolean continuousGradient,
String prefixFormat, boolean useLegacyFormat) {
if (colors == null || colors.isEmpty()) {
// Нет цветов — возвращаем как есть
if (prefix != null && !prefix.isEmpty()) {
return prefixFormat.replace("{prefix}", prefix) + nick;
}
return nick;
}
if (prefix == null || prefix.isEmpty()) {
// Нет префикса — градиент только на ник
return applyGradient(nick, colors, useLegacyFormat);
}
if (continuousGradient && gradientOnPrefix) {
// Единый градиент на префикс + ник
String fullText = prefixFormat.replace("{prefix}", prefix) + nick;
return applyGradient(fullText, colors, useLegacyFormat);
} else if (gradientOnPrefix) {
// Градиент отдельно на префикс и ник
String coloredPrefix = applyGradient(prefixFormat.replace("{prefix}", prefix), colors, useLegacyFormat);
String coloredNick = applyGradient(nick, colors, useLegacyFormat);
return coloredPrefix + coloredNick;
} else {
// Градиент только на ник
String formattedPrefix = prefixFormat.replace("{prefix}", prefix);
return formattedPrefix + applyGradient(nick, colors, useLegacyFormat);
}
}
}