Skip to content

Commit

Permalink
upgrade where possible
Browse files Browse the repository at this point in the history
  • Loading branch information
xGinko committed Nov 3, 2024
1 parent 1217f4e commit cdbb9a9
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 133 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>me.xginko</groupId>
<artifactId>SnowballFight</artifactId>
<version>1.3.0</version>
<version>1.3.1</version>
<packaging>jar</packaging>

<name>SnowballFight</name>
Expand Down
42 changes: 12 additions & 30 deletions src/main/java/me/xginko/snowballfight/SnowballConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import com.google.common.collect.ImmutableList;
import io.github.thatsmusic99.configurationmaster.api.ConfigFile;
import me.xginko.snowballfight.utils.Util;
import org.bukkit.Color;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.nio.file.Files;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
Expand All @@ -15,18 +17,16 @@
public final class SnowballConfig {

private final @NotNull ConfigFile configFile;

public final @NotNull List<Color> colors;
public final @NotNull Duration cacheDuration;
public final @NotNull Duration snowballCacheDuration;

SnowballConfig() throws Exception {
// Create plugin folder first if it does not exist yet
File pluginFolder = SnowballFight.getInstance().getDataFolder();
if (!pluginFolder.exists() && !pluginFolder.mkdir())
SnowballFight.logger().error("Failed to create plugin folder.");
// Load config.yml with ConfigMaster
Files.createDirectories(pluginFolder.toPath());
this.configFile = ConfigFile.loadConfig(new File(pluginFolder, "config.yml"));

this.cacheDuration = Duration.ofSeconds(getInt("settings.cache-keep-seconds", 20,
this.snowballCacheDuration = Duration.ofSeconds(getInt("settings.snowball-cache-seconds", 20,
"Don't touch unless you know what you're doing."));

final List<String> defaults = Arrays.asList(
Expand All @@ -41,43 +41,25 @@ public final class SnowballConfig {
this.colors = getList("settings.colors", defaults,
"You need to configure at least 1 color. Format: 'B3E3F4' or '#B3E3F4'")
.stream()
.distinct()
.map(hexString -> {
try {
final String parseable = hexString.replace("#", "");
return Color.fromRGB(
Integer.parseInt(parseable.substring(0, 2), 16),
Integer.parseInt(parseable.substring(2, 4), 16),
Integer.parseInt(parseable.substring(4, 6), 16)
);
return Util.colorFromHexString(hexString);
} catch (NumberFormatException e) {
SnowballFight.logger().warn("Could not parse color '{}'. Is it formatted correctly?", hexString);
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.collectingAndThen(Collectors.toList(), collected -> {
if (collected.isEmpty()) {
collected.addAll(defaults.stream()
.map(string -> {
try {
return Color.fromRGB(
Integer.parseInt(string.substring(0, 2), 16),
Integer.parseInt(string.substring(2, 4), 16),
Integer.parseInt(string.substring(4, 6), 16));
} catch (Exception e) {
return Color.WHITE;
}
})
.distinct()
.collect(Collectors.toList()));
}
if (collected.isEmpty())
collected.addAll(defaults.stream().map(Util::colorFromHexString).collect(Collectors.toList()));
return ImmutableList.copyOf(collected);
}));
structure();

setStructure();
}

public void structure() {
public void setStructure() {
configFile.addDefault("settings.cooldown", null);
configFile.addDefault("settings.infinite-snowballs", null);
configFile.addDefault("settings.damage", null);
Expand Down
21 changes: 5 additions & 16 deletions src/main/java/me/xginko/snowballfight/SnowballFight.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package me.xginko.snowballfight;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import me.xginko.snowballfight.commands.snowballs.SnowballsCommand;
import me.xginko.snowballfight.modules.SnowballModule;
import me.xginko.snowballfight.utils.Util;
Expand All @@ -14,25 +12,21 @@
import space.arim.morepaperlib.scheduling.GracefulScheduling;

import java.util.Objects;
import java.util.Random;
import java.util.UUID;

public final class SnowballFight extends JavaPlugin {

private static SnowballFight instance;
private static Cache<UUID, WrappedSnowball> snowballs;
private static SnowballTracker snowballs;
private static SnowballConfig config;
private static BukkitAudiences audiences;
private static GracefulScheduling scheduling;
private static ComponentLogger logger;
private static Random random;
private static Metrics metrics;
private static boolean isServerFolia;

@Override
public void onEnable() {
instance = this;
random = new Random();
audiences = BukkitAudiences.create(instance);
scheduling = new MorePaperLib(instance).scheduling();
logger = ComponentLogger.logger(getLogger().getName());
Expand Down Expand Up @@ -68,24 +62,23 @@ public void onDisable() {
metrics = null;
}
scheduling = null;
snowballs = null;
instance = null;
random = null;
logger = null;
config = null;
snowballs = null;
}

public void disableRunningTasks() {
SnowballModule.disableAll();
if (scheduling != null) scheduling.cancelGlobalTasks();
if (snowballs != null) snowballs.cleanUp();
if (snowballs != null) snowballs.disable();
}

public void reloadConfiguration() {
try {
disableRunningTasks();
config = new SnowballConfig();
snowballs = Caffeine.newBuilder().expireAfterWrite(config.cacheDuration).build();
snowballs = new SnowballTracker(instance, config.snowballCacheDuration);
SnowballModule.reloadModules();
config.saveConfig();
} catch (Throwable e) {
Expand All @@ -97,7 +90,7 @@ public static SnowballFight getInstance() {
return instance;
}

public static Cache<UUID, WrappedSnowball> snowballs() {
public static SnowballTracker snowballs() {
return snowballs;
}

Expand All @@ -117,10 +110,6 @@ public static ComponentLogger logger() {
return logger;
}

public static Random getRandom() {
return random;
}

public static boolean isServerFolia() {
return isServerFolia;
}
Expand Down
45 changes: 45 additions & 0 deletions src/main/java/me/xginko/snowballfight/SnowballTracker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package me.xginko.snowballfight;

import com.destroystokyo.paper.event.entity.EntityRemoveFromWorldEvent;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import me.xginko.snowballfight.utils.Disableable;
import org.bukkit.entity.Snowball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.jetbrains.annotations.NotNull;

import java.time.Duration;
import java.util.UUID;

public final class SnowballTracker implements Disableable, Listener {

private final @NotNull Cache<UUID, WrappedSnowball> snowballCache;

SnowballTracker(@NotNull SnowballFight plugin, @NotNull Duration duration) {
this.snowballCache = Caffeine.newBuilder().expireAfterWrite(duration).build();
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}

@Override
public void disable() {
HandlerList.unregisterAll(this);
snowballCache.invalidateAll();
snowballCache.cleanUp();
}

@EventHandler(priority = EventPriority.MONITOR)
private void onEntityRemoveFromWorld(EntityRemoveFromWorldEvent event) {
snowballCache.invalidate(event.getEntity().getUniqueId());
}

public WrappedSnowball get(@NotNull Snowball snowball) {
return snowballCache.get(snowball.getUniqueId(), uuid -> new WrappedSnowball(snowball));
}

public boolean contains(@NotNull UUID uuid) {
return snowballCache.getIfPresent(uuid) != null;
}
}
16 changes: 6 additions & 10 deletions src/main/java/me/xginko/snowballfight/WrappedSnowball.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package me.xginko.snowballfight;

import me.xginko.snowballfight.utils.Util;
import org.bukkit.Color;
import org.bukkit.entity.Snowball;
import org.jetbrains.annotations.NotNull;

public final class WrappedSnowball {

private final @NotNull Snowball snowball;
public final @NotNull Snowball snowball;
private @NotNull Color primaryColor, secondaryColor;

public WrappedSnowball(@NotNull Snowball snowball) {
Expand All @@ -15,17 +16,12 @@ public WrappedSnowball(@NotNull Snowball snowball) {
if (config.colors.size() == 1) {
this.primaryColor = this.secondaryColor = config.colors.get(0);
} else {
this.primaryColor = config.colors.get(SnowballFight.getRandom().nextInt(config.colors.size()));
do {
this.secondaryColor = config.colors.get(SnowballFight.getRandom().nextInt(config.colors.size()));
} while (primaryColor == secondaryColor);
this.primaryColor = config.colors.get(Util.RANDOM.nextInt(config.colors.size()));
do this.secondaryColor = config.colors.get(Util.RANDOM.nextInt(config.colors.size()));
while (primaryColor == secondaryColor);
}
}

public @NotNull Snowball snowball() {
return snowball;
}

public @NotNull Color getPrimaryColor() {
return primaryColor;
}
Expand All @@ -41,4 +37,4 @@ public void setPrimaryColor(@NotNull Color primaryColor) {
public void setSecondaryColor(@NotNull Color secondaryColor) {
this.secondaryColor = secondaryColor;
}
}
}
53 changes: 19 additions & 34 deletions src/main/java/me/xginko/snowballfight/modules/ExplodeOnHit.java
Original file line number Diff line number Diff line change
Expand Up @@ -99,46 +99,31 @@ private void onProjectileHit(ProjectileHitEvent event) {

if (!preSnowballExplodeEvent.callEvent()) return;

final Location explodeLoc = preSnowballExplodeEvent.getExplodeLocation();
final Snowball snowball = preSnowballExplodeEvent.getSnowball();
final Location explodeLoc = preSnowballExplodeEvent.getExplodeLocation();

if (SnowballFight.isServerFolia()) {
SnowballFight.scheduling().regionSpecificScheduler(explodeLoc).run(() -> {
new PostSnowballExplodeEvent(
preSnowballExplodeEvent.getSnowball(),
preSnowballExplodeEvent.getHitEntity(),
PostSnowballExplodeEvent postSnowballExplodeEvent = new PostSnowballExplodeEvent(
preSnowballExplodeEvent.getSnowball(),
preSnowballExplodeEvent.getHitEntity(),
explodeLoc,
preSnowballExplodeEvent.getExplosionPower(),
preSnowballExplodeEvent.willSetFire(),
preSnowballExplodeEvent.willBreakBlocks(),
explodeLoc.getWorld().createExplosion(
// Set explode source for damage tracking
snowball.getShooter() instanceof LivingEntity ? (LivingEntity) snowball.getShooter() : snowball,
explodeLoc,
preSnowballExplodeEvent.getExplosionPower(),
preSnowballExplodeEvent.willSetFire(),
preSnowballExplodeEvent.willBreakBlocks(),
explodeLoc.getWorld().createExplosion(
// Set explode source for damage tracking
snowball.getShooter() instanceof LivingEntity ? (LivingEntity) snowball.getShooter() : snowball,
explodeLoc,
preSnowballExplodeEvent.getExplosionPower(),
preSnowballExplodeEvent.willSetFire(),
preSnowballExplodeEvent.willBreakBlocks()
),
false
).callEvent();
});
preSnowballExplodeEvent.willBreakBlocks()
),
event.isAsynchronous()
);

if (SnowballFight.isServerFolia()) {
SnowballFight.scheduling().regionSpecificScheduler(explodeLoc).run(postSnowballExplodeEvent::callEvent);
} else {
new PostSnowballExplodeEvent(
preSnowballExplodeEvent.getSnowball(),
preSnowballExplodeEvent.getHitEntity(),
explodeLoc,
preSnowballExplodeEvent.getExplosionPower(),
preSnowballExplodeEvent.willSetFire(),
preSnowballExplodeEvent.willBreakBlocks(),
explodeLoc.getWorld().createExplosion(
snowball.getShooter() instanceof LivingEntity ? (LivingEntity) snowball.getShooter() : snowball,
explodeLoc,
preSnowballExplodeEvent.getExplosionPower(),
preSnowballExplodeEvent.willSetFire(),
preSnowballExplodeEvent.willBreakBlocks()
),
event.isAsynchronous()
).callEvent();
postSnowballExplodeEvent.callEvent();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.google.common.collect.ImmutableList;
import me.xginko.snowballfight.SnowballFight;
import me.xginko.snowballfight.WrappedSnowball;
import me.xginko.snowballfight.utils.Util;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.block.Block;
Expand Down Expand Up @@ -157,10 +158,10 @@ private void detonateFirework(final Location explosionLoc, final Snowball snowba
effectFireworks.add(firework.getUniqueId()); // Cache uuid to cancel damage/knockback by fireworks
FireworkMeta meta = firework.getFireworkMeta();
meta.clearEffects();
WrappedSnowball wrappedSnowball = SnowballFight.snowballs().get(snowball.getUniqueId(), k -> new WrappedSnowball(snowball));
WrappedSnowball wrappedSnowball = SnowballFight.snowballs().get(snowball);
meta.addEffect(FireworkEffect.builder()
.withColor(wrappedSnowball.getPrimaryColor(), wrappedSnowball.getSecondaryColor())
.with(effectTypes.get(SnowballFight.getRandom().nextInt(effectTypes.size())))
.with(effectTypes.get(Util.RANDOM.nextInt(effectTypes.size())))
.flicker(flicker)
.trail(trail)
.build());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.cryptomorin.xseries.XEntityType;
import me.xginko.snowballfight.SnowballFight;
import me.xginko.snowballfight.utils.Util;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
Expand Down Expand Up @@ -75,7 +76,7 @@ public void disable() {
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
private void onProjectileHit(ProjectileHitEvent event) {
if (event.getEntityType() != XEntityType.SNOWBALL.get()) return;
if (probability < 1.0 && SnowballFight.getRandom().nextDouble() > probability) return;
if (probability < 1.0 && Util.RANDOM.nextDouble() > probability) return;

final Entity hitEntity = event.getHitEntity();
if (onlyForEntities) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private void onProjectileHit(ProjectileHitEvent event) {

final LivingEntity living = (LivingEntity) event.getHitEntity();
if (onlyForSpecificEntities && (asBlacklist == configuredTypes.contains(living.getType()))) return;
if (probability < 1.0 && SnowballFight.getRandom().nextDouble() > probability) return;
if (probability < 1.0 && Util.RANDOM.nextDouble() > probability) return;

if (onlyPlayers && !(event.getEntity().getShooter() instanceof Player)) return;

Expand Down
Loading

0 comments on commit cdbb9a9

Please sign in to comment.