Compare commits

...

25 Commits

Author SHA1 Message Date
xGinko
15fcd14e16 add experimental regional optimization 2024-09-06 01:46:18 +02:00
xGinko
4019afe89b dont break loop 2024-09-02 02:11:07 +02:00
xGinko
6f1077ad2d only add to inv if survival 2024-09-02 02:09:14 +02:00
xGinko
72e2673248 try recreate vanilla restocking mechanic 2024-09-02 01:49:20 +02:00
xGinko
04d6cf604c try recreate vanilla restocking mechanic 2024-09-02 01:49:20 +02:00
Ginko
d4ba859176
Merge pull request #9 from OdgeBodge/master
Prevent nametag from being consumed when unoptimising
2024-08-29 23:34:30 +02:00
odgebodge
56d6baf9de don't consume on unoptimise 2024-08-29 22:12:09 +01:00
xGinko
ca3c486d8b cleanup main class 2024-08-09 14:55:53 +02:00
xGinko
9dd32b1207 add another missing return 2024-08-09 14:46:27 +02:00
xGinko
da300b2958 dont continue after disable call 2024-08-09 14:43:37 +02:00
xGinko
f90d3ac3f2 cleanup wrappers 2024-08-09 14:24:45 +02:00
xGinko
1360be9917 use cross compatible scheduler 2024-08-06 02:31:49 +02:00
xGinko
42a1bdec57 do more scheduling for folia 2024-08-06 02:30:31 +02:00
xGinko
6fe1330038 simplify command reload 2024-07-30 20:47:30 +02:00
xGinko
0a3cd80f9c make whitelist work like a whitelist 2024-07-30 02:33:34 +02:00
xGinko
0ff37cbd7d compile in lower version for backwards compatibility 2024-07-30 02:26:50 +02:00
xGinko
07d105e30e avoid auto-creation of alias references by configmaster 2024-07-30 02:20:32 +02:00
xGinko
aecd669638 remove usage of OldEnum for backwards compatibility
make reloadModules method simple again
2024-07-30 02:17:00 +02:00
xGinko
7969f75a3a close #7 2024-07-30 01:25:57 +02:00
xGinko
849d6fbaf5 update XSeries 2024-07-24 16:56:45 +02:00
xGinko
b0d1c42955 remove from cache on death 2024-07-24 16:51:36 +02:00
Ginko
159c03f3cd
Merge pull request #6 from bonn2/feat-profession-culling-whitelist 2024-07-19 22:36:48 +02:00
Brett Bonifas
106e1625cc Add villager profession culling whitelist 2024-07-19 01:06:59 -04:00
xGinko
c5e274daf9 remove unnecessary cast 2024-07-16 11:50:52 +02:00
xGinko
d0af45fc21 check if AVL is installed and disable plugin if yes 2024-07-16 11:41:05 +02:00
46 changed files with 807 additions and 394 deletions

View File

@ -6,7 +6,7 @@
<groupId>me.xginko</groupId>
<artifactId>VillagerOptimizer</artifactId>
<version>1.6.1</version>
<version>1.7.0</version>
<packaging>jar</packaging>
<name>VillagerOptimizer</name>
@ -121,7 +121,7 @@
<dependency>
<groupId>io.papermc.paper</groupId>
<artifactId>paper-api</artifactId>
<version>1.21-R0.1-SNAPSHOT</version>
<version>1.20.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -187,7 +187,7 @@
<dependency>
<groupId>com.github.cryptomorin</groupId>
<artifactId>XSeries</artifactId>
<version>11.2.0</version>
<version>11.2.1</version>
</dependency>
</dependencies>
</project>

View File

@ -1,11 +1,14 @@
package me.xginko.villageroptimizer;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
import me.xginko.villageroptimizer.config.Config;
import me.xginko.villageroptimizer.config.LanguageCache;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.utils.Util;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
@ -16,6 +19,7 @@ import org.apache.logging.log4j.core.config.Configurator;
import org.bstats.bukkit.Metrics;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import space.arim.morepaperlib.MorePaperLib;
@ -26,6 +30,7 @@ import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@ -41,9 +46,9 @@ import java.util.zip.ZipEntry;
public final class VillagerOptimizer extends JavaPlugin {
private static VillagerOptimizer instance;
private static WrapperCache wrapperCache;
private static CommandRegistration commandRegistration;
private static GracefulScheduling scheduling;
private static Cache<Villager, WrappedVillager> wrapperCache;
private static Map<String, LanguageCache> languageCacheMap;
private static Config config;
private static BukkitAudiences audiences;
@ -67,11 +72,21 @@ public final class VillagerOptimizer extends JavaPlugin {
logger = ComponentLogger.logger(getLogger().getName());
bStats = new Metrics(this, 19954);
if (getServer().getPluginManager().getPlugin("AntiVillagerLag") != null) {
logger.warn("While VillagerOptimizer can read data previously created by AVL, running");
logger.warn("both plugins at the same time is unsafe and definitely will cause issues.");
logger.warn("To protect your game from corruption, VillagerOptimizer will now disable!");
logger.warn("Please decide for one of the plugins!");
getServer().getPluginManager().disablePlugin(this);
return;
}
try {
getDataFolder().mkdirs();
} catch (Exception e) {
logger.error("Failed to create plugin directory! Cannot enable!", e);
getServer().getPluginManager().disablePlugin(this);
return;
}
logger.info(Component.text("╭────────────────────────────────────────────────────────────╮").style(Util.PL_STYLE));
@ -120,7 +135,7 @@ public final class VillagerOptimizer extends JavaPlugin {
VillagerOptimizerCommand.COMMANDS.forEach(VillagerOptimizerCommand::disable);
VillagerOptimizerCommand.COMMANDS.clear();
if (wrapperCache != null) {
wrapperCache.disable();
wrapperCache.cleanUp();
wrapperCache = null;
}
if (scheduling != null) {
@ -145,30 +160,39 @@ public final class VillagerOptimizer extends JavaPlugin {
public static @NotNull VillagerOptimizer getInstance() {
return instance;
}
public static @NotNull Config config() {
return config;
}
public static @NotNull WrapperCache getCache() {
return wrapperCache;
}
public static @NotNull CommandRegistration commandRegistration() {
return commandRegistration;
}
public static @NotNull GracefulScheduling scheduling() {
return scheduling;
}
public static @NotNull CommandRegistration commandRegistration() {
return commandRegistration;
}
public static @NotNull Cache<Villager, WrappedVillager> wrappers() {
return wrapperCache;
}
public static @NotNull Config config() {
return config;
}
public static @NotNull ComponentLogger logger() {
return logger;
}
public static @NotNull BukkitAudiences getAudiences() {
public static @NotNull BukkitAudiences audiences() {
return audiences;
}
public static @NotNull LanguageCache getLang(Locale locale) {
return getLang(locale.toString().toLowerCase());
}
public static @NotNull LanguageCache getLang(CommandSender commandSender) {
return commandSender instanceof Player ? getLang(((Player) commandSender).locale()) : getLang(config.default_lang);
}
public static @NotNull LanguageCache getLang(String lang) {
if (!config.auto_lang) return languageCacheMap.get(config.default_lang.toString().toLowerCase());
return languageCacheMap.getOrDefault(lang.replace("-", "_"), languageCacheMap.get(config.default_lang.toString().toLowerCase()));
@ -182,8 +206,8 @@ public final class VillagerOptimizer extends JavaPlugin {
private void reloadConfiguration() {
try {
config = new Config();
if (wrapperCache != null) wrapperCache.disable();
wrapperCache = new WrapperCache(config.cache_keep_time);
if (wrapperCache != null) wrapperCache.cleanUp();
wrapperCache = Caffeine.newBuilder().expireAfterWrite(config.cache_keep_time).build();
VillagerOptimizerCommand.reloadCommands();
VillagerOptimizerModule.reloadModules();
config.saveConfig();
@ -229,7 +253,7 @@ public final class VillagerOptimizer extends JavaPlugin {
.collect(Collectors.toCollection(TreeSet::new));
} catch (Throwable t) {
logger.error("Failed while searching for available translations!", t);
return new TreeSet<>();
return Collections.emptySortedSet();
}
}
}

View File

@ -1,31 +0,0 @@
package me.xginko.villageroptimizer;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import me.xginko.villageroptimizer.utils.Disableable;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.entity.Villager;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
import java.util.UUID;
public final class WrapperCache implements Disableable {
private final @NotNull Cache<UUID, WrappedVillager> wrapperCache;
public WrapperCache(Duration cacheDuration) {
this.wrapperCache = Caffeine.newBuilder().expireAfterWrite(cacheDuration).build();
}
@Override
public void disable() {
this.wrapperCache.invalidateAll();
this.wrapperCache.cleanUp();
}
@SuppressWarnings("DataFlowIssue")
public @NotNull WrappedVillager get(@NotNull Villager villager) {
return this.wrapperCache.get(villager.getUniqueId(), k -> new WrappedVillager(villager));
}
}

View File

@ -1,8 +1,8 @@
package me.xginko.villageroptimizer.commands;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.utils.Disableable;
import me.xginko.villageroptimizer.utils.Enableable;
import me.xginko.villageroptimizer.struct.Disableable;
import me.xginko.villageroptimizer.struct.Enableable;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.PluginCommand;
@ -11,11 +11,11 @@ import org.jetbrains.annotations.NotNull;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public abstract class VillagerOptimizerCommand implements Enableable, Disableable, CommandExecutor, TabCompleter {
@ -36,19 +36,15 @@ public abstract class VillagerOptimizerCommand implements Enableable, Disableabl
COMMANDS.forEach(VillagerOptimizerCommand::disable);
COMMANDS.clear();
COMMANDS_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerCommand.class).asClass())
.stream()
.filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
.map(clazz -> {
try {
return (VillagerOptimizerCommand) clazz.getDeclaredConstructor().newInstance();
} catch (Throwable t) {
VillagerOptimizer.logger().error("Failed initialising command '{}'.", clazz.getSimpleName(), t);
return null;
}
})
.filter(Objects::nonNull)
.forEach(COMMANDS::add);
for (Class<?> clazz : COMMANDS_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerCommand.class).asClass())) {
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue;
try {
COMMANDS.add((VillagerOptimizerCommand) clazz.getDeclaredConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
VillagerOptimizer.logger().error("Failed initialising command class '{}'.", clazz.getSimpleName(), e);
}
}
COMMANDS.forEach(VillagerOptimizerCommand::enable);
}

View File

@ -1,11 +1,10 @@
package me.xginko.villageroptimizer.commands.optimizevillagers;
import me.xginko.villageroptimizer.WrapperCache;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
import me.xginko.villageroptimizer.config.Config;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
@ -90,7 +89,6 @@ public class OptVillagersRadius extends VillagerOptimizerCommand {
return true;
}
WrapperCache wrapperCache = VillagerOptimizer.getCache();
int successCount = 0;
int failCount = 0;
final boolean player_has_cooldown_bypass = player.hasPermission(Permissions.Bypass.COMMAND_COOLDOWN.get());
@ -101,7 +99,7 @@ public class OptVillagersRadius extends VillagerOptimizerCommand {
Villager.Profession profession = villager.getProfession();
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
WrappedVillager wVillager = wrapperCache.get(villager);
WrappedVillager wVillager = VillagerOptimizer.wrappers().get(villager, WrappedVillager::new);
if (player_has_cooldown_bypass || wVillager.canOptimize(cooldown)) {
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(wVillager, OptimizationType.COMMAND, player);

View File

@ -1,10 +1,9 @@
package me.xginko.villageroptimizer.commands.unoptimizevillagers;
import me.xginko.villageroptimizer.WrapperCache;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
@ -85,7 +84,6 @@ public class UnOptVillagersRadius extends VillagerOptimizerCommand {
return true;
}
WrapperCache wrapperCache = VillagerOptimizer.getCache();
int successCount = 0;
for (Entity entity : player.getNearbyEntities(safeRadius, safeRadius, safeRadius)) {
@ -94,7 +92,7 @@ public class UnOptVillagersRadius extends VillagerOptimizerCommand {
Villager.Profession profession = villager.getProfession();
if (profession.equals(Villager.Profession.NITWIT) || profession.equals(Villager.Profession.NONE)) continue;
WrappedVillager wVillager = wrapperCache.get(villager);
WrappedVillager wVillager = VillagerOptimizer.wrappers().get(villager, WrappedVillager::new);
if (wVillager.isOptimized()) {
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(wVillager, player, OptimizationType.COMMAND);

View File

@ -5,7 +5,7 @@ import me.xginko.villageroptimizer.commands.VillagerOptimizerCommand;
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.DisableSubCmd;
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.ReloadSubCmd;
import me.xginko.villageroptimizer.commands.villageroptimizer.subcommands.VersionSubCmd;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.utils.Util;
import net.kyori.adventure.text.Component;

View File

@ -2,7 +2,7 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.commands.SubCommand;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.utils.Util;

View File

@ -2,7 +2,7 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.commands.SubCommand;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.utils.Util;
import net.kyori.adventure.text.Component;

View File

@ -3,7 +3,7 @@ package me.xginko.villageroptimizer.commands.villageroptimizer.subcommands;
import io.papermc.paper.plugin.configuration.PluginMeta;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.commands.SubCommand;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.utils.Util;
import net.kyori.adventure.text.Component;

View File

@ -118,13 +118,13 @@ public class Config {
return this.config.getInteger(path, def);
}
public @NotNull List<String> getList(@NotNull String path, @NotNull List<String> def, @NotNull String comment) {
public @NotNull <T> List<T> getList(@NotNull String path, @NotNull List<T> def, @NotNull String comment) {
this.config.addDefault(path, def, comment);
return this.config.getStringList(path);
return this.config.getList(path);
}
public @NotNull List<String> getList(@NotNull String path, @NotNull List<String> def) {
public @NotNull <T> List<T> getList(@NotNull String path, @NotNull List<T> def) {
this.config.addDefault(path, def);
return this.config.getStringList(path);
return this.config.getList(path);
}
}

View File

@ -20,6 +20,7 @@ public class LanguageCache {
public final @NotNull List<Component> nametag_optimize_success, nametag_on_optimize_cooldown, nametag_unoptimize_success,
block_optimize_success, block_on_optimize_cooldown, block_unoptimize_success,
workstation_optimize_success, workstation_on_optimize_cooldown, workstation_unoptimize_success,
activity_optimize_success,
command_optimize_success, command_radius_limit_exceed, command_optimize_fail, command_unoptimize_success,
command_specify_radius, command_radius_invalid, command_no_villagers_nearby,
trades_restocked, optimize_for_trading, villager_leveling_up;
@ -67,6 +68,10 @@ public class LanguageCache {
"<gray>You need to wait %time% until you can optimize this villager again.");
this.workstation_unoptimize_success = getListTranslation("messages.workstation.unoptimize-success",
"<green>Successfully unoptimized %villagertype% villager by removing workstation block %blocktype%.");
// Activity
this.activity_optimize_success = getListTranslation("messages.activity.optimized-near-you",
"<gray>%amount% villagers close to you were automatically optimized due to high activity.");
// Command
this.command_optimize_success = getListTranslation("messages.command.optimize-success",
"<green>Successfully optimized %amount% villager(s) in a radius of %radius% blocks.");

View File

@ -1,7 +1,7 @@
package me.xginko.villageroptimizer.events;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;

View File

@ -1,7 +1,7 @@
package me.xginko.villageroptimizer.events;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.utils;
package me.xginko.villageroptimizer.logging;
import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
import net.kyori.adventure.text.logger.slf4j.ComponentLoggerProvider;

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.utils;
package me.xginko.villageroptimizer.logging;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TranslatableComponent;

View File

@ -1,9 +1,10 @@
package me.xginko.villageroptimizer.modules;
import com.cryptomorin.xseries.XEntityType;
import me.xginko.villageroptimizer.utils.ExpiringSet;
import me.xginko.villageroptimizer.struct.models.ExpiringSet;
import me.xginko.villageroptimizer.utils.LocationUtil;
import me.xginko.villageroptimizer.utils.Util;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.entity.Entity;
@ -19,9 +20,12 @@ import space.arim.morepaperlib.scheduling.ScheduledTask;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -29,10 +33,11 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
private ScheduledTask periodic_chunk_check;
private final List<Villager.Profession> non_optimized_removal_priority, optimized_removal_priority;
private final Set<Villager.Profession> profession_whitelist;
private final ExpiringSet<Chunk> checked_chunks;
private final long check_period;
private final int non_optimized_max_per_chunk, optimized_max_per_chunk;
private final boolean log_enabled, skip_unloaded_chunks;
private final boolean log_enabled, skip_unloaded_chunks, use_whitelist;
protected VillagerChunkLimit() {
super("villager-chunk-limit");
@ -44,16 +49,14 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
"A larger delay is less resource intense but could become inefficient.");
this.skip_unloaded_chunks = config.getBoolean(configPath + ".skip-not-fully-loaded-chunks", true,
"Does not check chunks that don't have their entities loaded.");
this.log_enabled = config.getBoolean(configPath + ".log-removals", true);
this.non_optimized_max_per_chunk = config.getInt(configPath + ".unoptimized.max-per-chunk", 20,
"The maximum amount of unoptimized villagers per chunk.");
this.checked_chunks = new ExpiringSet<>(Duration.ofSeconds(
Math.max(1, config.getInt(configPath + ".chunk-check-cooldown-seconds", 5,
"The delay in seconds a chunk will not be checked again after the first time.\n" +
"Reduces chances to lag the server due to overchecking."))));
final List<String> defaults = Stream.of(
this.log_enabled = config.getBoolean(configPath + ".log-removals", true);
List<String> defaults = Stream.of(
"NONE", "NITWIT", "SHEPHERD", "FISHERMAN", "BUTCHER", "CARTOGRAPHER", "LEATHERWORKER",
"FLETCHER", "MASON", "FARMER", "ARMORER", "TOOLSMITH", "WEAPONSMITH", "CLERIC", "LIBRARIAN")
"FLETCHER", "MASON", "FARMER", "ARMORER", "TOOLSMITH", "WEAPONSMITH", "CLERIC", "LIBRARIAN")
.filter(profession -> {
try {
// Make sure no scary warnings appear when creating config defaults
@ -63,7 +66,26 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
return false;
}
}).collect(Collectors.toList());
this.non_optimized_removal_priority = config.getList(configPath + ".unoptimized.removal-priority", defaults,
this.use_whitelist = config.getBoolean(configPath + ".whitelist.enable", false,
"Enable if you only want to manage villager counts for certain profession types.");
this.profession_whitelist = config.getList(configPath + ".whitelist.professions", Arrays.asList("NONE", "NITWIT"),
"Professions in this list will not be touched by the chunk limit.")
.stream()
.map(configuredProfession -> {
try {
return Villager.Profession.valueOf(configuredProfession);
} catch (IllegalArgumentException e) {
warn("(whitelist) Villager profession '" + configuredProfession +
"' not recognized. Make sure you're using the correct profession enums from " +
"https://jd.papermc.io/paper/1.20/org/bukkit/entity/Villager.Profession.html.");
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toCollection(HashSet::new));
this.non_optimized_max_per_chunk = config.getInt(configPath + ".unoptimized.max-per-chunk", 20,
"The maximum amount of unoptimized villagers per chunk.");
this.non_optimized_removal_priority = config.getList(configPath + ".unoptimized.removal-priority", new ArrayList<>(defaults),
"Professions that are in the top of the list are going to be scheduled for removal first.\n" +
"Use enums from https://jd.papermc.io/paper/1.20/org/bukkit/entity/Villager.Profession.html")
.stream()
@ -81,7 +103,7 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
.collect(Collectors.toList());
this.optimized_max_per_chunk = config.getInt(configPath + ".optimized.max-per-chunk", 60,
"The maximum amount of optimized villagers per chunk.");
this.optimized_removal_priority = config.getList(configPath + ".optimized.removal-priority", defaults)
this.optimized_removal_priority = config.getList(configPath + ".optimized.removal-priority", new ArrayList<>(defaults))
.stream()
.map(configuredProfession -> {
try {
@ -159,7 +181,10 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
Villager villager = (Villager) entity;
if (wrapperCache.get(villager).isOptimized()) {
// Ignore villager if profession is not in the whitelist
if (use_whitelist && profession_whitelist.contains(villager.getProfession())) continue;
if (wrapperCache.get(villager, WrappedVillager::new).isOptimized()) {
optimized_villagers.add(villager);
} else {
not_optimized_villagers.add(villager);
@ -180,7 +205,7 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
scheduling.entitySpecificScheduler(villager).run(kill -> {
villager.remove();
if (log_enabled) info("Removed unoptimized villager with profession '" +
Util.formatEnum(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
Util.toNiceString(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
}, null);
}
}
@ -199,7 +224,7 @@ public class VillagerChunkLimit extends VillagerOptimizerModule implements Runna
scheduling.entitySpecificScheduler(villager).run(kill -> {
villager.remove();
if (log_enabled) info("Removed unoptimized villager with profession '" +
Util.formatEnum(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
Util.toNiceString(villager.getProfession()) + "' at " + LocationUtil.toString(villager.getLocation()));
}, null);
}
}

View File

@ -1,17 +1,19 @@
package me.xginko.villageroptimizer.modules;
import me.xginko.villageroptimizer.WrapperCache;
import com.github.benmanes.caffeine.cache.Cache;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.config.Config;
import me.xginko.villageroptimizer.utils.Disableable;
import me.xginko.villageroptimizer.utils.Enableable;
import me.xginko.villageroptimizer.struct.Disableable;
import me.xginko.villageroptimizer.struct.Enableable;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.entity.Villager;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import space.arim.morepaperlib.scheduling.GracefulScheduling;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public abstract class VillagerOptimizerModule implements Enableable, Disableable {
@ -23,7 +25,7 @@ public abstract class VillagerOptimizerModule implements Enableable, Disableable
protected final VillagerOptimizer plugin;
protected final Config config;
protected final WrapperCache wrapperCache;
protected final Cache<Villager, WrappedVillager> wrapperCache;
protected final GracefulScheduling scheduling;
public final String configPath;
private final String logFormat;
@ -31,7 +33,7 @@ public abstract class VillagerOptimizerModule implements Enableable, Disableable
public VillagerOptimizerModule(String configPath) {
this.plugin = VillagerOptimizer.getInstance();
this.config = VillagerOptimizer.config();
this.wrapperCache = VillagerOptimizer.getCache();
this.wrapperCache = VillagerOptimizer.wrappers();
this.scheduling = VillagerOptimizer.scheduling();
this.configPath = configPath;
shouldEnable(); // Ensure enable option is always first
@ -47,20 +49,18 @@ public abstract class VillagerOptimizerModule implements Enableable, Disableable
ENABLED_MODULES.forEach(VillagerOptimizerModule::disable);
ENABLED_MODULES.clear();
MODULES_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerModule.class).asClass())
.stream()
.filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
.map(clazz -> {
try {
return (VillagerOptimizerModule) clazz.getDeclaredConstructor().newInstance();
} catch (Throwable t) {
VillagerOptimizer.logger().error("Failed initialising module '{}'.", clazz.getSimpleName(), t);
return null;
}
})
.filter(Objects::nonNull)
.filter(VillagerOptimizerModule::shouldEnable)
.forEach(ENABLED_MODULES::add);
for (Class<?> clazz : MODULES_PACKAGE.get(Scanners.SubTypes.of(VillagerOptimizerModule.class).asClass())) {
if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue;
try {
VillagerOptimizerModule module = (VillagerOptimizerModule) clazz.getDeclaredConstructor().newInstance();
if (module.shouldEnable()) {
ENABLED_MODULES.add(module);
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
VillagerOptimizer.logger().error("Failed initialising module class '{}'.", clazz.getSimpleName(), e);
}
}
ENABLED_MODULES.forEach(VillagerOptimizerModule::enable);
}

View File

@ -4,6 +4,7 @@ import com.cryptomorin.xseries.XEntityType;
import com.cryptomorin.xseries.XMaterial;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.utils.LocationUtil;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
@ -53,7 +54,7 @@ public class EnableLeashingVillagers extends VillagerOptimizerModule implements
final Villager villager = (Villager) event.getRightClicked();
if (villager.isLeashed()) return;
if (only_optimized && !wrapperCache.get(villager).isOptimized()) return;
if (only_optimized && !wrapperCache.get(villager, WrappedVillager::new).isOptimized()) return;
event.setCancelled(true); // Cancel the event, so we don't interact with the villager

View File

@ -39,7 +39,7 @@ public class FixOptimisationAfterCure extends VillagerOptimizerModule implements
) {
Villager villager = (Villager) event.getTransformedEntity();
scheduling.entitySpecificScheduler(villager).runDelayed(() -> {
WrappedVillager wVillager = wrapperCache.get(villager);
WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
wVillager.setOptimizationType(wVillager.getOptimizationType());
}, null, 40L);
}

View File

@ -65,7 +65,7 @@ public class LevelOptimizedProfession extends VillagerOptimizerModule implements
&& event.getInventory().getHolder() instanceof Villager
) {
final Villager villager = (Villager) event.getInventory().getHolder();
final WrappedVillager wVillager = wrapperCache.get(villager);
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
if (!wVillager.isOptimized()) return;
if (wVillager.canLevelUp(cooldown_millis)) {

View File

@ -2,6 +2,7 @@ package me.xginko.villageroptimizer.modules.gameplay;
import com.cryptomorin.xseries.XEntityType;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -65,7 +66,7 @@ public class PreventOptimizedDamage extends VillagerOptimizerModule implements L
if (
event.getEntityType() == XEntityType.VILLAGER.get()
&& damage_causes_to_cancel.contains(event.getCause())
&& wrapperCache.get((Villager) event.getEntity()).isOptimized()
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
) {
event.setCancelled(true);
}
@ -76,7 +77,7 @@ public class PreventOptimizedDamage extends VillagerOptimizerModule implements L
if (
cancel_knockback
&& event.getEntityType() == XEntityType.VILLAGER.get()
&& wrapperCache.get((Villager) event.getEntity()).isOptimized()
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
) {
event.setCancelled(true);
}

View File

@ -2,6 +2,7 @@ package me.xginko.villageroptimizer.modules.gameplay;
import com.cryptomorin.xseries.XEntityType;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Mob;
import org.bukkit.entity.Villager;
@ -41,7 +42,7 @@ public class PreventOptimizedTargeting extends VillagerOptimizerModule implement
if (
target != null
&& target.getType() == XEntityType.VILLAGER.get()
&& wrapperCache.get((Villager) target).isOptimized()
&& wrapperCache.get((Villager) target, WrappedVillager::new).isOptimized()
) {
event.setTarget(null);
event.setCancelled(true);
@ -54,7 +55,7 @@ public class PreventOptimizedTargeting extends VillagerOptimizerModule implement
if (
target != null
&& target.getType() == XEntityType.VILLAGER.get()
&& wrapperCache.get((Villager) target).isOptimized()
&& wrapperCache.get((Villager) target, WrappedVillager::new).isOptimized()
) {
event.setCancelled(true);
}
@ -65,7 +66,7 @@ public class PreventOptimizedTargeting extends VillagerOptimizerModule implement
if (
event.getEntityType() == XEntityType.VILLAGER.get()
&& event.getDamager() instanceof Mob
&& wrapperCache.get((Villager) event.getEntity()).isOptimized()
&& wrapperCache.get((Villager) event.getEntity(), WrappedVillager::new).isOptimized()
) {
((Mob) event.getDamager()).setTarget(null);
}

View File

@ -1,9 +1,10 @@
package me.xginko.villageroptimizer.modules.gameplay;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
@ -48,7 +49,7 @@ public class PreventUnoptimizedTrading extends VillagerOptimizerModule implement
if (event.getInventory().getType() != InventoryType.MERCHANT) return;
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
if (!(event.getInventory().getHolder() instanceof Villager)) return;
if (wrapperCache.get((Villager) event.getInventory().getHolder()).isOptimized()) return;
if (wrapperCache.get((Villager) event.getInventory().getHolder(), WrappedVillager::new).isOptimized()) return;
event.setCancelled(true);
@ -63,7 +64,7 @@ public class PreventUnoptimizedTrading extends VillagerOptimizerModule implement
if (event.getInventory().getType() != InventoryType.MERCHANT) return;
if (event.getWhoClicked().hasPermission(Permissions.Bypass.TRADE_PREVENTION.get())) return;
if (!(event.getInventory().getHolder() instanceof Villager)) return;
if (wrapperCache.get((Villager) event.getInventory().getHolder()).isOptimized()) return;
if (wrapperCache.get((Villager) event.getInventory().getHolder(), WrappedVillager::new).isOptimized()) return;
event.setCancelled(true);

View File

@ -2,14 +2,13 @@ package me.xginko.villageroptimizer.modules.gameplay;
import com.cryptomorin.xseries.XEntityType;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.utils.KyoriUtil;
import me.xginko.villageroptimizer.utils.LocationUtil;
import me.xginko.villageroptimizer.utils.Util;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import net.kyori.adventure.text.TextReplacementConfig;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -18,10 +17,14 @@ import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import java.time.Duration;
import java.util.Arrays;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;
public class RestockOptimizedTrades extends VillagerOptimizerModule implements Listener {
private final long restock_delay_millis;
private final SortedSet<Long> restockDayTimes;
private final boolean log_enabled, notify_player;
public RestockOptimizedTrades() {
@ -29,8 +32,10 @@ public class RestockOptimizedTrades extends VillagerOptimizerModule implements L
config.master().addComment(configPath,
"This is for automatic restocking of trades for optimized villagers. Optimized Villagers\n" +
"don't have enough AI to restock their trades naturally, so this is here as a workaround.");
this.restock_delay_millis = config.getInt(configPath + ".delay-in-ticks", 1000,
"1 second = 20 ticks. There are 24.000 ticks in a single minecraft day.") * 50L;
this.restockDayTimes = new TreeSet<>(Comparator.reverseOrder());
this.restockDayTimes.addAll(config.getList(configPath + ".restock-times", Arrays.asList(1000L, 13000L),
"At which (tick-)times during the day villagers will restock.\n" +
"There are 24.000 ticks in a single minecraft day."));
this.notify_player = config.getBoolean(configPath + ".notify-player", true,
"Sends the player a message when the trades were restocked on a clicked villager.");
this.log_enabled = config.getBoolean(configPath + ".log", false);
@ -52,30 +57,54 @@ public class RestockOptimizedTrades extends VillagerOptimizerModule implements L
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onInteract(PlayerInteractEntityEvent event) {
private void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (event.getRightClicked().getType() != XEntityType.VILLAGER.get()) return;
final WrappedVillager wVillager = wrapperCache.get((Villager) event.getRightClicked());
if (!wVillager.isOptimized()) return;
WrappedVillager wrapped = wrapperCache.get((Villager) event.getRightClicked(), WrappedVillager::new);
if (!wrapped.isOptimized()) return;
final Player player = event.getPlayer();
final boolean player_bypassing = player.hasPermission(Permissions.Bypass.RESTOCK_COOLDOWN.get());
if (!wVillager.canRestock(restock_delay_millis) && !player_bypassing) return;
if (event.getPlayer().hasPermission(Permissions.Bypass.RESTOCK_COOLDOWN.get())) {
wrapped.restock();
return;
}
wVillager.restock();
wVillager.saveRestockTime();
long lastRestockFullTimeTicks = wrapped.getLastRestockFullTime();
long currentFullTimeTicks = wrapped.currentFullTimeTicks();
long currentDayTimeTicks = wrapped.currentDayTimeTicks();
if (notify_player && !player_bypassing) {
long currentDay = currentFullTimeTicks - currentDayTimeTicks;
long ticksTillRestock = (24000 + currentDay + restockDayTimes.first()) - currentFullTimeTicks;
boolean restocked = false;
for (Long restockDayTime : restockDayTimes) {
long restockTimeToday = currentDay + restockDayTime;
if (currentFullTimeTicks < restockTimeToday || lastRestockFullTimeTicks >= restockTimeToday) {
ticksTillRestock = Math.min(ticksTillRestock, restockTimeToday - currentFullTimeTicks);
continue;
}
if (!restocked) {
wrapped.restock();
wrapped.saveRestockTime();
restocked = true;
}
}
if (!restocked) return;
if (notify_player) {
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
.matchLiteral("%time%")
.replacement(Util.formatDuration(Duration.ofMillis(wVillager.getRestockCooldownMillis(restock_delay_millis))))
.replacement(Util.formatDuration(Duration.ofMillis(ticksTillRestock * 50L)))
.build();
VillagerOptimizer.getLang(player.locale()).trades_restocked
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
VillagerOptimizer.getLang(event.getPlayer().locale()).trades_restocked
.forEach(line -> KyoriUtil.sendMessage(event.getPlayer(), line.replaceText(timeLeft)));
}
if (log_enabled) {
info("Restocked optimized villager at " + LocationUtil.toString(wVillager.villager().getLocation()));
info("Restocked optimized villager at " + LocationUtil.toString(wrapped.villager.getLocation()));
}
}
}

View File

@ -1,6 +1,6 @@
package me.xginko.villageroptimizer.modules.gameplay;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import org.bukkit.event.EventHandler;
@ -35,9 +35,9 @@ public class UnoptimizeOnJobLoose extends VillagerOptimizerModule implements Lis
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onJobReset(VillagerCareerChangeEvent event) {
if (event.getReason() != VillagerCareerChangeEvent.ChangeReason.LOSING_JOB) return;
final WrappedVillager wrappedVillager = wrapperCache.get(event.getEntity());
if (wrappedVillager.isOptimized()) {
wrappedVillager.setOptimizationType(OptimizationType.NONE);
final WrappedVillager wrapped = wrapperCache.get(event.getEntity(), WrappedVillager::new);
if (wrapped.isOptimized()) {
wrapped.setOptimizationType(OptimizationType.NONE);
}
}
}

View File

@ -34,7 +34,7 @@ public class VisuallyHighlightOptimized extends VillagerOptimizerModule implemen
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onOptimize(VillagerOptimizeEvent event) {
Villager villager = event.getWrappedVillager().villager();
Villager villager = event.getWrappedVillager().villager;
scheduling.entitySpecificScheduler(villager).run(glow -> {
if (!villager.isGlowing()) villager.setGlowing(true);
}, null);
@ -42,7 +42,7 @@ public class VisuallyHighlightOptimized extends VillagerOptimizerModule implemen
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onUnOptimize(VillagerUnoptimizeEvent event) {
Villager villager = event.getWrappedVillager().villager();
Villager villager = event.getWrappedVillager().villager;
scheduling.entitySpecificScheduler(villager).run(unGlow -> {
if (villager.isGlowing()) villager.setGlowing(false);
}, null);

View File

@ -0,0 +1,240 @@
package me.xginko.villageroptimizer.modules.optimization;
import com.cryptomorin.xseries.XEntityType;
import com.destroystokyo.paper.event.entity.EntityPathfindEvent;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.models.BlockRegion2D;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import net.kyori.adventure.text.TextReplacementConfig;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityInteractEvent;
import org.jetbrains.annotations.NotNull;
import java.time.Duration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class OptimizeByActivity extends VillagerOptimizerModule implements Listener {
protected static class RegionData {
public final BlockRegion2D region;
public final AtomicInteger pathfindCount, entityInteractCount;
public final AtomicBoolean regionBusy;
public RegionData(BlockRegion2D region) {
this.region = region;
this.pathfindCount = new AtomicInteger();
this.entityInteractCount = new AtomicInteger();
this.regionBusy = new AtomicBoolean(false);
}
}
private final Cache<BlockRegion2D, RegionData> regionDataCache;
private final double checkRadius;
private final int pathfindLimit, entityInteractLimit;
private final boolean notifyPlayers, doLogging;
public OptimizeByActivity() {
super("optimization-methods.regional-activity");
config.master().addComment(configPath + ".enable",
"Enable optimization by naming villagers to one of the names configured below.\n" +
"Nametag optimized villagers will be unoptimized again when they are renamed to something else.");
this.checkRadius = config.getDouble(configPath + ".check-radius-blocks", 500.0,
"The radius in blocks in which activity will be grouped together and measured.");
this.regionDataCache = Caffeine.newBuilder().expireAfterWrite(Duration.ofMillis(
config.getInt(configPath + ".data-keep-time-millis", 10000,
"The time in milliseconds before a region and its data will be expired\n" +
"if no activity has been detected.\n" +
"For proper functionality, needs to be at least as long as your pause time."))).build();
this.pathfindLimit = config.getInt(configPath + ".limits.pathfind-event", 150);
this.entityInteractLimit = config.getInt(configPath + ".limits.interact-event", 50);
this.notifyPlayers = config.getBoolean(configPath + ".notify-players", true,
"Sends players a message to any player near an auto-optimized villager.");
this.doLogging = config.getBoolean(configPath + ".log", false);
}
@Override
public void enable() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@Override
public void disable() {
HandlerList.unregisterAll(this);
}
@Override
public boolean shouldEnable() {
return config.getBoolean(configPath + ".enable", false);
}
private @NotNull RegionData getRegionData(Location location) {
return regionDataCache.get(getRegion(location), RegionData::new);
}
private @NotNull BlockRegion2D getRegion(Location location) {
// Find and return region containing this location
for (Map.Entry<BlockRegion2D, RegionData> regionDataEntry : regionDataCache.asMap().entrySet()) {
if (regionDataEntry.getKey().contains(location)) {
return regionDataEntry.getKey();
}
}
// Create and cache region if none exists
BlockRegion2D region = BlockRegion2D.of(location.getWorld(), location.getX(), location.getZ(), checkRadius);
regionDataCache.put(region, new RegionData(region));
return region;
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onEntityPathfind(EntityPathfindEvent event) {
if (event.getEntityType() != XEntityType.VILLAGER.get()) return;
Location location = event.getEntity().getLocation();
BlockRegion2D region2D = getRegion(location);
RegionData regionData = getRegionData(location);
if (regionData.regionBusy.get() || regionData.pathfindCount.incrementAndGet() <= pathfindLimit) {
return;
}
regionData.regionBusy.set(true);
AtomicInteger optimizeCount = new AtomicInteger();
Set<Player> playersWithinArea = new CopyOnWriteArraySet<>();
region2D.getEntities()
.thenAccept(entities -> {
for (Entity entity : entities) {
scheduling.entitySpecificScheduler(entity).run(() -> {
if (entity.getType() == XEntityType.VILLAGER.get()) {
WrappedVillager wrappedVillager = wrapperCache.get((Villager) entity, WrappedVillager::new);
if (wrappedVillager.isOptimized()) {
return;
}
wrappedVillager.setOptimizationType(OptimizationType.REGIONAL_ACTIVITY);
optimizeCount.incrementAndGet();
}
if (notifyPlayers && entity.getType() == XEntityType.PLAYER.get()) {
playersWithinArea.add((Player) entity);
}
}, null);
}
})
.thenRun(() -> {
if (notifyPlayers) {
TextReplacementConfig amount = TextReplacementConfig.builder()
.matchLiteral("%amount%")
.replacement(optimizeCount.toString())
.build();
for (Player player : playersWithinArea) {
VillagerOptimizer.scheduling().entitySpecificScheduler(player).run(() ->
VillagerOptimizer.getLang(player.locale()).activity_optimize_success
.forEach(line -> player.sendMessage(line.replaceText(amount))),
null);
}
playersWithinArea.clear();
}
if (doLogging) {
info( "Optimized " + optimizeCount.get() + " villagers in a radius of " + checkRadius +
" blocks from center at x=" + regionData.region.getCenterX() + ", z=" + regionData.region.getCenterZ() +
" in world " + location.getWorld().getName() +
"because of too high pathfinding activity within the configured timeframe: " +
regionData.pathfindCount + " (limit: " + pathfindLimit + ")");
}
regionDataCache.invalidate(region2D);
});
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
private void onEntityInteract(EntityInteractEvent event) {
if (event.getEntityType() != XEntityType.VILLAGER.get()) return;
Location location = event.getEntity().getLocation();
BlockRegion2D region2D = getRegion(location);
RegionData regionData = getRegionData(location);
if (regionData.regionBusy.get() || regionData.entityInteractCount.incrementAndGet() <= entityInteractLimit) {
return;
}
regionData.regionBusy.set(true);
AtomicInteger optimizeCount = new AtomicInteger();
Set<Player> playersWithinArea = new CopyOnWriteArraySet<>();
region2D.getEntities()
.thenAccept(entities -> {
for (Entity entity : entities) {
scheduling.entitySpecificScheduler(entity).run(() -> {
if (entity.getType() == XEntityType.VILLAGER.get()) {
WrappedVillager wrappedVillager = wrapperCache.get((Villager) entity, WrappedVillager::new);
if (wrappedVillager.isOptimized()) {
return;
}
wrappedVillager.setOptimizationType(OptimizationType.REGIONAL_ACTIVITY);
optimizeCount.incrementAndGet();
}
if (notifyPlayers && entity.getType() == XEntityType.PLAYER.get()) {
playersWithinArea.add((Player) entity);
}
}, null);
}
})
.thenRun(() -> {
if (notifyPlayers) {
TextReplacementConfig amount = TextReplacementConfig.builder()
.matchLiteral("%amount%")
.replacement(optimizeCount.toString())
.build();
for (Player player : playersWithinArea) {
VillagerOptimizer.scheduling().entitySpecificScheduler(player).run(() ->
VillagerOptimizer.getLang(player.locale()).activity_optimize_success
.forEach(line -> player.sendMessage(line.replaceText(amount))),
null);
}
playersWithinArea.clear();
}
if (doLogging) {
info( "Optimized " + optimizeCount.get() + " villagers in a radius of " + checkRadius +
" blocks from center at x=" + regionData.region.getCenterX() + ", z=" + regionData.region.getCenterZ() +
" in world " + location.getWorld().getName() +
"because of too many villagers interacting with objects within the configured timeframe: " +
regionData.pathfindCount + " (limit: " + pathfindLimit + ")");
}
regionDataCache.invalidate(region2D);
});
}
}

View File

@ -2,8 +2,8 @@ package me.xginko.villageroptimizer.modules.optimization;
import com.cryptomorin.xseries.XMaterial;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
@ -111,7 +111,7 @@ public class OptimizeByBlock extends VillagerOptimizerModule implements Listener
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
if (distance >= closestDistance) continue;
final WrappedVillager wVillager = wrapperCache.get(villager);
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
if (wVillager.canOptimize(cooldown_millis)) {
closestOptimizableVillager = wVillager;
closestDistance = distance;
@ -135,11 +135,11 @@ public class OptimizeByBlock extends VillagerOptimizerModule implements Listener
if (notify_player) {
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
.matchLiteral("%vil_profession%")
.replacement(Util.formatEnum(closestOptimizableVillager.villager().getProfession()))
.replacement(Util.toNiceString(closestOptimizableVillager.villager.getProfession()))
.build();
final TextReplacementConfig placedMaterial = TextReplacementConfig.builder()
.matchLiteral("%blocktype%")
.replacement(Util.formatEnum(placed.getType()))
.replacement(Util.toNiceString(placed.getType()))
.build();
VillagerOptimizer.getLang(player.locale()).block_optimize_success
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedMaterial)));
@ -147,7 +147,7 @@ public class OptimizeByBlock extends VillagerOptimizerModule implements Listener
if (log_enabled) {
info(player.getName() + " optimized villager at " +
LocationUtil.toString(closestOptimizableVillager.villager().getLocation()));
LocationUtil.toString(closestOptimizableVillager.villager.getLocation()));
}
} else {
closestOptimizableVillager.sayNo();
@ -178,7 +178,7 @@ public class OptimizeByBlock extends VillagerOptimizerModule implements Listener
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), blockLoc);
if (distance >= closestDistance) continue;
final WrappedVillager wVillager = wrapperCache.get(villager);
final WrappedVillager wVillager = wrapperCache.get(villager, WrappedVillager::new);
if (wVillager.isOptimized()) {
closestOptimizedVillager = wVillager;
closestDistance = distance;
@ -200,19 +200,19 @@ public class OptimizeByBlock extends VillagerOptimizerModule implements Listener
if (notify_player) {
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
.matchLiteral("%vil_profession%")
.replacement(Util.formatEnum(closestOptimizedVillager.villager().getProfession()))
.replacement(Util.toNiceString(closestOptimizedVillager.villager.getProfession()))
.build();
final TextReplacementConfig brokenMaterial = TextReplacementConfig.builder()
.matchLiteral("%blocktype%")
.replacement(Util.formatEnum(broken.getType()))
.replacement(Util.toNiceString(broken.getType()))
.build();
VillagerOptimizer.getLang(player.locale()).block_unoptimize_success
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenMaterial)));
}
if (log_enabled) {
info(player.getName() + " unoptimized villager using " + Util.formatEnum(broken.getType()) +
LocationUtil.toString(closestOptimizedVillager.villager().getLocation()));
info(player.getName() + " unoptimized villager using " + Util.toNiceString(broken.getType()) +
LocationUtil.toString(closestOptimizedVillager.villager.getLocation()));
}
}
}

View File

@ -3,8 +3,8 @@ package me.xginko.villageroptimizer.modules.optimization;
import com.cryptomorin.xseries.XEntityType;
import com.cryptomorin.xseries.XMaterial;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
@ -14,6 +14,7 @@ import me.xginko.villageroptimizer.utils.Util;
import me.xginko.villageroptimizer.wrapper.WrappedVillager;
import net.kyori.adventure.text.TextReplacementConfig;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.entity.Villager;
import org.bukkit.event.EventHandler;
@ -85,13 +86,12 @@ public class OptimizeByNametag extends VillagerOptimizerModule implements Listen
if (!meta.hasDisplayName()) return;
final String nameTagPlainText = ChatColor.stripColor(meta.getDisplayName());
final Villager villager = (Villager) event.getRightClicked();
final WrappedVillager wVillager = wrapperCache.get(villager);
final WrappedVillager wrapped = wrapperCache.get((Villager) event.getRightClicked(), WrappedVillager::new);
if (nametags.contains(nameTagPlainText.toLowerCase())) {
if (wVillager.canOptimize(cooldown) || player.hasPermission(Permissions.Bypass.NAMETAG_COOLDOWN.get())) {
if (wrapped.canOptimize(cooldown) || player.hasPermission(Permissions.Bypass.NAMETAG_COOLDOWN.get())) {
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
wVillager,
wrapped,
OptimizationType.NAMETAG,
player,
event.isAsynchronous()
@ -99,13 +99,12 @@ public class OptimizeByNametag extends VillagerOptimizerModule implements Listen
if (!optimizeEvent.callEvent()) return;
if (!consume_nametag) {
player.getInventory().addItem(usedItem.asOne());
player.updateInventory();
}
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
wrapped.saveOptimizeTime();
wVillager.setOptimizationType(optimizeEvent.getOptimizationType());
wVillager.saveOptimizeTime();
if (!consume_nametag && player.getGameMode() == GameMode.SURVIVAL) {
player.getInventory().addItem(usedItem.asOne());
}
if (notify_player) {
VillagerOptimizer.getLang(player.locale()).nametag_optimize_success
@ -114,31 +113,35 @@ public class OptimizeByNametag extends VillagerOptimizerModule implements Listen
if (log_enabled) {
info(player.getName() + " optimized villager using nametag '" + nameTagPlainText + "' at " +
LocationUtil.toString(wVillager.villager().getLocation()));
LocationUtil.toString(wrapped.villager.getLocation()));
}
} else {
event.setCancelled(true);
wVillager.sayNo();
wrapped.sayNo();
if (notify_player) {
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
.matchLiteral("%time%")
.replacement(Util.formatDuration(Duration.ofMillis(wVillager.getOptimizeCooldownMillis(cooldown))))
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown))))
.build();
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
}
}
} else {
if (wVillager.isOptimized()) {
if (wrapped.isOptimized()) {
VillagerUnoptimizeEvent unOptimizeEvent = new VillagerUnoptimizeEvent(
wVillager,
wrapped,
player,
OptimizationType.NAMETAG,
event.isAsynchronous()
);
if (!unOptimizeEvent.callEvent()) return;
wVillager.setOptimizationType(OptimizationType.NONE);
wrapped.setOptimizationType(OptimizationType.NONE);
if (!consume_nametag && player.getGameMode() == GameMode.SURVIVAL) {
player.getInventory().addItem(usedItem.asOne());
}
if (notify_player) {
VillagerOptimizer.getLang(player.locale()).nametag_unoptimize_success
@ -147,7 +150,7 @@ public class OptimizeByNametag extends VillagerOptimizerModule implements Listen
if (log_enabled) {
info(player.getName() + " unoptimized villager using nametag '" + nameTagPlainText + "' at " +
LocationUtil.toString(wVillager.villager().getLocation()));
LocationUtil.toString(wrapped.villager.getLocation()));
}
}
}

View File

@ -1,8 +1,8 @@
package me.xginko.villageroptimizer.modules.optimization;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.enums.Permissions;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Permissions;
import me.xginko.villageroptimizer.events.VillagerOptimizeEvent;
import me.xginko.villageroptimizer.events.VillagerUnoptimizeEvent;
import me.xginko.villageroptimizer.modules.VillagerOptimizerModule;
@ -92,58 +92,62 @@ public class OptimizeByWorkstation extends VillagerOptimizerModule implements Li
}
for (Villager villager : workstationLoc.getNearbyEntitiesByType(Villager.class, search_radius)) {
if (villager.getProfession() != workstationProfession) continue;
WrappedVillager wrapped = wrapperCache.get(villager);
if (wrapped.getJobSite() == null) continue;
if (wrapped.getJobSite().getWorld().getUID() != workstationLoc.getWorld().getUID()) continue;
if (LocationUtil.relDistance3DSquared(wrapped.getJobSite(), workstationLoc) > 1) continue;
scheduling.entitySpecificScheduler(villager).run(() -> {
if (villager.getProfession() != workstationProfession) return;
WrappedVillager wrapped = wrapperCache.get(villager, WrappedVillager::new);
if (!wrapped.canOptimize(cooldown_millis) && !player.hasPermission(Permissions.Bypass.WORKSTATION_COOLDOWN.get())) {
wrapped.sayNo();
if (notify_player) {
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
.matchLiteral("%time%")
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown_millis))))
.build();
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
Location jobSite = wrapped.getJobSite();
if (jobSite == null || jobSite.getWorld().getUID() != workstationLoc.getWorld().getUID()) return;
if (LocationUtil.relDistance3DSquared(jobSite, workstationLoc) > 1) return;
if (!wrapped.canOptimize(cooldown_millis) && !player.hasPermission(Permissions.Bypass.WORKSTATION_COOLDOWN.get())) {
wrapped.sayNo();
if (notify_player) {
final TextReplacementConfig timeLeft = TextReplacementConfig.builder()
.matchLiteral("%time%")
.replacement(Util.formatDuration(Duration.ofMillis(wrapped.getOptimizeCooldownMillis(cooldown_millis))))
.build();
VillagerOptimizer.getLang(player.locale()).nametag_on_optimize_cooldown
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(timeLeft)));
}
taskComplete.set(true);
return;
}
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
wrapped,
OptimizationType.WORKSTATION,
player,
event.isAsynchronous()
);
if (!optimizeEvent.callEvent()) return;
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
wrapped.saveOptimizeTime();
if (notify_player) {
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
.matchLiteral("%vil_profession%")
.replacement(Util.toNiceString(wrapped.villager.getProfession()))
.build();
final TextReplacementConfig placedWorkstation = TextReplacementConfig.builder()
.matchLiteral("%blocktype%")
.replacement(Util.toNiceString(placed.getType()))
.build();
VillagerOptimizer.getLang(player.locale()).workstation_optimize_success
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedWorkstation)));
}
if (log_enabled) {
info(player.getName() + " optimized villager using workstation " + Util.toNiceString(placed.getType()) + " at " +
LocationUtil.toString(wrapped.villager.getLocation()));
}
taskComplete.set(true);
return;
}
VillagerOptimizeEvent optimizeEvent = new VillagerOptimizeEvent(
wrapped,
OptimizationType.WORKSTATION,
player,
event.isAsynchronous()
);
if (!optimizeEvent.callEvent()) return;
wrapped.setOptimizationType(optimizeEvent.getOptimizationType());
wrapped.saveOptimizeTime();
if (notify_player) {
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
.matchLiteral("%vil_profession%")
.replacement(Util.formatEnum(wrapped.villager().getProfession()))
.build();
final TextReplacementConfig placedWorkstation = TextReplacementConfig.builder()
.matchLiteral("%blocktype%")
.replacement(Util.formatEnum(placed.getType()))
.build();
VillagerOptimizer.getLang(player.locale()).workstation_optimize_success
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(placedWorkstation)));
}
if (log_enabled) {
info(player.getName() + " optimized villager using workstation " + Util.formatEnum(placed.getType()) + " at " +
LocationUtil.toString(wrapped.villager().getLocation()));
}
taskComplete.set(true);
return;
}, null);
}
}, 1L, 10L);
}
@ -167,7 +171,7 @@ public class OptimizeByWorkstation extends VillagerOptimizerModule implements Li
final double distance = LocationUtil.relDistance3DSquared(villager.getLocation(), workstationLoc);
if (distance >= closestDistance) continue;
WrappedVillager wrapped = wrapperCache.get(villager);
WrappedVillager wrapped = wrapperCache.get(villager, WrappedVillager::new);
if (wrapped.isOptimized()) {
closestOptimized = wrapped;
@ -191,19 +195,19 @@ public class OptimizeByWorkstation extends VillagerOptimizerModule implements Li
if (notify_player) {
final TextReplacementConfig vilProfession = TextReplacementConfig.builder()
.matchLiteral("%vil_profession%")
.replacement(Util.formatEnum(closestOptimized.villager().getProfession()))
.replacement(Util.toNiceString(closestOptimized.villager.getProfession()))
.build();
final TextReplacementConfig brokenWorkstation = TextReplacementConfig.builder()
.matchLiteral("%blocktype%")
.replacement(Util.formatEnum(broken.getType()))
.replacement(Util.toNiceString(broken.getType()))
.build();
VillagerOptimizer.getLang(player.locale()).workstation_unoptimize_success
.forEach(line -> KyoriUtil.sendMessage(player, line.replaceText(vilProfession).replaceText(brokenWorkstation)));
}
if (log_enabled) {
info(player.getName() + " unoptimized villager using workstation " + Util.formatEnum(broken.getType()) + " at " +
LocationUtil.toString(closestOptimized.villager().getLocation()));
info(player.getName() + " unoptimized villager using workstation " + Util.toNiceString(broken.getType()) + " at " +
LocationUtil.toString(closestOptimized.villager.getLocation()));
}
}
}

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.utils;
package me.xginko.villageroptimizer.struct;
public interface Disableable {
void disable();

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.utils;
package me.xginko.villageroptimizer.struct;
public interface Enableable {
void enable();

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.enums;
package me.xginko.villageroptimizer.struct.enums;
import net.kyori.adventure.key.Namespaced;
import org.bukkit.Keyed;
@ -52,7 +52,7 @@ public final class Keyring {
OPTIMIZATION_TYPE("optimization-type"),
LAST_OPTIMIZE_SYSTIME_MILLIS("last-optimize"),
LAST_LEVELUP_SYSTIME_MILLIS("last-levelup"),
LAST_RESTOCK_SYSTIME_MILLIS("last-restock");
LAST_RESTOCK_WORLD_FULLTIME("last-restock-full-time");
private final @NotNull NamespacedKey key;
@ -69,7 +69,7 @@ public final class Keyring {
public enum AntiVillagerLag implements Keyed {
NEXT_OPTIMIZATION_SYSTIME_SECONDS("cooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
LAST_RESTOCK_WORLDFULLTIME("time"), // Returns LONG -> villager.getWorld().getFullTime()
LAST_RESTOCK_WORLD_FULLTIME("time"), // Returns LONG -> villager.getWorld().getFullTime()
NEXT_LEVELUP_SYSTIME_SECONDS("levelCooldown"), // Returns LONG -> (System.currentTimeMillis() / 1000) + cooldown seconds
OPTIMIZED_ANY("Marker"), // Returns STRING -> "AVL"
OPTIMIZED_BLOCK("disabledByBlock"), // Returns STRING -> key().toString()

View File

@ -1,6 +1,8 @@
package me.xginko.villageroptimizer.enums;
package me.xginko.villageroptimizer.struct.enums;
public enum OptimizationType {
CHUNK_LIMIT,
REGIONAL_ACTIVITY,
COMMAND,
NAMETAG,
WORKSTATION,

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.enums;
package me.xginko.villageroptimizer.struct.enums;
import org.bukkit.Bukkit;
import org.bukkit.permissions.Permission;

View File

@ -0,0 +1,131 @@
package me.xginko.villageroptimizer.struct.models;
import me.xginko.villageroptimizer.VillagerOptimizer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class BlockRegion2D {
private final UUID worldUID;
private final double halfSideLength, centerX, centerZ;
/**
* A square region on a minecraft world map.
*
* @param worldUID The UUID of the world this region is in.
* @param centerX The X-axis of the center location on the map.
* @param centerZ The Z-axis of the center location on the map.
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
*/
public BlockRegion2D(UUID worldUID, double centerX, double centerZ, double halfSideLength) {
this.worldUID = worldUID;
this.centerX = centerX;
this.centerZ = centerZ;
this.halfSideLength = halfSideLength;
}
/**
* Creates a square region on a minecraft world map.
*
* @param worldUID The UUID of the world this region is in.
* @param centerX The X-axis of the center location on the map.
* @param centerZ The Z-axis of the center location on the map.
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
*/
public static BlockRegion2D of(UUID worldUID, double centerX, double centerZ, double halfSideLength) {
return new BlockRegion2D(worldUID, centerX, centerZ, halfSideLength);
}
/**
* Creates a square region on a minecraft world map.
*
* @param world The world this region is in.
* @param centerX The X-axis of the center location on the map.
* @param centerZ The Z-axis of the center location on the map.
* @param halfSideLength Half the length of the square's side. Acts like a radius would on circular regions.
*/
public static BlockRegion2D of(World world, double centerX, double centerZ, double halfSideLength) {
return BlockRegion2D.of(world.getUID(), centerX, centerZ, halfSideLength);
}
public UUID getWorldUID() {
return this.worldUID;
}
public double getHalfSideLength() {
return this.halfSideLength;
}
public double getCenterX() {
return this.centerX;
}
public double getCenterZ() {
return this.centerZ;
}
public boolean contains(Location location) {
if (!location.getWorld().getUID().equals(this.worldUID)) {
return false;
}
return location.getX() >= this.centerX - this.halfSideLength
&& location.getX() <= this.centerX + this.halfSideLength
&& location.getZ() >= this.centerZ - this.halfSideLength
&& location.getZ() <= this.centerZ + this.halfSideLength;
}
public CompletableFuture<Collection<Entity>> getEntities() {
World world = Bukkit.getWorld(worldUID);
if (world == null) {
// Only way I can imagine this happening would be if the server is using a world manager plugin and unloads
// the world during an operation.
// Since these plugins are rather common though, we will silently complete with an empty set instead of exceptionally.
return CompletableFuture.completedFuture(Collections.emptySet());
}
CompletableFuture<Collection<Entity>> future = new CompletableFuture<>();
Location centerLoc = new Location(world, centerX, world.getMinHeight(), centerZ);
VillagerOptimizer.scheduling().regionSpecificScheduler(centerLoc).run(() -> future.complete(
centerLoc.getNearbyEntities(
halfSideLength,
Math.abs(world.getMaxHeight()) + Math.abs(world.getMinHeight()), // World y can be between -64 and 320, we want everything from top to bottom
halfSideLength
)));
return future;
}
@Override
public boolean equals(Object obj) {
if (null == obj || obj.getClass() != BlockRegion2D.class)
return false;
BlockRegion2D blockRegion2D = (BlockRegion2D)obj;
return blockRegion2D.worldUID.equals(this.worldUID) && blockRegion2D.centerX == this.centerX && blockRegion2D.centerZ == this.centerZ;
}
@Override
public int hashCode() {
return Objects.hash(this.worldUID, this.centerX, this.centerZ, this.halfSideLength);
}
@Override
public String toString() {
return "BlockRegion2D{" +
" radius(half side length)=" + halfSideLength +
", centerX=" + centerX +
", centerZ=" + centerZ +
", worldUID=" + worldUID +
"}";
}
}

View File

@ -1,4 +1,4 @@
package me.xginko.villageroptimizer.utils;
package me.xginko.villageroptimizer.struct.models;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
@ -63,7 +63,7 @@ public final class ExpiringSet<E> extends AbstractSet<E> implements Set<E> {
*/
@Override
public boolean contains(Object item) {
return this.cache.getIfPresent((E) item) != null;
return this.cache.getIfPresent(item) != null;
}
/**

View File

@ -11,11 +11,11 @@ import java.util.Locale;
public class KyoriUtil {
public static void sendMessage(@NotNull CommandSender sender, @NotNull Component message) {
VillagerOptimizer.getAudiences().sender(sender).sendMessage(message);
VillagerOptimizer.audiences().sender(sender).sendMessage(message);
}
public static void sendActionBar(@NotNull CommandSender sender, @NotNull Component message) {
VillagerOptimizer.getAudiences().sender(sender).sendActionBar(message);
VillagerOptimizer.audiences().sender(sender).sendActionBar(message);
}
public static @NotNull Component toUpperCase(@NotNull Component input, @NotNull Locale locale) {

View File

@ -11,7 +11,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@ -25,7 +25,8 @@ public class Util {
static {
PL_COLOR = TextColor.color(102,255,230);
PL_STYLE = Style.style(PL_COLOR, TextDecoration.BOLD);
PROFESSION_MAP = new EnumMap<>(Material.class);
PROFESSION_MAP = new HashMap<>();
PROFESSION_MAP.put(XMaterial.LOOM.parseMaterial(), Villager.Profession.SHEPHERD);
PROFESSION_MAP.put(XMaterial.BARREL.parseMaterial(), Villager.Profession.FISHERMAN);
PROFESSION_MAP.put(XMaterial.SMOKER.parseMaterial(), Villager.Profession.BUTCHER);
@ -39,6 +40,7 @@ public class Util {
PROFESSION_MAP.put(XMaterial.SMITHING_TABLE.parseMaterial(), Villager.Profession.TOOLSMITH);
PROFESSION_MAP.put(XMaterial.FLETCHING_TABLE.parseMaterial(), Villager.Profession.FLETCHER);
PROFESSION_MAP.put(XMaterial.CARTOGRAPHY_TABLE.parseMaterial(), Villager.Profession.CARTOGRAPHER);
try {
Chunk.class.getMethod("isEntitiesLoaded");
canUseIsEntitiesLoaded = true;
@ -71,14 +73,24 @@ public class Util {
}
}
public static @NotNull String formatEnum(@NotNull Enum<?> input) {
public static @NotNull String toNiceString(@NotNull Object input) {
// Get name
String name;
if (input instanceof Enum<?>) {
name = ((Enum<?>) input).name();
} else {
name = input.toString();
}
// Turn something like "REDSTONE_TORCH" into "redstone torch"
String[] lowercaseWords = input.name().toLowerCase(Locale.ROOT).split("_");
String[] lowercaseWords = name.toLowerCase(Locale.ROOT).split("_");
// Capitalize first letter for each word
for (int i = 0; i < lowercaseWords.length; i++) {
String word = lowercaseWords[i];
// Capitalize first letter for each word
lowercaseWords[i] = word.substring(0, 1).toUpperCase() + word.substring(1);
}
// return as nice string
return String.join(" ", lowercaseWords);
}

View File

@ -1,54 +1,61 @@
package me.xginko.villageroptimizer.wrapper;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.Keyring;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Keyring;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.entity.Villager;
import org.bukkit.persistence.PersistentDataContainer;
import org.jetbrains.annotations.NotNull;
public interface VillagerDataHandler {
public abstract class PDCWrapper {
static VillagerDataHandler[] forVillager(Villager villager) {
public final Villager villager;
public final PersistentDataContainer dataContainer;
public PDCWrapper(Villager villager) {
this.villager = villager;
this.dataContainer = villager.getPersistentDataContainer();
}
public static PDCWrapper[] forVillager(Villager villager) {
if (VillagerOptimizer.config().support_other_plugins) {
return new VillagerDataHandler[]{
new MainVillagerDataHandlerImpl(villager),
new AVLVillagerDataHandlerImpl(villager)
};
return new PDCWrapper[]{new PDCWrapperVO(villager), new PDCWrapperAVL(villager)};
} else {
return new VillagerDataHandler[]{ new MainVillagerDataHandlerImpl(villager) };
return new PDCWrapper[]{new PDCWrapperVO(villager)};
}
}
/**
* @return The namespace of the handler
*/
Keyring.Space getSpace();
public abstract Keyring.Space getSpace();
/**
* @return True if the villager is optimized by plugin, otherwise false.
*/
boolean isOptimized();
public abstract boolean isOptimized();
/**
* @param cooldown_millis The configured cooldown in millis until the next optimization is allowed to occur.
* @return True if villager can be optimized again, otherwise false.
*/
boolean canOptimize(long cooldown_millis);
public abstract boolean canOptimize(long cooldown_millis);
/**
* @param type OptimizationType the villager should be set to.
*/
void setOptimizationType(OptimizationType type);
public abstract void setOptimizationType(OptimizationType type);
/**
* @return The current OptimizationType of the villager.
*/
@NotNull OptimizationType getOptimizationType();
@NotNull
public abstract OptimizationType getOptimizationType();
/**
* Saves the system time when the villager was last optimized.
*/
void saveOptimizeTime();
public abstract void saveOptimizeTime();
/**
* For convenience so the remaining millis since the last stored optimize time
@ -58,42 +65,30 @@ public interface VillagerDataHandler {
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
* @return The time left in millis until the villager can be optimized again.
*/
long getOptimizeCooldownMillis(long cooldown_millis);
public abstract long getOptimizeCooldownMillis(long cooldown_millis);
/**
* For convenience so the remaining millis since the last stored restock time
* can be easily calculated.
*
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
* @return True if the villager has been loaded long enough.
* Gets the time of the day in ticks when the entity was last restocked.
* This value is affected by /time set
* @return The time of the minecraft day (in ticks) when the villager was last restocked
*/
boolean canRestock(long cooldown_millis);
public abstract long getLastRestockFullTime();
/**
* Saves the time of when the entity was last restocked.
*/
void saveRestockTime();
/**
* For convenience so the remaining millis since the last stored restock time
* can be easily calculated.
* This enables new configured cooldowns to instantly apply instead of them being persistent.
*
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
* @return The time left in millis until the villager can be restocked again.
*/
long getRestockCooldownMillis(long cooldown_millis);
public abstract void saveRestockTime();
/**
* @param cooldown_millis The configured cooldown in milliseconds you want to check against.
* @return Whether the villager can be leveled up or not with the checked milliseconds
*/
boolean canLevelUp(long cooldown_millis);
public abstract boolean canLevelUp(long cooldown_millis);
/**
* Saves the time of the in-game world when the entity was last leveled up.
*/
void saveLastLevelUp();
public abstract void saveLastLevelUp();
/**
* Here for convenience so the remaining millis since the last stored level-up time
@ -101,5 +96,5 @@ public interface VillagerDataHandler {
*
* @return The time of the in-game world when the entity was last leveled up.
*/
long getLevelCooldownMillis(long cooldown_millis);
public abstract long getLevelCooldownMillis(long cooldown_millis);
}

View File

@ -1,23 +1,18 @@
package me.xginko.villageroptimizer.wrapper;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.Keyring;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Keyring;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.entity.Villager;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.TimeUnit;
public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
public final class PDCWrapperAVL extends PDCWrapper {
private final @NotNull Villager villager;
private final @NotNull PersistentDataContainer dataContainer;
AVLVillagerDataHandlerImpl(@NotNull Villager villager) {
this.villager = villager;
this.dataContainer = villager.getPersistentDataContainer();
PDCWrapperAVL(@NotNull Villager villager) {
super(villager);
}
@Override
@ -104,21 +99,16 @@ public class AVLVillagerDataHandlerImpl implements VillagerDataHandler {
}
@Override
public boolean canRestock(long cooldown_millis) {
return !dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG)
|| villager.getWorld().getFullTime() > dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG);
public long getLastRestockFullTime() {
if (dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG)) {
return dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG);
}
return 0L;
}
@Override
public void saveRestockTime() {
dataContainer.set(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
}
@Override
public long getRestockCooldownMillis(long cooldown_millis) {
if (dataContainer.has(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG))
return (villager.getWorld().getFullTime() - dataContainer.get(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLDFULLTIME.getKey(), PersistentDataType.LONG)) * 50L;
return cooldown_millis;
dataContainer.set(Keyring.AntiVillagerLag.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
}
@Override

View File

@ -1,21 +1,16 @@
package me.xginko.villageroptimizer.wrapper;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.enums.Keyring;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.struct.enums.Keyring;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.entity.Villager;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;
public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
public final class PDCWrapperVO extends PDCWrapper {
private final @NotNull Villager villager;
private final @NotNull PersistentDataContainer dataContainer;
MainVillagerDataHandlerImpl(@NotNull Villager villager) {
this.villager = villager;
this.dataContainer = villager.getPersistentDataContainer();
PDCWrapperVO(@NotNull Villager villager) {
super(villager);
}
@Override
@ -87,30 +82,16 @@ public class MainVillagerDataHandlerImpl implements VillagerDataHandler {
}
@Override
public boolean canRestock(long cooldown_millis) {
return getLastRestock() + cooldown_millis <= System.currentTimeMillis();
}
@Override
public void saveRestockTime() {
dataContainer.set(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG, System.currentTimeMillis());
}
/**
* @return The time when the entity was last restocked.
*/
private long getLastRestock() {
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG)) {
return dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG);
public long getLastRestockFullTime() {
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG)) {
return dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG);
}
return 0L;
}
@Override
public long getRestockCooldownMillis(long cooldown_millis) {
if (dataContainer.has(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG))
return System.currentTimeMillis() - (dataContainer.get(Keyring.VillagerOptimizer.LAST_RESTOCK_SYSTIME_MILLIS.getKey(), PersistentDataType.LONG) + cooldown_millis);
return cooldown_millis;
public void saveRestockTime() {
dataContainer.set(Keyring.VillagerOptimizer.LAST_RESTOCK_WORLD_FULLTIME.getKey(), PersistentDataType.LONG, villager.getWorld().getFullTime());
}
@Override

View File

@ -1,39 +1,54 @@
package me.xginko.villageroptimizer.wrapper;
import me.xginko.villageroptimizer.enums.Keyring;
import me.xginko.villageroptimizer.enums.OptimizationType;
import me.xginko.villageroptimizer.VillagerOptimizer;
import me.xginko.villageroptimizer.struct.enums.Keyring;
import me.xginko.villageroptimizer.struct.enums.OptimizationType;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.Villager;
import org.bukkit.entity.memory.MemoryKey;
import org.bukkit.event.entity.VillagerReplenishTradeEvent;
import org.bukkit.inventory.MerchantRecipe;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class WrappedVillager implements VillagerDataHandler {
public class WrappedVillager extends PDCWrapper {
private final @NotNull Villager villager;
private final @NotNull VillagerDataHandler[] dataHandlers;
private final @NotNull PDCWrapper[] pdcWrappers;
public WrappedVillager(@NotNull Villager villager) {
this.villager = villager;
this.dataHandlers = VillagerDataHandler.forVillager(villager);
super(villager);
this.pdcWrappers = PDCWrapper.forVillager(villager);
}
/**
* @return The villager inside the wrapper.
* Returns a number between 0 and 24000
* is affected by /time set
*/
public @NotNull Villager villager() {
return villager;
public long currentDayTimeTicks() {
return villager.getWorld().getTime();
}
/**
* Returns the tick time of the world
* is affected by /time set
*/
public long currentFullTimeTicks() {
return villager.getWorld().getFullTime();
}
/**
* Restock all trading recipes.
*/
public void restock() {
for (MerchantRecipe recipe : villager.getRecipes()) {
recipe.setUses(0);
}
VillagerOptimizer.scheduling().entitySpecificScheduler(villager).run(() -> {
for (MerchantRecipe merchantRecipe : villager.getRecipes()) {
VillagerReplenishTradeEvent restockRecipeEvent = new VillagerReplenishTradeEvent(villager, merchantRecipe);
if (restockRecipeEvent.callEvent()) {
restockRecipeEvent.getRecipe().setUses(0);
}
}
}, null);
}
/**
@ -50,7 +65,7 @@ public class WrappedVillager implements VillagerDataHandler {
}
/**
* @return true if the villager can loose his acquired profession by having their workstation destroyed.
* @return true if the villager can lose its acquired profession by having its workstation destroyed.
*/
public boolean canLooseProfession() {
// A villager with a level of 1 and no trading experience is liable to lose its profession.
@ -76,8 +91,8 @@ public class WrappedVillager implements VillagerDataHandler {
@Override
public boolean isOptimized() {
for (VillagerDataHandler handler : dataHandlers) {
if (handler.isOptimized()) {
for (PDCWrapper pdcWrapper : pdcWrappers) {
if (pdcWrapper.isOptimized()) {
return true;
}
}
@ -86,8 +101,8 @@ public class WrappedVillager implements VillagerDataHandler {
@Override
public boolean canOptimize(long cooldown_millis) {
for (VillagerDataHandler handler : dataHandlers) {
if (!handler.canOptimize(cooldown_millis)) {
for (PDCWrapper pdcWrapper : pdcWrappers) {
if (!pdcWrapper.canOptimize(cooldown_millis)) {
return false;
}
}
@ -96,18 +111,18 @@ public class WrappedVillager implements VillagerDataHandler {
@Override
public void setOptimizationType(OptimizationType type) {
for (VillagerDataHandler handler : dataHandlers) {
handler.setOptimizationType(type);
for (PDCWrapper pdcWrapper : pdcWrappers) {
pdcWrapper.setOptimizationType(type);
}
}
@Override
public @NotNull OptimizationType getOptimizationType() {
OptimizationType result = OptimizationType.NONE;
for (VillagerDataHandler handler : dataHandlers) {
OptimizationType type = handler.getOptimizationType();
for (PDCWrapper pdcWrapper : pdcWrappers) {
OptimizationType type = pdcWrapper.getOptimizationType();
if (type != OptimizationType.NONE) {
if (handler.getSpace() == Keyring.Space.VillagerOptimizer) {
if (pdcWrapper.getSpace() == Keyring.Space.VillagerOptimizer) {
return type;
} else {
result = type;
@ -119,50 +134,40 @@ public class WrappedVillager implements VillagerDataHandler {
@Override
public void saveOptimizeTime() {
for (VillagerDataHandler handler : dataHandlers) {
handler.saveOptimizeTime();
for (PDCWrapper pdcWrapper : pdcWrappers) {
pdcWrapper.saveOptimizeTime();
}
}
@Override
public long getOptimizeCooldownMillis(long cooldown_millis) {
long cooldown = 0L;
for (VillagerDataHandler handler : dataHandlers) {
cooldown = Math.max(cooldown, handler.getOptimizeCooldownMillis(cooldown_millis));
for (PDCWrapper pdcWrapper : pdcWrappers) {
cooldown = Math.max(cooldown, pdcWrapper.getOptimizeCooldownMillis(cooldown_millis));
}
return cooldown;
}
@Override
public boolean canRestock(long cooldown_millis) {
for (VillagerDataHandler handler : dataHandlers) {
if (!handler.canRestock(cooldown_millis)) {
return false;
}
public long getLastRestockFullTime() {
long cooldown = 0L;
for (PDCWrapper pdcWrapper : pdcWrappers) {
cooldown = Math.max(cooldown, pdcWrapper.getLastRestockFullTime());
}
return true;
return cooldown;
}
@Override
public void saveRestockTime() {
for (VillagerDataHandler handler : dataHandlers) {
handler.saveRestockTime();
for (PDCWrapper pdcWrapper : pdcWrappers) {
pdcWrapper.saveRestockTime();
}
}
@Override
public long getRestockCooldownMillis(long cooldown_millis) {
long cooldown = cooldown_millis;
for (VillagerDataHandler handler : dataHandlers) {
cooldown = Math.max(cooldown, handler.getRestockCooldownMillis(cooldown_millis));
}
return cooldown;
}
@Override
public boolean canLevelUp(long cooldown_millis) {
for (VillagerDataHandler handler : dataHandlers) {
if (!handler.canLevelUp(cooldown_millis)) {
for (PDCWrapper pdcWrapper : pdcWrappers) {
if (!pdcWrapper.canLevelUp(cooldown_millis)) {
return false;
}
}
@ -171,16 +176,16 @@ public class WrappedVillager implements VillagerDataHandler {
@Override
public void saveLastLevelUp() {
for (VillagerDataHandler handler : dataHandlers) {
handler.saveLastLevelUp();
for (PDCWrapper pdcWrapper : pdcWrappers) {
pdcWrapper.saveLastLevelUp();
}
}
@Override
public long getLevelCooldownMillis(long cooldown_millis) {
long cooldown = cooldown_millis;
for (VillagerDataHandler handler : dataHandlers) {
cooldown = Math.max(cooldown, handler.getLevelCooldownMillis(cooldown_millis));
for (PDCWrapper pdcWrapper : pdcWrappers) {
cooldown = Math.max(cooldown, pdcWrapper.getLevelCooldownMillis(cooldown_millis));
}
return cooldown;
}

View File

@ -1 +1 @@
me.xginko.villageroptimizer.utils.ComponentLoggerProviderImpl
me.xginko.villageroptimizer.logging.ComponentLoggerProviderImpl

View File

@ -5,6 +5,8 @@ authors: [ xGinko ]
description: ${project.description}
website: ${project.url}
api-version: '1.16'
softdepend:
- AntiVillagerLag
folia-supported: true
commands: