diff --git a/README.md b/README.md
index 2270f1e..8bb97df 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# ChunkVisualizer
-**ChunkVisualizer** is a lightweight and powerful Minecraft plugin that allows players to visualize chunk boundaries in real-time without using the debug menu (`F3 + G`).
+**ChunkVisualizer** is a lightweight and powerful Minecraft plugin that allows players to visualize chunk boundaries in real-time without using the debug menu (`F3 + G`).
It is a perfect companion for **Towny** or other land-claim systems, as it allows players to see specific chunk edges clearly without cluttering the screen with a global grid.
@@ -9,23 +9,38 @@ It is a perfect companion for **Towny** or other land-claim systems, as it allow
## 🎥 Demonstration
### 1. Dynamic Chunk Tracking
-The visualization automatically follows the player when crossing chunk borders, ensuring seamless territory control.
+The visualization automatically follows the player when crossing chunk borders, ensuring seamless territory control. It works with both highlight modes (corner blocks and walls) and is refreshed after teleports and respawns.
+
### 2. Full GUI Customization
Use the `/cv settings` command to open an intuitive interface that allows you to:
-* **Toggle** visibility with a single click.
+* **Toggle** visibility with a single click (`Shift + Click` in Blocks mode).
+* **Switch highlight mode** between corner blocks and chunk walls.
* **Adjust height** of the boundary blocks relative to your current position.
-* **Change materials** used for the visualization.
-* **Reset** all settings to server defaults.
+* **Change materials** used for the visualization: click any block in your inventory while the menu is open.
+* **Change outline color** of the corner blocks (red, orange, yellow, green, cyan, blue, purple or white).
+* **Customize walls** (requires `chunkvisualizer.use.display`):
+ * pick the wall color,
+ * adjust opacity from 5% to 100%,
+ * toggle the glow effect.
+* **Reset the block material** to the server default with a right click on the material slot.
-
+All settings are saved per player and restored on the next join.
+
+
+
### 3. Non-Intrusive "Ghost" Blocks
-Built using modern packets and **Display Entities**, these blocks have no collision. They **do not interfere with gameplay**: you can mine ores or interact with items directly through the visualization.
+Built using modern packets and **Display Entities**, these blocks have no collision. They **do not interfere with gameplay**: you can mine ores or interact with items directly through the visualization. Everything is client-side and visible only to the player who enabled it.
+
+
+### 4. Two Highlight Modes
+* **Corner blocks**: ghost blocks at the four chunk corners with a colored outline. Height, material and outline color are configurable.
+* **Walls**: semi-transparent colored walls along the chunk edges (`text_display`), with adjustable opacity and an optional glow effect. Requires the `chunkvisualizer.use.display` permission.
---
@@ -33,19 +48,47 @@ Built using modern packets and **Display Entities**, these blocks have no collis
| Command | Description | Permission |
| :--- | :--- | :--- |
-| `/cv` | Main command (Help menu) | `chunkvisualizer.use` |
-| `/cv settings` | Open the customization GUI | `chunkvisualizer.use` |
-| `/cv reload` | Reload configuration files | `chunkvisualizer.admin` |
+| `/cv` | Main command (help) | — |
+| `/cv settings` | Open the customization GUI | `chunkvisualizer.settings` |
+| — | Use the **Walls** highlight mode in the GUI | `chunkvisualizer.use.display` |
+| `/cv reload` | Reload `config.yml` and `messages.yml` | `chunkvisualizer.admin` |
+
+> Grant `chunkvisualizer.settings` to your players (e.g. via LuckPerms) so they can open the menu. Without `chunkvisualizer.use.display`, players are always shown the corner blocks mode.
---
-## ⚙️ Installation
-1. Download the latest `.jar` file from the [Releases](https://github.com/SawaPlayGO/ChunkVisualizer/releases/tag/v0.1) page.
-2. Place it into your server's `plugins` folder.
-3. Restart the server or load it using a plugin manager.
+## 🔧 Configuration
+
+Defaults for new players are set in `plugins/ChunkVisualizer/config.yml`:
+
+| Option | Description |
+| :--- | :--- |
+| `default-enabled` | Visualization on/off on first join |
+| `default-mode` | `BLOCKS` or `WALLS` |
+| `default-height` | Height of the corner blocks relative to the player |
+| `default-material` | Material of the corner blocks (any valid Bukkit `Material`) |
+| `default-block-glow-color` | Outline color of the corner blocks |
+| `default-wall-color` | Wall color (`RED`, `ORANGE`, `YELLOW`, `GREEN`, `CYAN`, `BLUE`, `PURPLE`, `WHITE`) |
+| `default-wall-alpha` | Wall opacity in percent (5-100) |
+| `default-wall-glow` | Wall glow on/off |
+
+Changes to these defaults affect only players who join for the first time. Existing players keep their own saved settings.
+
+All texts live in `messages.yml`. Use `/cv reload` to apply config and message changes.
+
+Player settings are stored in SQLite (`plugins/ChunkVisualizer/data.db`) and are tied to the player name.
+
+---
+
+## 📋 Requirements
+* Paper 1.21+
+* Java 21
+* No external dependencies: PacketEvents is bundled inside the jar.
---
-## 📝 Roadmap
-* [ ] Persistent user settings storage (Database/Flatfile support).
-* [ ] Color support for boundary block outlines/highlights.
+## ⚙️ Installation
+1. Download the latest `.jar` file from the [Releases](https://github.com/SawaPlayGO/ChunkVisualizer/releases) page.
+2. Place it into your server's `plugins` folder.
+3. Restart the server or load it using a plugin manager.
+4. Give your players the `chunkvisualizer.settings` permission.
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 36ac536..f6440e4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -6,7 +6,7 @@
ru.sawaplago
ChunkVisualizer
- 0.3.1
+ 0.4
jar
ChunkVisualizer
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/listeners/ChunkChangeListener.java b/src/main/java/ru/sawaplago/chunkVisualizer/listeners/ChunkChangeListener.java
index f2f27df..38c7067 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/listeners/ChunkChangeListener.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/listeners/ChunkChangeListener.java
@@ -2,34 +2,76 @@
import java.util.HashMap;
import java.util.Map;
+import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
+import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.event.player.PlayerRespawnEvent;
+import org.bukkit.event.player.PlayerTeleportEvent;
+import ru.sawaplago.chunkVisualizer.ChunkVisualizer;
import ru.sawaplago.chunkVisualizer.events.PlayerChunkChangeEvent;
import ru.sawaplago.chunkVisualizer.objects.Chunk;
public class ChunkChangeListener implements Listener {
- private final Map lastChunk = new HashMap<>();
+ /** Задержка, чтобы игрок реально оказался на новой позиции/в новом мире. */
+ private static final long REFRESH_DELAY_TICKS = 2L;
- @EventHandler
+ private final Map lastChunk = new HashMap<>();
+
+ @EventHandler(ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent e) {
Player p = e.getPlayer();
- Chunk currentChunk = Chunk.getCurrentChunk(p);
- Chunk previousChunk = lastChunk.get(p);
+ if (e.getTo() == null) return;
+
+ // Внутри события игрок ещё стоит в точке "from", поэтому берём "to"
+ Chunk currentChunk = Chunk.getCurrentChunk(e.getTo());
+ Chunk previousChunk = lastChunk.get(p.getUniqueId());
if (previousChunk == null) {
- lastChunk.put(p, currentChunk);
+ lastChunk.put(p.getUniqueId(), currentChunk);
return;
}
if (!currentChunk
.getStartChunkPositionVector()
.equals(previousChunk.getStartChunkPositionVector())) {
- PlayerChunkChangeEvent event =
- new PlayerChunkChangeEvent(p, previousChunk, currentChunk);
- Bukkit.getPluginManager().callEvent(event);
- lastChunk.put(p, currentChunk);
+ lastChunk.put(p.getUniqueId(), currentChunk);
+ Bukkit.getPluginManager()
+ .callEvent(new PlayerChunkChangeEvent(p, previousChunk, currentChunk));
}
}
+
+ // PlayerTeleportEvent НЕ приходит в хендлер PlayerMoveEvent (у него свой HandlerList)
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onTeleport(PlayerTeleportEvent e) {
+ scheduleRefresh(e.getPlayer());
+ }
+
+ // После респавна клиент очищает сущности
+ @EventHandler
+ public void onRespawn(PlayerRespawnEvent e) {
+ scheduleRefresh(e.getPlayer());
+ }
+
+ @EventHandler
+ public void onQuit(PlayerQuitEvent e) {
+ lastChunk.remove(e.getPlayer().getUniqueId());
+ }
+
+ private void scheduleRefresh(Player player) {
+ Bukkit.getScheduler()
+ .runTaskLater(
+ ChunkVisualizer.getInstance(),
+ () -> {
+ if (!player.isOnline()) return;
+ Chunk chunk = Chunk.getCurrentChunk(player);
+ lastChunk.put(player.getUniqueId(), chunk);
+ Bukkit.getPluginManager()
+ .callEvent(new PlayerChunkChangeEvent(player, chunk, chunk));
+ },
+ REFRESH_DELAY_TICKS);
+ }
}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/listeners/PlayerChunkChangeListener.java b/src/main/java/ru/sawaplago/chunkVisualizer/listeners/PlayerChunkChangeListener.java
index 5c86297..42e4448 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/listeners/PlayerChunkChangeListener.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/listeners/PlayerChunkChangeListener.java
@@ -9,18 +9,29 @@
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
+import org.bukkit.scheduler.BukkitRunnable;
+import org.bukkit.scheduler.BukkitTask;
+import org.bukkit.util.Vector;
import ru.sawaplago.chunkVisualizer.ChunkVisualizer;
import ru.sawaplago.chunkVisualizer.events.PlayerChunkChangeEvent;
import ru.sawaplago.chunkVisualizer.managers.DatabaseManager;
import ru.sawaplago.chunkVisualizer.managers.UserSettingsManager;
import ru.sawaplago.chunkVisualizer.managers.data.UserSettings;
import ru.sawaplago.chunkVisualizer.objects.Chunk;
+import ru.sawaplago.chunkVisualizer.visuals.ChunkHighlighter;
import ru.sawaplago.chunkVisualizer.visuals.ItemDisplayChunkHighlighter;
+import ru.sawaplago.chunkVisualizer.visuals.TextDisplayWallHighlighter;
public class PlayerChunkChangeListener implements Listener {
+ /** Через сколько тиков показываем подсветку, даже если чанк так и не отправлен. */
+ private static final int MAX_WAIT_TICKS = 100;
+
+ private static final long CHECK_PERIOD_TICKS = 2L;
+
private final DatabaseManager databaseManager;
private final UserSettingsManager userSettingsManager;
- private final Map activeHighlighters = new HashMap<>();
+ private final Map activeHighlighters = new HashMap<>();
+ private final Map pendingTasks = new HashMap<>();
public PlayerChunkChangeListener() {
this.databaseManager = ChunkVisualizer.getInstance().getDatabaseManager();
@@ -30,34 +41,13 @@ public PlayerChunkChangeListener() {
@EventHandler
public void onPlayerChunkChange(PlayerChunkChangeEvent event) {
Player p = event.getPlayer();
- Chunk chunkTo = event.getToChunk();
-
- ItemDisplayChunkHighlighter oldHighlighter = activeHighlighters.remove(p.getUniqueId());
- if (oldHighlighter != null) {
- oldHighlighter.despawn();
- }
-
- UserSettings userSettings = userSettingsManager.getSettings(p.getUniqueId());
-
- if (userSettings == null || !userSettings.isEnabled()) {
- return;
- }
-
- if (!userSettings.isEnabled()) {
- return;
- }
-
- ItemDisplayChunkHighlighter newHighlighter =
- new ItemDisplayChunkHighlighter(
- chunkTo, p, userSettings.getHeights(), userSettings.getMaterial());
- newHighlighter.show();
- activeHighlighters.put(p.getUniqueId(), newHighlighter);
+ removeHighlighter(p);
+ showHighlighter(p, event.getToChunk());
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
- Chunk currentChunk = Chunk.getCurrentChunk(player);
Optional userSettingsOpt = databaseManager.getUserSettings(player.getName());
@@ -65,33 +55,117 @@ public void onPlayerJoin(PlayerJoinEvent event) {
if (userSettingsOpt.isEmpty()) {
userSettings = UserSettings.defaultSettings(player.getName());
databaseManager.saveOrCreateUserSettings(userSettings);
- userSettingsManager.setSettings(player.getUniqueId(), userSettings);
} else {
userSettings = userSettingsOpt.get();
- userSettingsManager.setSettings(player.getUniqueId(), userSettings);
}
+ userSettingsManager.setSettings(player.getUniqueId(), userSettings);
- if (!userSettings.isEnabled()) {
- return;
- }
-
- ItemDisplayChunkHighlighter newHighlighter =
- new ItemDisplayChunkHighlighter(
- currentChunk,
- player,
- userSettings.getHeights(),
- userSettings.getMaterial());
- newHighlighter.show();
- activeHighlighters.put(player.getUniqueId(), newHighlighter);
+ showHighlighter(player, Chunk.getCurrentChunk(player));
}
@EventHandler
public void onQuit(PlayerQuitEvent event) {
- ItemDisplayChunkHighlighter highlighter =
- activeHighlighters.remove(event.getPlayer().getUniqueId());
+ cancelPending(event.getPlayer());
+ removeHighlighter(event.getPlayer());
userSettingsManager.removeSettings(event.getPlayer().getUniqueId());
- if (highlighter != null) {
- highlighter.despawn();
+ }
+
+ private void removeHighlighter(Player player) {
+ cancelPending(player);
+ ChunkHighlighter old = activeHighlighters.remove(player.getUniqueId());
+ if (old != null) {
+ old.despawn();
+ }
+ }
+
+ private void cancelPending(Player player) {
+ BukkitTask task = pendingTasks.remove(player.getUniqueId());
+ if (task != null) {
+ task.cancel();
+ }
+ }
+
+ private void showHighlighter(Player player, Chunk chunk) {
+ cancelPending(player);
+
+ UserSettings settings = userSettingsManager.getSettings(player.getUniqueId());
+ if (settings == null || !settings.isEnabled()) {
+ return;
}
+
+ // Клиент выбрасывает спавн сущностей в незагруженном чанке,
+ // поэтому ждём, пока сервер отправит игроку этот чанк.
+ if (isChunkReady(player, chunk)) {
+ spawnHighlighter(player, chunk);
+ return;
+ }
+
+ UUID uuid = player.getUniqueId();
+ BukkitRunnable runnable =
+ new BukkitRunnable() {
+ private int waited = 0;
+
+ @Override
+ public void run() {
+ waited += (int) CHECK_PERIOD_TICKS;
+
+ if (!player.isOnline()) {
+ pendingTasks.remove(uuid);
+ cancel();
+ return;
+ }
+
+ if (isChunkReady(player, chunk) || waited >= MAX_WAIT_TICKS) {
+ pendingTasks.remove(uuid);
+ cancel();
+ spawnHighlighter(player, chunk);
+ }
+ }
+ };
+ pendingTasks.put(
+ uuid,
+ runnable.runTaskTimer(
+ ChunkVisualizer.getInstance(), CHECK_PERIOD_TICKS, CHECK_PERIOD_TICKS));
+ }
+
+ private boolean isChunkReady(Player player, Chunk chunk) {
+ Vector start = chunk.getStartChunkPositionVector();
+ int chunkX = start.getBlockX() >> 4;
+ int chunkZ = start.getBlockZ() >> 4;
+ return player.isChunkSent(org.bukkit.Chunk.getChunkKey(chunkX, chunkZ));
+ }
+
+ private void spawnHighlighter(Player player, Chunk chunk) {
+ // Настройки могли поменяться, пока ждали
+ UserSettings settings = userSettingsManager.getSettings(player.getUniqueId());
+ if (settings == null || !settings.isEnabled()) {
+ return;
+ }
+
+ ChunkHighlighter old = activeHighlighters.remove(player.getUniqueId());
+ if (old != null) {
+ old.despawn();
+ }
+
+ ChunkHighlighter highlighter =
+ switch (settings.getEffectiveMode(player)) {
+ case WALLS ->
+ new TextDisplayWallHighlighter(
+ chunk,
+ player,
+ settings.getWallColor(),
+ settings.getWallAlpha(),
+ settings.isWallGlow());
+ case BLOCKS ->
+ new ItemDisplayChunkHighlighter(
+ chunk,
+ player,
+ settings.getHeights(),
+ settings.getMaterial(),
+ settings.resolveBlockGlowColor());
+ };
+
+ highlighter.show();
+ activeHighlighters.put(player.getUniqueId(), highlighter);
}
}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/managers/ConfigManager.java b/src/main/java/ru/sawaplago/chunkVisualizer/managers/ConfigManager.java
index 21d01ec..002ddc7 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/managers/ConfigManager.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/managers/ConfigManager.java
@@ -5,6 +5,8 @@
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
+import ru.sawaplago.chunkVisualizer.objects.HighlightMode;
+import ru.sawaplago.chunkVisualizer.objects.WallColor;
public class ConfigManager {
private final JavaPlugin plugin;
@@ -32,6 +34,31 @@ public boolean isDefaultIsEnabled() {
public Material getDefaultMaterial() {
String materialName = config.getString("settings.default-material", "GLOWSTONE");
- return Material.getMaterial(materialName);
+ Material material = Material.getMaterial(materialName);
+ return material != null ? material : Material.GLOWSTONE;
+ }
+
+ public WallColor getDefaultBlockGlowColor() {
+ return WallColor.fromString(
+ config.getString("settings.default-block-glow-color", "WHITE"), WallColor.WHITE);
+ }
+
+ public HighlightMode getDefaultMode() {
+ return HighlightMode.fromString(
+ config.getString("settings.default-mode", "BLOCKS"), HighlightMode.BLOCKS);
+ }
+
+ public WallColor getDefaultWallColor() {
+ return WallColor.fromString(
+ config.getString("settings.default-wall-color", "RED"), WallColor.RED);
+ }
+
+ public int getDefaultWallAlpha() {
+ int alpha = config.getInt("settings.default-wall-alpha", 50);
+ return Math.max(WallColor.MIN_ALPHA, Math.min(WallColor.MAX_ALPHA, alpha));
+ }
+
+ public boolean isDefaultWallGlow() {
+ return config.getBoolean("settings.default-wall-glow", false);
}
}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/managers/DatabaseManager.java b/src/main/java/ru/sawaplago/chunkVisualizer/managers/DatabaseManager.java
index 39889ba..0827418 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/managers/DatabaseManager.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/managers/DatabaseManager.java
@@ -3,7 +3,9 @@
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.File;
+import java.util.HashSet;
import java.util.Optional;
+import java.util.Set;
import org.bukkit.Material;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.argument.ArgumentFactory;
@@ -21,6 +23,7 @@ public DatabaseManager() {
this.dataSource = new HikariDataSource(config);
this.jdbi = Jdbi.create(dataSource);
this.createTables();
+ this.migrateTables();
this.registerMappers();
}
@@ -30,8 +33,8 @@ public void saveOrCreateUserSettings(UserSettings settings) {
handle.createUpdate(
"""
INSERT OR REPLACE INTO user_settings
- (playerName, heights, isEnabled, material)
- VALUES (:playerName, :heights, :enabled, :material)
+ (playerName, heights, isEnabled, material, blockGlowColor, mode, wallColor, wallAlpha, wallGlow)
+ VALUES (:playerName, :heights, :enabled, :material, :blockGlowColor, :mode, :wallColor, :wallAlpha, :wallGlow)
""")
.bindBean(settings)
.execute());
@@ -42,7 +45,8 @@ public Optional getUserSettings(String playerName) {
handle ->
handle.createQuery(
"""
- SELECT playerName, heights, isEnabled as enabled, material
+ SELECT playerName, heights, isEnabled as enabled, material,
+ blockGlowColor, mode, wallColor, wallAlpha, wallGlow
FROM user_settings
WHERE playerName = :playerName
""")
@@ -69,6 +73,7 @@ private void registerMappers() {
? Optional.of(
(pos, stmt, ___) -> stmt.setString(pos, m.name()))
: Optional.empty());
+ // HighlightMode и WallColor (enum) Jdbi сохраняет/читает по имени сам
}
private void createTables() {
@@ -77,14 +82,52 @@ private void createTables() {
handle.execute(
"""
CREATE TABLE IF NOT EXISTS user_settings (
- playerName TEXT PRIMARY KEY,
- heights INTEGER,
- isEnabled BOOLEAN,
- material TEXT
+ playerName TEXT PRIMARY KEY,
+ heights INTEGER,
+ isEnabled BOOLEAN,
+ material TEXT,
+ blockGlowColor TEXT DEFAULT 'WHITE',
+ mode TEXT DEFAULT 'BLOCKS',
+ wallColor TEXT DEFAULT 'RED',
+ wallAlpha INTEGER DEFAULT 50,
+ wallGlow BOOLEAN DEFAULT 0
)
"""));
}
+ /** Добавляет новые колонки в таблицу, созданную старыми версиями плагина. */
+ private void migrateTables() {
+ jdbi.useHandle(
+ handle -> {
+ Set columns =
+ new HashSet<>(
+ handle.createQuery(
+ "SELECT name FROM pragma_table_info('user_settings')")
+ .mapTo(String.class)
+ .list());
+ if (!columns.contains("mode")) {
+ handle.execute(
+ "ALTER TABLE user_settings ADD COLUMN mode TEXT DEFAULT 'BLOCKS'");
+ }
+ if (!columns.contains("wallColor")) {
+ handle.execute(
+ "ALTER TABLE user_settings ADD COLUMN wallColor TEXT DEFAULT 'RED'");
+ }
+ if (!columns.contains("wallAlpha")) {
+ handle.execute(
+ "ALTER TABLE user_settings ADD COLUMN wallAlpha INTEGER DEFAULT 50");
+ }
+ if (!columns.contains("wallGlow")) {
+ handle.execute(
+ "ALTER TABLE user_settings ADD COLUMN wallGlow BOOLEAN DEFAULT 0");
+ }
+ if (!columns.contains("blockGlowColor")) {
+ handle.execute(
+ "ALTER TABLE user_settings ADD COLUMN blockGlowColor TEXT DEFAULT 'WHITE'");
+ }
+ });
+ }
+
private static String getAndCreateDirectory(String fileName) {
File dataFolder = new File("plugins/ChunkVisualizer");
if (!dataFolder.exists()) {
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/managers/MessageManager.java b/src/main/java/ru/sawaplago/chunkVisualizer/managers/MessageManager.java
index 52fb7ba..97b9dab 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/managers/MessageManager.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/managers/MessageManager.java
@@ -1,6 +1,9 @@
package ru.sawaplago.chunkVisualizer.managers;
import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
@@ -33,6 +36,14 @@ public void reload() {
configFile = new File(plugin.getDataFolder(), "messages.yml");
}
config = YamlConfiguration.loadConfiguration(configFile);
+
+ // Новые ключи из jar подхватываются, даже если messages.yml на сервере старый
+ InputStream defaults = plugin.getResource("messages.yml");
+ if (defaults != null) {
+ config.setDefaults(
+ YamlConfiguration.loadConfiguration(
+ new InputStreamReader(defaults, StandardCharsets.UTF_8)));
+ }
}
public FileConfiguration getConfig() {
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/managers/data/UserSettings.java b/src/main/java/ru/sawaplago/chunkVisualizer/managers/data/UserSettings.java
index d15e3af..e5aee2b 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/managers/data/UserSettings.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/managers/data/UserSettings.java
@@ -4,8 +4,11 @@
import lombok.Data;
import lombok.NoArgsConstructor;
import org.bukkit.Material;
+import org.bukkit.entity.Player;
import ru.sawaplago.chunkVisualizer.ChunkVisualizer;
import ru.sawaplago.chunkVisualizer.managers.ConfigManager;
+import ru.sawaplago.chunkVisualizer.objects.HighlightMode;
+import ru.sawaplago.chunkVisualizer.objects.WallColor;
@Data
@NoArgsConstructor
@@ -15,6 +18,11 @@ public class UserSettings {
private int heights;
private boolean isEnabled;
private Material material;
+ private WallColor blockGlowColor;
+ private HighlightMode mode;
+ private WallColor wallColor;
+ private int wallAlpha;
+ private boolean wallGlow;
public static UserSettings defaultSettings(String playerName) {
ConfigManager configManager = ChunkVisualizer.getInstance().getConfigManager();
@@ -22,6 +30,22 @@ public static UserSettings defaultSettings(String playerName) {
playerName,
configManager.getDefaultHeight(),
configManager.isDefaultIsEnabled(),
- configManager.getDefaultMaterial());
+ configManager.getDefaultMaterial(),
+ configManager.getDefaultBlockGlowColor(),
+ configManager.getDefaultMode(),
+ configManager.getDefaultWallColor(),
+ configManager.getDefaultWallAlpha(),
+ configManager.isDefaultWallGlow());
+ }
+
+ /** Режим с учётом прав: без chunkvisualizer.use.display всегда BLOCKS. */
+ public HighlightMode getEffectiveMode(Player player) {
+ HighlightMode current = mode == null ? HighlightMode.BLOCKS : mode;
+ return current.canUse(player) ? current : HighlightMode.BLOCKS;
+ }
+
+ /** Цвет обводки блоков; если в БД null - белый (стандартный). */
+ public WallColor resolveBlockGlowColor() {
+ return blockGlowColor != null ? blockGlowColor : WallColor.WHITE;
}
}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/menus/SettingsMenu.java b/src/main/java/ru/sawaplago/chunkVisualizer/menus/SettingsMenu.java
index 11ab30e..05e060f 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/menus/SettingsMenu.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/menus/SettingsMenu.java
@@ -25,12 +25,26 @@
import ru.sawaplago.chunkVisualizer.managers.UserSettingsManager;
import ru.sawaplago.chunkVisualizer.managers.data.UserSettings;
import ru.sawaplago.chunkVisualizer.objects.Chunk;
+import ru.sawaplago.chunkVisualizer.objects.HighlightMode;
+import ru.sawaplago.chunkVisualizer.objects.WallColor;
public class SettingsMenu implements Listener {
private static final int SIZE = 27;
- private static final int HEIGHT_SLOT = 12; // x=3, y=1
- private static final int BLOCK_SLOT = 14; // x=5, y=1
+
+ // Общий слот: левый нижний угол
+ private static final int MODE_SLOT = 18;
+
+ // Режим BLOCKS
+ private static final int HEIGHT_SLOT = 11; // высота + toggle
+ private static final int BLOCK_SLOT = 13; // материал
+ private static final int BLOCK_GLOW_COLOR_SLOT = 15; // цвет обводки
+
+ // Режим WALLS (четыре кнопки через одну)
+ private static final int WALLS_STATUS_SLOT = 10; // toggle
+ private static final int WALLS_COLOR_SLOT = 12; // цвет
+ private static final int WALLS_ALPHA_SLOT = 14; // прозрачность
+ private static final int WALLS_GLOW_SLOT = 16; // свечение
private final MessageManager messageManager;
private final UserSettingsManager userSettingsManager;
@@ -44,7 +58,6 @@ public SettingsMenu() {
this.messageManager = ChunkVisualizer.getInstance().getMessageManager();
}
- /** Холдер нужен, чтобы listener отличал это меню от остальных инвентарей. */
private static class MenuHolder implements InventoryHolder {
private Inventory inventory;
@@ -107,32 +120,130 @@ private void handleTopClick(InventoryClickEvent event, Player player, Inventory
int slot = event.getSlot();
ClickType click = event.getClick();
- if (slot == HEIGHT_SLOT) {
- UserSettings current = userSettingsManager.getSettings(player.getUniqueId());
- if (current == null) return;
+ UserSettings current = userSettingsManager.getSettings(player.getUniqueId());
+ if (current == null) return;
+
+ HighlightMode mode = current.getEffectiveMode(player);
- if (click.isShiftClick()) {
+ boolean changed;
+ if (slot == MODE_SLOT) {
+ changed = handleModeClick(player, click, current, mode);
+ } else if (mode == HighlightMode.BLOCKS) {
+ changed = handleBlocksClick(player, slot, click, current);
+ } else {
+ changed = handleWallsClick(player, slot, click, current);
+ }
+
+ if (changed) {
+ saveAndRefresh(player, current, inventory);
+ }
+ }
+
+ private boolean handleModeClick(
+ Player player, ClickType click, UserSettings current, HighlightMode mode) {
+ if (!click.isLeftClick() && !click.isRightClick()) return false;
+
+ HighlightMode target = mode.next();
+ if (!target.canUse(player)) {
+ player.sendMessage(messageManager.getMessage("no-permission-display"));
+ player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_NO, 1, 1);
+ return false;
+ }
+
+ current.setMode(target);
+ player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_PLING, 1, 1.5f);
+ return true;
+ }
+
+ private boolean handleBlocksClick(
+ Player player, int slot, ClickType click, UserSettings current) {
+ boolean leftOrRight = click.isLeftClick() || click.isRightClick();
+
+ switch (slot) {
+ case HEIGHT_SLOT -> {
+ if (!leftOrRight) return false;
+ if (click.isShiftClick()) {
+ current.setEnabled(!current.isEnabled());
+ player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_HAT, 1, 1);
+ } else if (click.isLeftClick()) {
+ current.setHeights(current.getHeights() - 1);
+ player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
+ } else {
+ current.setHeights(current.getHeights() + 1);
+ player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
+ }
+ return true;
+ }
+ case BLOCK_SLOT -> {
+ if (!click.isRightClick() || click.isShiftClick()) return false;
+ current.setMaterial(configManager.getDefaultMaterial());
+ player.playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1, 1);
+ return true;
+ }
+ case BLOCK_GLOW_COLOR_SLOT -> {
+ WallColor color = current.resolveBlockGlowColor();
+ if (click.isLeftClick()) {
+ current.setBlockGlowColor(color.next());
+ } else if (click.isRightClick()) {
+ current.setBlockGlowColor(color.previous());
+ } else {
+ return false;
+ }
+ player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
+ return true;
+ }
+ default -> {
+ return false;
+ }
+ }
+ }
+
+ private boolean handleWallsClick(
+ Player player, int slot, ClickType click, UserSettings current) {
+ boolean leftOrRight = click.isLeftClick() || click.isRightClick();
+
+ switch (slot) {
+ case WALLS_STATUS_SLOT -> {
+ if (!leftOrRight) return false;
current.setEnabled(!current.isEnabled());
player.playSound(player.getLocation(), Sound.BLOCK_NOTE_BLOCK_HAT, 1, 1);
- } else if (click.isLeftClick()) {
- current.setHeights(current.getHeights() - 1);
+ return true;
+ }
+ case WALLS_COLOR_SLOT -> {
+ WallColor color =
+ current.getWallColor() != null ? current.getWallColor() : WallColor.RED;
+ if (click.isLeftClick()) {
+ current.setWallColor(color.next());
+ } else if (click.isRightClick()) {
+ current.setWallColor(color.previous());
+ } else {
+ return false;
+ }
player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
- } else if (click.isRightClick()) {
- current.setHeights(current.getHeights() + 1);
+ return true;
+ }
+ case WALLS_ALPHA_SLOT -> {
+ int alpha = current.getWallAlpha();
+ if (click.isLeftClick()) {
+ alpha = Math.max(WallColor.MIN_ALPHA, alpha - WallColor.ALPHA_STEP);
+ } else if (click.isRightClick()) {
+ alpha = Math.min(WallColor.MAX_ALPHA, alpha + WallColor.ALPHA_STEP);
+ } else {
+ return false;
+ }
+ current.setWallAlpha(alpha);
player.playSound(player.getLocation(), Sound.UI_BUTTON_CLICK, 1, 1);
- } else {
- return;
+ return true;
+ }
+ case WALLS_GLOW_SLOT -> {
+ if (!leftOrRight) return false;
+ current.setWallGlow(!current.isWallGlow());
+ player.playSound(player.getLocation(), Sound.BLOCK_AMETHYST_BLOCK_CHIME, 1, 1);
+ return true;
+ }
+ default -> {
+ return false;
}
-
- saveAndRefresh(player, current, inventory);
- } else if (slot == BLOCK_SLOT && click.isRightClick() && !click.isShiftClick()) {
- UserSettings current = userSettingsManager.getSettings(player.getUniqueId());
- if (current == null) return;
-
- current.setMaterial(configManager.getDefaultMaterial());
- player.playSound(player.getLocation(), Sound.ENTITY_ITEM_PICKUP, 1, 1);
-
- saveAndRefresh(player, current, inventory);
}
}
@@ -145,6 +256,9 @@ private void handleBottomClick(InventoryClickEvent event, Player player, Invento
UserSettings current = userSettingsManager.getSettings(player.getUniqueId());
if (current == null) return;
+ // Материал имеет смысл менять только в режиме блоков
+ if (current.getEffectiveMode(player) != HighlightMode.BLOCKS) return;
+
current.setMaterial(clicked.getType());
player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_PLACE, 1, 1);
@@ -155,13 +269,14 @@ private void saveAndRefresh(Player player, UserSettings settings, Inventory inve
databaseManager.saveOrCreateUserSettings(settings);
userSettingsManager.setSettings(player.getUniqueId(), settings);
+ // Сразу перерисовываем подсветку, не дожидаясь смены чанка
refreshVisuals(player);
render(player, inventory);
}
private void render(Player player, Inventory inventory) {
- UserSettings userSettings = userSettingsManager.getSettings(player.getUniqueId());
- if (userSettings == null) return;
+ UserSettings settings = userSettingsManager.getSettings(player.getUniqueId());
+ if (settings == null) return;
ItemStack glass = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
ItemMeta glassMeta = glass.getItemMeta();
@@ -173,42 +288,49 @@ private void render(Player player, Inventory inventory) {
inventory.setItem(i, glass);
}
- int currentHeight = userSettings.getHeights();
- boolean isEnabled = userSettings.isEnabled();
- Material currentMaterial = userSettings.getMaterial();
+ HighlightMode mode = settings.getEffectiveMode(player);
+ boolean isEnabled = settings.isEnabled();
String statusText =
isEnabled
? messageManager.getMessage("gui.status-on")
: messageManager.getMessage("gui.status-off");
- String heightName =
- messageManager
- .getMessage("gui.height-name")
- .replace("%height%", String.valueOf(currentHeight));
-
- ItemStack heightItem =
- new ItemStack(
- isEnabled
- ? Material.LIME_GLAZED_TERRACOTTA
- : Material.RED_GLAZED_TERRACOTTA);
- ItemMeta hMeta = heightItem.getItemMeta();
- if (hMeta != null) {
- hMeta.setDisplayName(heightName);
- hMeta.setLore(
- List.of(
- messageManager.getMessage("gui.lore-status") + statusText,
- "",
- messageManager.getMessage("gui.lore-lmb"),
- messageManager.getMessage("gui.lore-rmb"),
- messageManager.getMessage("gui.lore-shift")));
- heightItem.setItemMeta(hMeta);
- }
- inventory.setItem(HEIGHT_SLOT, heightItem);
- ItemStack blockItem = new ItemStack(currentMaterial);
- ItemMeta bMeta = blockItem.getItemMeta();
- if (bMeta != null) {
- bMeta.setDisplayName(messageManager.getMessage("gui.block-name"));
+ // --- Режим (левый нижний угол) ---
+ String modeText =
+ messageManager.getMessage(
+ mode == HighlightMode.WALLS ? "gui.mode-walls" : "gui.mode-blocks");
+ inventory.setItem(
+ MODE_SLOT,
+ createItem(
+ mode == HighlightMode.WALLS ? Material.GLASS : Material.GLOWSTONE,
+ messageManager.getMessage("gui.mode-name").replace("%mode%", modeText),
+ List.of(
+ messageManager.getMessage("gui.lore-mode-current") + modeText,
+ "",
+ messageManager.getMessage("gui.lore-mode-switch"))));
+
+ Material statusIcon =
+ isEnabled ? Material.LIME_GLAZED_TERRACOTTA : Material.RED_GLAZED_TERRACOTTA;
+
+ if (mode == HighlightMode.BLOCKS) {
+ // --- Высота + toggle ---
+ inventory.setItem(
+ HEIGHT_SLOT,
+ createItem(
+ statusIcon,
+ messageManager
+ .getMessage("gui.height-name")
+ .replace("%height%", String.valueOf(settings.getHeights())),
+ List.of(
+ messageManager.getMessage("gui.lore-status") + statusText,
+ "",
+ messageManager.getMessage("gui.lore-lmb"),
+ messageManager.getMessage("gui.lore-rmb"),
+ messageManager.getMessage("gui.lore-shift"))));
+
+ // --- Материал ---
+ Material currentMaterial = settings.getMaterial();
List lore =
messageManager.getConfig().getStringList("gui.block-lore").stream()
.map(
@@ -218,10 +340,98 @@ private void render(Player player, Inventory inventory) {
s.replace(
"%material%", currentMaterial.name())))
.toList();
- bMeta.setLore(lore);
- blockItem.setItemMeta(bMeta);
+ inventory.setItem(
+ BLOCK_SLOT,
+ createItem(currentMaterial, messageManager.getMessage("gui.block-name"), lore));
+
+ // --- Цвет обводки блоков ---
+ WallColor glowColor = settings.resolveBlockGlowColor();
+ String glowColorText = messageManager.getMessage("gui.colors." + glowColor.name());
+ inventory.setItem(
+ BLOCK_GLOW_COLOR_SLOT,
+ createItem(
+ glowColor.getIcon(),
+ messageManager
+ .getMessage("gui.block-glow-name")
+ .replace("%color%", glowColorText),
+ List.of(
+ messageManager.getMessage("gui.lore-color-current")
+ + glowColorText,
+ "",
+ messageManager.getMessage("gui.lore-color-next"),
+ messageManager.getMessage("gui.lore-color-prev"))));
+ } else {
+ // --- Toggle ---
+ inventory.setItem(
+ WALLS_STATUS_SLOT,
+ createItem(
+ statusIcon,
+ messageManager
+ .getMessage("gui.status-name")
+ .replace("%status%", statusText),
+ List.of(
+ messageManager.getMessage("gui.lore-status") + statusText,
+ "",
+ messageManager.getMessage("gui.lore-toggle"))));
+
+ // --- Цвет ---
+ WallColor color =
+ settings.getWallColor() != null ? settings.getWallColor() : WallColor.RED;
+ String colorText = messageManager.getMessage("gui.colors." + color.name());
+ inventory.setItem(
+ WALLS_COLOR_SLOT,
+ createItem(
+ color.getIcon(),
+ messageManager
+ .getMessage("gui.color-name")
+ .replace("%color%", colorText),
+ List.of(
+ messageManager.getMessage("gui.lore-color-current") + colorText,
+ "",
+ messageManager.getMessage("gui.lore-color-next"),
+ messageManager.getMessage("gui.lore-color-prev"))));
+
+ // --- Прозрачность ---
+ inventory.setItem(
+ WALLS_ALPHA_SLOT,
+ createItem(
+ Material.GLASS_PANE,
+ messageManager
+ .getMessage("gui.alpha-name")
+ .replace("%alpha%", String.valueOf(settings.getWallAlpha())),
+ List.of(
+ messageManager.getMessage("gui.lore-alpha-lmb"),
+ messageManager.getMessage("gui.lore-alpha-rmb"))));
+
+ // --- Свечение ---
+ boolean glowOn = settings.isWallGlow();
+ String glowText =
+ glowOn
+ ? messageManager.getMessage("gui.status-on")
+ : messageManager.getMessage("gui.status-off");
+ inventory.setItem(
+ WALLS_GLOW_SLOT,
+ createItem(
+ glowOn ? Material.GLOW_INK_SAC : Material.INK_SAC,
+ messageManager
+ .getMessage("gui.glow-name")
+ .replace("%status%", glowText),
+ List.of(
+ messageManager.getMessage("gui.lore-status") + glowText,
+ "",
+ messageManager.getMessage("gui.lore-glow-toggle"))));
+ }
+ }
+
+ private ItemStack createItem(Material material, String name, List lore) {
+ ItemStack item = new ItemStack(material);
+ ItemMeta meta = item.getItemMeta();
+ if (meta != null) {
+ meta.setDisplayName(name);
+ meta.setLore(lore);
+ item.setItemMeta(meta);
}
- inventory.setItem(BLOCK_SLOT, blockItem);
+ return item;
}
private void refreshVisuals(Player player) {
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/objects/Chunk.java b/src/main/java/ru/sawaplago/chunkVisualizer/objects/Chunk.java
index 3d80981..ec6c404 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/objects/Chunk.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/objects/Chunk.java
@@ -1,6 +1,7 @@
package ru.sawaplago.chunkVisualizer.objects;
import java.util.ArrayList;
+import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
@@ -38,38 +39,17 @@ public ArrayList getAngleChunk() {
}
public static Chunk getCurrentChunk(Player p) {
- int chunkXIndex = Math.floorDiv((int) Math.floor(p.getX()), CHUNK_SIZE);
- int chunkZIndex = Math.floorDiv((int) Math.floor(p.getZ()), CHUNK_SIZE);
+ return getCurrentChunk(p.getLocation());
+ }
- int startX = chunkXIndex * CHUNK_SIZE;
- int startZ = chunkZIndex * CHUNK_SIZE;
+ public static Chunk getCurrentChunk(Location location) {
+ int chunkXIndex = Math.floorDiv(location.getBlockX(), CHUNK_SIZE);
+ int chunkZIndex = Math.floorDiv(location.getBlockZ(), CHUNK_SIZE);
- return new Chunk(startX, startZ);
+ return new Chunk(chunkXIndex * CHUNK_SIZE, chunkZIndex * CHUNK_SIZE);
}
public static ArrayList getAngleChunk(Chunk chunk) {
- ArrayList chunks = new ArrayList<>();
- Vector nwVector =
- new Vector(chunk.startAngleVector.getX(), 0, chunk.startAngleVector.getZ());
- Vector neVector =
- new Vector(
- chunk.startAngleVector.getX() + CHUNK_SIZE,
- 0,
- chunk.startAngleVector.getZ());
- Vector swVector =
- new Vector(
- chunk.startAngleVector.getX(),
- 0,
- chunk.startAngleVector.getZ() + CHUNK_SIZE);
- Vector seVector =
- new Vector(
- chunk.startAngleVector.getX() + CHUNK_SIZE,
- 0,
- chunk.startAngleVector.getZ() + CHUNK_SIZE);
- chunks.add(nwVector);
- chunks.add(neVector);
- chunks.add(swVector);
- chunks.add(seVector);
- return chunks;
+ return chunk.getAngleChunk();
}
}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/objects/HighlightMode.java b/src/main/java/ru/sawaplago/chunkVisualizer/objects/HighlightMode.java
new file mode 100644
index 0000000..a59a95f
--- /dev/null
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/objects/HighlightMode.java
@@ -0,0 +1,32 @@
+package ru.sawaplago.chunkVisualizer.objects;
+
+import org.bukkit.entity.Player;
+
+public enum HighlightMode {
+ BLOCKS(null),
+ WALLS("chunkvisualizer.use.display");
+
+ private final String permission;
+
+ HighlightMode(String permission) {
+ this.permission = permission;
+ }
+
+ public boolean canUse(Player player) {
+ return permission == null || player.hasPermission(permission);
+ }
+
+ public HighlightMode next() {
+ HighlightMode[] values = values();
+ return values[(ordinal() + 1) % values.length];
+ }
+
+ public static HighlightMode fromString(String name, HighlightMode fallback) {
+ if (name == null) return fallback;
+ try {
+ return valueOf(name.trim().toUpperCase());
+ } catch (IllegalArgumentException e) {
+ return fallback;
+ }
+ }
+}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/objects/WallColor.java b/src/main/java/ru/sawaplago/chunkVisualizer/objects/WallColor.java
new file mode 100644
index 0000000..eec6c66
--- /dev/null
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/objects/WallColor.java
@@ -0,0 +1,59 @@
+package ru.sawaplago.chunkVisualizer.objects;
+
+import org.bukkit.Material;
+
+public enum WallColor {
+ RED(0xFF0000, Material.RED_STAINED_GLASS_PANE),
+ ORANGE(0xFF8000, Material.ORANGE_STAINED_GLASS_PANE),
+ YELLOW(0xFFFF00, Material.YELLOW_STAINED_GLASS_PANE),
+ GREEN(0x00FF00, Material.LIME_STAINED_GLASS_PANE),
+ CYAN(0x00FFFF, Material.CYAN_STAINED_GLASS_PANE),
+ BLUE(0x0000FF, Material.BLUE_STAINED_GLASS_PANE),
+ PURPLE(0xAA00FF, Material.PURPLE_STAINED_GLASS_PANE),
+ WHITE(0xFFFFFF, Material.WHITE_STAINED_GLASS_PANE);
+
+ public static final int MIN_ALPHA = 5;
+ public static final int MAX_ALPHA = 100;
+ public static final int ALPHA_STEP = 5;
+
+ private final int rgb;
+ private final Material icon;
+
+ WallColor(int rgb, Material icon) {
+ this.rgb = rgb;
+ this.icon = icon;
+ }
+
+ public int getRgb() {
+ return rgb;
+ }
+
+ public Material getIcon() {
+ return icon;
+ }
+
+ public WallColor next() {
+ WallColor[] values = values();
+ return values[(ordinal() + 1) % values.length];
+ }
+
+ public WallColor previous() {
+ WallColor[] values = values();
+ return values[(ordinal() - 1 + values.length) % values.length];
+ }
+
+ public int toArgb(int alphaPercent) {
+ int clamped = Math.max(0, Math.min(100, alphaPercent));
+ int alpha = Math.round(clamped * 255f / 100f);
+ return (alpha << 24) | rgb;
+ }
+
+ public static WallColor fromString(String name, WallColor fallback) {
+ if (name == null) return fallback;
+ try {
+ return valueOf(name.trim().toUpperCase());
+ } catch (IllegalArgumentException e) {
+ return fallback;
+ }
+ }
+}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ChunkHighlighter.java b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ChunkHighlighter.java
new file mode 100644
index 0000000..b351725
--- /dev/null
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ChunkHighlighter.java
@@ -0,0 +1,7 @@
+package ru.sawaplago.chunkVisualizer.visuals;
+
+public interface ChunkHighlighter {
+ void show();
+
+ void despawn();
+}
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ItemDisplayChunkHighlighter.java b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ItemDisplayChunkHighlighter.java
index 7180bf2..6181566 100644
--- a/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ItemDisplayChunkHighlighter.java
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/ItemDisplayChunkHighlighter.java
@@ -19,10 +19,12 @@
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import ru.sawaplago.chunkVisualizer.objects.Chunk;
+import ru.sawaplago.chunkVisualizer.objects.WallColor;
-public class ItemDisplayChunkHighlighter {
+public class ItemDisplayChunkHighlighter implements ChunkHighlighter {
private static final byte GLOWING_FLAG = 0x40;
private static final byte INVISIBLE_FLAG = 0x20;
+ private static final int METADATA_GLOW_COLOR_INDEX = 22;
private static final int METADATA_ITEM_INDEX = 23;
private static final int METADATA_DISPLAY_TYPE_INDEX = 24;
private static final byte DISPLAY_TYPE_HEAD = 5;
@@ -34,14 +36,18 @@ public class ItemDisplayChunkHighlighter {
private final List activeEntityIds = new ArrayList<>();
private final int height;
private final Material material;
+ private final int glowRgb;
- public ItemDisplayChunkHighlighter(Chunk chunk, Player player, int height, Material material) {
+ public ItemDisplayChunkHighlighter(
+ Chunk chunk, Player player, int height, Material material, WallColor glowColor) {
this.material = material;
this.chunk = chunk;
this.player = player;
this.height = height;
+ this.glowRgb = (glowColor != null ? glowColor : WallColor.WHITE).getRgb();
}
+ @Override
public void show() {
if (!activeEntityIds.isEmpty()) return;
@@ -72,6 +78,9 @@ private int spawnSinglePoint(Location loc) {
metaList.add(
new EntityData<>(0, EntityDataTypes.BYTE, (byte) (GLOWING_FLAG | INVISIBLE_FLAG)));
+ // Цвет обводки (glow color override)
+ metaList.add(new EntityData<>(METADATA_GLOW_COLOR_INDEX, EntityDataTypes.INT, glowRgb));
+
String materialName = this.material.getKey().toString();
ItemType type = ItemTypes.getByName(materialName);
@@ -92,6 +101,7 @@ private int spawnSinglePoint(Location loc) {
return entityId;
}
+ @Override
public void despawn() {
if (activeEntityIds.isEmpty()) return;
diff --git a/src/main/java/ru/sawaplago/chunkVisualizer/visuals/TextDisplayWallHighlighter.java b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/TextDisplayWallHighlighter.java
new file mode 100644
index 0000000..a5b3c1c
--- /dev/null
+++ b/src/main/java/ru/sawaplago/chunkVisualizer/visuals/TextDisplayWallHighlighter.java
@@ -0,0 +1,167 @@
+package ru.sawaplago.chunkVisualizer.visuals;
+
+import com.github.retrooper.packetevents.PacketEvents;
+import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
+import com.github.retrooper.packetevents.protocol.entity.data.EntityDataTypes;
+import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
+import com.github.retrooper.packetevents.protocol.world.Location;
+import com.github.retrooper.packetevents.util.Quaternion4f;
+import com.github.retrooper.packetevents.util.Vector3f;
+import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities;
+import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
+import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
+import net.kyori.adventure.text.Component;
+import org.bukkit.World;
+import org.bukkit.entity.Player;
+import org.bukkit.util.Vector;
+import ru.sawaplago.chunkVisualizer.objects.Chunk;
+import ru.sawaplago.chunkVisualizer.objects.WallColor;
+
+/** Рисует 4 стенки чанка через text_display (только на клиенте игрока). */
+public class TextDisplayWallHighlighter implements ChunkHighlighter {
+
+ // Индексы метаданных Entity / Display / TextDisplay (1.20.2+)
+ private static final int META_ENTITY_FLAGS = 0;
+ private static final int META_TRANSLATION = 11;
+ private static final int META_SCALE = 12;
+ private static final int META_LEFT_ROTATION = 13;
+ private static final int META_RIGHT_ROTATION = 14;
+ private static final int META_BILLBOARD = 15;
+ private static final int META_BRIGHTNESS = 16;
+ private static final int META_VIEW_RANGE = 17;
+ private static final int META_GLOW_COLOR = 22;
+ private static final int META_TEXT = 23;
+ private static final int META_BACKGROUND = 25;
+
+ private static final byte GLOWING_FLAG = 0x40;
+ private static final byte BILLBOARD_FIXED = 0;
+ private static final float VIEW_RANGE = 16f;
+ // brightness override: (block light << 4) | (sky light << 20)
+ private static final int FULL_BRIGHTNESS = (15 << 4) | (15 << 20);
+ private static final Vector3f SCALE = new Vector3f(130f, 1020f, 1f);
+ private static final Quaternion4f RIGHT_ROTATION = new Quaternion4f(0f, 0f, 0f, 1f);
+
+ private static final AtomicInteger ID_HOLDER = new AtomicInteger(300_000_000);
+
+ /** offsetX/offsetZ - место вызова относительно угла чанка (центр чанка = 8, 8). */
+ private record Wall(
+ double offsetX, double offsetZ, Vector3f translation, Quaternion4f leftRotation) {}
+
+ private static final List WALLS =
+ List.of(
+ new Wall(
+ 8.5,
+ 6.5,
+ new Vector3f(7.5f, 0f, 0f),
+ new Quaternion4f(0f, -0.7071f, 0f, 0.7071f)),
+ new Wall(
+ 9.5, 9.5, new Vector3f(0f, 0f, 6.5f), new Quaternion4f(0f, 1f, 0f, 0f)),
+ new Wall(
+ 6.5,
+ 9.5,
+ new Vector3f(-6.5f, 0f, 0f),
+ new Quaternion4f(0f, 0.7071f, 0f, 0.7071f)),
+ new Wall(
+ 6.5,
+ 6.5,
+ new Vector3f(0f, 0f, -6.5f),
+ new Quaternion4f(0f, 0f, 0f, 1f)));
+
+ private final Chunk chunk;
+ private final Player player;
+ private final int backgroundColor;
+ private final int glowRgb;
+ private final boolean glow;
+ private final List activeEntityIds = new ArrayList<>();
+
+ public TextDisplayWallHighlighter(
+ Chunk chunk, Player player, WallColor color, int alphaPercent, boolean glow) {
+ this.chunk = chunk;
+ this.player = player;
+ WallColor safeColor = color != null ? color : WallColor.RED;
+ this.backgroundColor = safeColor.toArgb(alphaPercent);
+ this.glowRgb = safeColor.getRgb();
+ this.glow = glow;
+ }
+
+ @Override
+ public void show() {
+ if (!activeEntityIds.isEmpty()) return;
+
+ World world = player.getWorld();
+ int minY = world.getMinHeight();
+ int maxY = world.getMaxHeight() - 1;
+
+ // Спавним на высоте игрока
+ int spawnY = Math.max(minY, Math.min(maxY, player.getLocation().getBlockY()));
+
+ // Стена по-прежнему начинается с minHeight: опускаем её через translation
+ float shiftY = (float) (minY - spawnY);
+
+ Vector start = chunk.getStartChunkPositionVector();
+
+ for (Wall wall : WALLS) {
+ Location loc =
+ new Location(
+ start.getX() + wall.offsetX(),
+ spawnY,
+ start.getZ() + wall.offsetZ(),
+ 0,
+ 0);
+ Vector3f translation = new Vector3f(wall.translation().x, shiftY, wall.translation().z);
+ activeEntityIds.add(spawnWall(loc, wall, translation));
+ }
+ }
+
+ private int spawnWall(Location loc, Wall wall, Vector3f translation) {
+ int entityId = ID_HOLDER.getAndIncrement();
+ UUID uuid = UUID.randomUUID();
+
+ WrapperPlayServerSpawnEntity spawnPacket =
+ new WrapperPlayServerSpawnEntity(
+ entityId, uuid, EntityTypes.TEXT_DISPLAY, loc, 0f, 0, null);
+ PacketEvents.getAPI().getPlayerManager().sendPacket(player, spawnPacket);
+
+ List> meta = new ArrayList<>();
+ meta.add(new EntityData<>(META_TRANSLATION, EntityDataTypes.VECTOR3F, translation));
+ meta.add(new EntityData<>(META_SCALE, EntityDataTypes.VECTOR3F, SCALE));
+ meta.add(
+ new EntityData<>(
+ META_LEFT_ROTATION, EntityDataTypes.QUATERNION, wall.leftRotation()));
+ meta.add(new EntityData<>(META_RIGHT_ROTATION, EntityDataTypes.QUATERNION, RIGHT_ROTATION));
+ meta.add(new EntityData<>(META_BILLBOARD, EntityDataTypes.BYTE, BILLBOARD_FIXED));
+ meta.add(new EntityData<>(META_VIEW_RANGE, EntityDataTypes.FLOAT, VIEW_RANGE));
+ // width/height не отправляем: 0 = без culling по боксу
+ meta.add(new EntityData<>(META_TEXT, EntityDataTypes.ADV_COMPONENT, Component.text(" ")));
+ meta.add(new EntityData<>(META_BACKGROUND, EntityDataTypes.INT, backgroundColor));
+
+ if (glow) {
+ // Контур (флаг glowing) цвета стены + полная яркость, чтобы стена "светилась"
+ meta.add(new EntityData<>(META_ENTITY_FLAGS, EntityDataTypes.BYTE, GLOWING_FLAG));
+ meta.add(new EntityData<>(META_GLOW_COLOR, EntityDataTypes.INT, glowRgb));
+ meta.add(new EntityData<>(META_BRIGHTNESS, EntityDataTypes.INT, FULL_BRIGHTNESS));
+ }
+
+ PacketEvents.getAPI()
+ .getPlayerManager()
+ .sendPacket(player, new WrapperPlayServerEntityMetadata(entityId, meta));
+
+ return entityId;
+ }
+
+ @Override
+ public void despawn() {
+ if (activeEntityIds.isEmpty()) return;
+
+ int[] ids = activeEntityIds.stream().mapToInt(Integer::intValue).toArray();
+ PacketEvents.getAPI()
+ .getPlayerManager()
+ .sendPacket(player, new WrapperPlayServerDestroyEntities(ids));
+
+ activeEntityIds.clear();
+ }
+}
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index 00f4ae6..26965de 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -2,7 +2,7 @@
# A full server restart is required to apply changes
settings:
- # Default height for the visualization relative to the player
+ # Default height for the visualization relative to the player (BLOCKS mode)
default-height: 1
# Should the visualization be enabled by default when a player joins for the first time?
@@ -10,4 +10,22 @@ settings:
# Default block material for the display (Must be a valid Bukkit Material name)
# See: https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html
- default-material: "GLOWSTONE"
\ No newline at end of file
+ default-material: "GLOWSTONE"
+
+ # Default outline (glow) color of the corner blocks (BLOCKS mode):
+ # RED, ORANGE, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE
+ default-block-glow-color: "WHITE"
+
+ # Default highlight mode for new players:
+ # BLOCKS - corner blocks (item_display)
+ # WALLS - chunk walls (text_display), requires permission chunkvisualizer.use.display
+ default-mode: "BLOCKS"
+
+ # Default wall color (WALLS mode): RED, ORANGE, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE
+ default-wall-color: "RED"
+
+ # Default wall opacity in percent (5-100, 100 = fully opaque)
+ default-wall-alpha: 50
+
+ # Should the walls glow by default (WALLS mode)? Players can change it in /cv settings
+ default-wall-glow: false
\ No newline at end of file
diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml
index 09dc316..c3f4147 100644
--- a/src/main/resources/messages.yml
+++ b/src/main/resources/messages.yml
@@ -3,6 +3,7 @@ menu-title: "&8Visualization Settings"
chunk-updated: "&aChunk visualization updated!"
only-players: "&cOnly players can use this command!"
no-permission: "&cYou do not have permission to execute this command."
+no-permission-display: "&cYou do not have permission to use the walls mode."
commands:
unknown: "&cUnknown subcommand. Use /cv help"
@@ -14,12 +15,14 @@ commands:
# GUI Button Settings /cv
gui:
height-name: "&eHighlight Height: &b%height%"
+ status-name: "&eVisualization: %status%"
status-on: "&aON"
status-off: "&cOFF"
lore-status: "&7Status: "
lore-lmb: "&eLMB: &fDecrease height (-1)"
lore-rmb: "&eRMB: &fIncrease height (+1)"
lore-shift: "&eShift + Click: &fToggle ON/OFF"
+ lore-toggle: "&eClick: &fToggle ON/OFF"
block-name: "&eVisualization Material"
block-lore:
- "&7Current block: &f%material%"
@@ -28,3 +31,33 @@ gui:
- "&eto change the material."
- ""
- "&cRMB: &fReset to Glowstone"
+
+ # Blocks mode: outline color
+ block-glow-name: "&eOutline Color: &f%color%"
+
+ # Highlight mode
+ mode-name: "&eHighlight Mode: &b%mode%"
+ mode-blocks: "Corner blocks"
+ mode-walls: "Walls"
+ lore-mode-current: "&7Current: &f"
+ lore-mode-switch: "&eClick: &fSwitch mode"
+
+ # Walls mode
+ color-name: "&eWall Color: &f%color%"
+ lore-color-current: "&7Current: &f"
+ lore-color-next: "&eLMB: &fNext color"
+ lore-color-prev: "&eRMB: &fPrevious color"
+ alpha-name: "&eWall Opacity: &b%alpha%%"
+ lore-alpha-lmb: "&eLMB: &fDecrease opacity (-5%)"
+ lore-alpha-rmb: "&eRMB: &fIncrease opacity (+5%)"
+ glow-name: "&eWall Glow: %status%"
+ lore-glow-toggle: "&eClick: &fToggle glow"
+ colors:
+ RED: "&cRed"
+ ORANGE: "&6Orange"
+ YELLOW: "&eYellow"
+ GREEN: "&aGreen"
+ CYAN: "&3Cyan"
+ BLUE: "&9Blue"
+ PURPLE: "&5Purple"
+ WHITE: "&fWhite"
\ No newline at end of file
diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml
index d404cf8..25042f6 100644
--- a/src/main/resources/plugin.yml
+++ b/src/main/resources/plugin.yml
@@ -1,5 +1,5 @@
name: ChunkVisualizer
-version: '0.3.1'
+version: '0.4'
main: ru.sawaplago.chunkVisualizer.ChunkVisualizer
api-version: '1.21'
authors: [ SawaPlayGO ]