Initial commit: LoParkour v1.1.0

This commit is contained in:
loki 2026-02-24 22:07:03 +01:00
commit aecb03ccf8
120 changed files with 9668 additions and 0 deletions

View file

@ -0,0 +1,199 @@
package dev.loki.loparkour.config;
import dev.loki.loparkour.LoParkour;
import dev.loki.loparkour.reward.Rewards;
import dev.loki.loparkour.schematic.Schematics;
import dev.efnilite.vilib.configupdater.ConfigUpdater;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Config management class.
*/
public enum Config {
CONFIG("config.yml", List.of("styles")),
GENERATION("generation.yml", null),
REWARDS("rewards-v2.yml", List.of("score-rewards", "interval-rewards", "one-time-rewards")),
SCHEMATICS("schematics/schematics.yml", List.of("difficulty"));
/**
* The path to this file, incl. plugin folder.
*/
public final File path;
/**
* The name of this file, e.g. config.yml
*/
public final String fileName;
/**
* The sections in the file that will be ignored when updating the keys.
*/
public final List<String> ignoredSections;
/**
* The {@link FileConfiguration} instance associated with this config file.
*/
public FileConfiguration fileConfiguration;
Config(String fileName, @Nullable List<String> ignoredSections) {
this.fileName = fileName;
this.ignoredSections = ignoredSections;
this.path = LoParkour.getInFolder(fileName);
if (!path.exists()) {
LoParkour.getPlugin().saveResource(fileName, false);
}
update();
load();
}
/**
* Reloads all config files.
*/
public static void reload(boolean initialLoad) {
for (Config config : values()) {
config.load();
}
// read config stuff
Rewards.init();
Locales.init();
Schematics.init();
Option.init(initialLoad);
LoParkour.log("Loaded all config files");
}
/**
* Loads the file from disk.
*/
public void load() {
this.fileConfiguration = YamlConfiguration.loadConfiguration(path);
}
/**
* Updates the file so all keys are present.
*/
public void update() {
try {
ConfigUpdater.update(LoParkour.getPlugin(), fileName, path, ignoredSections);
} catch (Exception ex) {
LoParkour.logging().stack("Error while trying to update config file", ex);
}
}
/**
* @param path The path.
* @return True when path exists, false if not.
*/
public boolean isPath(@NotNull String path) {
return fileConfiguration.isSet(path);
}
/**
* @param path The path.
* @return The value at path.
*/
public Object get(@NotNull String path) {
check(path);
return fileConfiguration.get(path);
}
/**
* @param path The path.
* @return The boolean value at path.
*/
public boolean getBoolean(@NotNull String path) {
check(path);
return fileConfiguration.getBoolean(path);
}
/**
* @param path The path.
* @return The int value at path.
*/
public int getInt(@NotNull String path) {
check(path);
return fileConfiguration.getInt(path);
}
/**
* @param path The path.
* @return The double value at path.
*/
public double getDouble(@NotNull String path) {
check(path);
return fileConfiguration.getDouble(path);
}
/**
* @param path The path.
* @return The String value at path.
*/
@NotNull
public String getString(@NotNull String path) {
check(path);
return fileConfiguration.getString(path, "");
}
/**
* @param path The path.
* @return The String list value at path.
*/
@NotNull
public List<String> getStringList(@NotNull String path) {
check(path);
return fileConfiguration.getStringList(path);
}
/**
* @param path The path.
* @return The int list value at path.
*/
@NotNull
public List<Integer> getIntList(@NotNull String path) {
check(path);
return fileConfiguration.getIntegerList(path);
}
/**
* @param path The path.
* @param deep Whether search should include children of children as well.
* @return The children nodes from path.
*/
@NotNull
public List<String> getChildren(@NotNull String path, boolean... deep) {
check(path);
ConfigurationSection section = fileConfiguration.getConfigurationSection(path);
if (section == null) {
return new ArrayList<>();
}
return new ArrayList<>(section.getKeys(deep != null));
}
// checks if the specified path exists to avoid developer error
private void check(@NotNull String path) {
if (!isPath(path)) {
throw new NoSuchElementException("Unknown path %s in %s".formatted(path, fileName));
}
}
}

View file

@ -0,0 +1,257 @@
package dev.loki.loparkour.config;
import dev.loki.loparkour.LoParkour;
import dev.loki.loparkour.menu.ParkourOption;
import dev.loki.loparkour.player.ParkourUser;
import dev.efnilite.vilib.inventory.item.Item;
import dev.efnilite.vilib.util.Task;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
/**
* Locale message/item handler.
*/
public class Locales {
// a list of all nodes, used to check against missing nodes
private static List<String> resourceNodes;
/**
* A map of all locales with their respective yml trees
*/
public static final Map<String, FileConfiguration> locales = new HashMap<>();
/**
* Initializes this Locale handler.
*/
public static void init() {
Plugin plugin = LoParkour.getPlugin();
Task.create(plugin).async().execute(() -> {
locales.clear();
FileConfiguration embedded = YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource("locales/en.yml"), StandardCharsets.UTF_8));
// get all nodes from the plugin's english resource, aka the most updated version
resourceNodes = getChildren(embedded, "", true);
File folder = LoParkour.getInFolder("locales");
// download files to locales folder
if (!folder.exists()) {
folder.mkdirs();
}
String[] files = folder.list();
// create non-existent files
if (files != null && files.length == 0) {
plugin.saveResource("locales/en.yml", false);
plugin.saveResource("locales/nl.yml", false);
plugin.saveResource("locales/fr.yml", false);
plugin.saveResource("locales/zh_cn.yml", false);
}
// get all files in locales folder
try (Stream<Path> stream = Files.list(folder.toPath())) {
stream.forEach(path -> {
File file = path.toFile();
// get locale from file name
String locale = file.getName().split("\\.")[0];
LoParkour.log("Found locale " + locale);
FileConfiguration config = YamlConfiguration.loadConfiguration(file);
validate(embedded, config, file);
locales.put(locale, config);
});
} catch (Exception ex) {
LoParkour.logging().stack("Error while trying to read locale files", "restart/reload your server", ex);
}
}).run();
}
// validates whether a lang file contains all required keys.
// if it doesn't, automatically add them
private static void validate(FileConfiguration provided, FileConfiguration user, File localPath) {
List<String> userNodes = getChildren(user, "", true);
for (String node : resourceNodes) {
if (userNodes.contains(node)) {
continue;
}
LoParkour.log("Fixing missing config node %s in %s".formatted(node, localPath.getName()));
user.set(node, provided.get(node));
}
LoParkour.log("Validated locale " + localPath.getName());
try {
user.save(localPath);
} catch (IOException ex) {
LoParkour.logging().stack("Error while trying to save fixed config file %s".formatted(localPath), "delete this file and restart your server", ex);
}
}
/**
* Gets a String from the provided path in the provided player's locale.
* If the player is a {@link ParkourUser}, their locale value will be used.
* If not, the default locale will be used.
*
* @param player The player
* @param path The path
* @return a String
*/
public static String getString(Player player, String path) {
ParkourUser user = ParkourUser.getUser(player);
String locale = user == null ? Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG) : user.locale;
return getString(locale, path);
}
/**
* Gets a coloured String from the provided path in the provided locale file
*
* @param locale The locale
* @param path The path
* @return a String
*/
public static String getString(String locale, String path) {
return getValue(locale, config -> config.getString(path), "");
}
/**
* Gets an uncoloured String list from the provided path in the provided locale file
*
* @param locale The locale
* @param path The path
* @return a String list
*/
public static List<String> getStringList(String locale, String path) {
return getValue(locale, config -> config.getStringList(path), Collections.emptyList());
}
private static <T> T getValue(String locale, Function<FileConfiguration, T> f, T def) {
if (locales.isEmpty()) {
return def;
}
FileConfiguration config = locales.get(locale);
return config != null ? f.apply(config) : def;
}
/**
* Returns an item from a json locale file.
* The locale is derived from the player.
* If the player is a {@link ParkourUser}, their locale value will be used.
* If not, the default locale will be used.
*
* @param player The player
* @param path The full path of the item in the locale file
* @return a non-null {@link Item} instance built from the description in the locale file
*/
@NotNull
public static Item getItem(@NotNull Player player, String path, String... replace) {
ParkourUser user = ParkourUser.getUser(player);
String locale = user == null ? Option.OPTIONS_DEFAULTS.get(ParkourOption.LANG) : user.locale;
return getItem(locale, path, replace);
}
private static final Pattern pattern = Pattern.compile("%[a-z]");
/**
* Returns an item from a provided json locale file with possible replacements.
*
* @param locale The locale
* @param path The path in the json file
* @param replace The Strings that will replace any appearances of a String following the regex "%[a-z]"
* @return a non-null {@link Item} instance built from the description in the locale file
*/
@NotNull
public static Item getItem(String locale, String path, String... replace) {
if (locales.isEmpty()) { // during reloading
return new Item(Material.STONE, "");
}
FileConfiguration base = locales.get(locale);
String material = base.getString("%s.material".formatted(path));
String name = base.getString("%s.name".formatted(path));
String lore = base.getString("%s.lore".formatted(path));
int modelId = base.getInt("%s.model_id".formatted(path), -1);
if (material == null) {
material = "";
}
if (name == null) {
name = "";
}
if (lore == null) {
lore = "";
}
int idx = 0;
Matcher matcher = pattern.matcher(name);
while (matcher.find()) {
if (idx == replace.length) {
break;
}
name = name.replaceFirst(matcher.group(), replace[idx]);
idx++;
}
matcher = pattern.matcher(lore);
while (matcher.find()) {
if (idx == replace.length) {
break;
}
lore = lore.replaceFirst(matcher.group(), replace[idx]);
idx++;
}
Item item = new Item(Material.getMaterial(material.toUpperCase()), name);
if (!lore.isEmpty()) {
item.lore(lore.split("\\|\\|"));
}
if (modelId != -1) {
item.modelId(modelId);
}
return item;
}
public static List<String> getChildren(FileConfiguration file, String path, boolean deep) {
ConfigurationSection section = file.getConfigurationSection(path);
return section != null ? new ArrayList<>(section.getKeys(deep)) : Collections.emptyList();
}
}

View file

@ -0,0 +1,264 @@
package dev.loki.loparkour.config;
import dev.loki.loparkour.LoParkour;
import dev.loki.loparkour.api.Registry;
import dev.loki.loparkour.menu.ParkourOption;
import dev.loki.loparkour.style.RandomStyle;
import dev.loki.loparkour.style.Style;
import dev.efnilite.vilib.particle.ParticleData;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.util.Vector;
import java.util.*;
import java.util.function.BiFunction;
/**
* Class for variables required in generating without accessing the file a lot (constants)
*/
public class Option {
public static double BORDER_SIZE;
public static List<Integer> POSSIBLE_LEADS;
// Advanced settings
public static BlockFace HEADING;
public static Map<ParkourOption, Boolean> OPTIONS_ENABLED;
public static Map<ParkourOption, String> OPTIONS_DEFAULTS;
public static Location GO_BACK_LOC;
public static void init(boolean firstLoad) {
initSql();
initEnums();
initGeneration();
initStyles("styles.list", Config.CONFIG.fileConfiguration, RandomStyle::new)
.forEach(Registry::register);
GO_BACK_LOC = parseLocation(Config.CONFIG.getString("bungeecord.go-back"));
String[] axes = Config.CONFIG.getString("bungeecord.go-back-axes").split(",");
GO_BACK_LOC.setPitch(Float.parseFloat(axes[0]));
GO_BACK_LOC.setYaw(Float.parseFloat(axes[1]));
// General settings
// Options
List<ParkourOption> options = new ArrayList<>(Arrays.asList(ParkourOption.values()));
// exceptions
options.remove(ParkourOption.JOIN);
options.remove(ParkourOption.ADMIN);
// =====================================
OPTIONS_DEFAULTS = new HashMap<>();
OPTIONS_ENABLED = new HashMap<>();
String prefix = "default-values";
for (ParkourOption option : options) {
String parent = "%s.%s".formatted(prefix, option.path);
// register enabled value
OPTIONS_ENABLED.put(option, Config.CONFIG.getBoolean("%s.enabled".formatted(parent)));
// register default value
if (!Config.CONFIG.isPath("%s.default".formatted(parent))) {
continue;
}
Object value = Config.CONFIG.get("%s.default".formatted(parent));
if (value != null) {
OPTIONS_DEFAULTS.put(option, String.valueOf(value));
}
}
// =====================================
// Config stuff
POSSIBLE_LEADS = Config.CONFIG.getIntList("options.leads.amount");
for (int lead : new ArrayList<>(POSSIBLE_LEADS)) {
if (lead < 1 || lead > 128) {
LoParkour.logging().error("Invalid lead: %d. Should be above 1 and below 128.".formatted(lead));
POSSIBLE_LEADS.remove((Object) lead);
}
}
// Generation
String heading = Config.GENERATION.getString("advanced.island.parkour.heading");
switch (heading.toLowerCase()) {
case "north" -> HEADING = BlockFace.NORTH;
case "south" -> HEADING = BlockFace.SOUTH;
case "west" -> HEADING = BlockFace.WEST;
case "east" -> HEADING = BlockFace.EAST;
default -> LoParkour.logging().error("Invalid heading: %s".formatted(heading));
}
// Scoring
if (firstLoad) {
BORDER_SIZE = Config.GENERATION.getDouble("advanced.border-size");
SQL = Config.CONFIG.getBoolean("sql.enabled");
}
}
private static Vector stringToVector(String direction) {
return switch (direction.toLowerCase()) {
case "north" -> new Vector(0, 0, -1);
case "south" -> new Vector(0, 0, 1);
case "west" -> new Vector(-1, 0, 0);
default -> new Vector(1, 0, 0); // east
};
}
private static Location parseLocation(String location) {
String[] values = location.replaceAll("[()]", "").replaceAll("[, ]", " ").split(" ");
World world = Bukkit.getWorld(values[3]);
if (world == null) {
world = Bukkit.getWorlds().get(0);
}
return new Location(world, Double.parseDouble(values[0]), Double.parseDouble(values[1]), Double.parseDouble(values[2]));
}
public static ParticleShape PARTICLE_SHAPE;
public static Sound SOUND_TYPE;
public static int SOUND_PITCH;
public static int SOUND_VOLUME;
public static Particle PARTICLE_TYPE;
public static ParticleData<?> PARTICLE_DATA;
private static void initEnums() {
String value = Config.CONFIG.getString("particles.sound-type").toUpperCase();
try {
SOUND_TYPE = Sound.valueOf(value);
} catch (IllegalArgumentException ex) {
SOUND_TYPE = Sound.valueOf("BLOCK_NOTE_PLING");
LoParkour.logging().error("Invalid sound: %s".formatted(value));
}
value = Config.CONFIG.getString("particles.particle-type");
try {
PARTICLE_TYPE = Particle.valueOf(value);
} catch (IllegalArgumentException ex) {
PARTICLE_TYPE = Particle.valueOf("SPELL_INSTANT");
LoParkour.logging().error("Invalid particle type: %s".formatted(value));
}
SOUND_PITCH = Config.CONFIG.getInt("particles.sound-pitch");
SOUND_VOLUME = Config.CONFIG.getInt("particles.sound-volume");
PARTICLE_SHAPE = ParticleShape.valueOf(Config.CONFIG.getString("particles.particle-shape").toUpperCase());
PARTICLE_DATA = new ParticleData<>(PARTICLE_TYPE, null, 10, 0, 0, 0, 0);
}
public enum ParticleShape {
DOT, CIRCLE, BOX
}
// --------------------------------------------------------------
// MySQL
public static boolean SQL;
public static int SQL_PORT;
public static String SQL_URL;
public static String SQL_DB;
public static String SQL_USERNAME;
public static String SQL_PASSWORD;
public static String SQL_PREFIX;
private static void initSql() {
SQL_PORT = Config.CONFIG.getInt("sql.port");
SQL_DB = Config.CONFIG.getString("sql.database");
SQL_URL = Config.CONFIG.getString("sql.url");
SQL_USERNAME = Config.CONFIG.getString("sql.username");
SQL_PASSWORD = Config.CONFIG.getString("sql.password");
SQL_PREFIX = Config.CONFIG.getString("sql.prefix");
}
// --------------------------------------------------------------
// Generation
public static double TYPE_NORMAL;
public static double TYPE_SPECIAL;
public static double TYPE_SCHEMATICS;
public static double SPECIAL_ICE;
public static double SPECIAL_SLAB;
public static double SPECIAL_PANE;
public static double SPECIAL_FENCE;
public static double NORMAL_DISTANCE_1;
public static double NORMAL_DISTANCE_2;
public static double NORMAL_DISTANCE_3;
public static double NORMAL_DISTANCE_4;
public static double NORMAL_HEIGHT_1;
public static double NORMAL_HEIGHT_0;
public static double NORMAL_HEIGHT_NEG1;
public static double NORMAL_HEIGHT_NEG2;
public static int MAX_Y;
public static int MIN_Y;
private static void initGeneration() {
TYPE_NORMAL = Config.GENERATION.getInt("generation.type.normal") / 100.0;
TYPE_SPECIAL = Config.GENERATION.getInt("generation.type.schematic") / 100.0;
TYPE_SCHEMATICS = Config.GENERATION.getInt("generation.type.special") / 100.0;
SPECIAL_ICE = Config.GENERATION.getInt("generation.special.ice") / 100.0;
SPECIAL_SLAB = Config.GENERATION.getInt("generation.special.slab") / 100.0;
SPECIAL_PANE = Config.GENERATION.getInt("generation.special.pane") / 100.0;
SPECIAL_FENCE = Config.GENERATION.getInt("generation.special.fence") / 100.0;
NORMAL_DISTANCE_1 = Config.GENERATION.getInt("generation.normal.distance.1") / 100.0;
NORMAL_DISTANCE_2 = Config.GENERATION.getInt("generation.normal.distance.2") / 100.0;
NORMAL_DISTANCE_3 = Config.GENERATION.getInt("generation.normal.distance.3") / 100.0;
NORMAL_DISTANCE_4 = Config.GENERATION.getInt("generation.normal.distance.4") / 100.0;
NORMAL_HEIGHT_1 = Config.GENERATION.getInt("generation.normal.height.1") / 100.0;
NORMAL_HEIGHT_0 = Config.GENERATION.getInt("generation.normal.height.0") / 100.0;
NORMAL_HEIGHT_NEG1 = Config.GENERATION.getInt("generation.normal.height.-1") / 100.0;
NORMAL_HEIGHT_NEG2 = Config.GENERATION.getInt("generation.normal.height.-2") / 100.0;
MAX_Y = Config.GENERATION.getInt("generation.settings.max-y");
MIN_Y = Config.GENERATION.getInt("generation.settings.min-y");
if (MIN_Y >= MAX_Y) {
MIN_Y = 100;
MAX_Y = 200;
LoParkour.logging().stack("Provided minimum y is the same or larger than maximum y!", "check your generation.yml file");
}
}
// --------------------------------------------------------------
public static Set<Style> initStyles(String path, FileConfiguration config, BiFunction<String, List<Material>, Style> fn) {
var styles = new HashSet<Style>();
for (String style : Locales.getChildren(config, path, false)) {
styles.add(fn.apply(style,
config.getStringList("%s.%s".formatted(path, style)).stream()
.map(name -> {
var material = Material.getMaterial(name.toUpperCase());
if (material == null) {
LoParkour.logging().error("Invalid material %s in style %s".formatted(name, style));
return Material.STONE;
}
return material;
})
.toList()));
}
return styles;
}
}