9
0
mirror of https://github.com/Xiao-MoMi/Custom-Crops.git synced 2026-01-03 22:26:22 +00:00
This commit is contained in:
XiaoMoMi
2024-09-15 15:39:06 +08:00
parent bd23b33f03
commit ce4c12da11
15 changed files with 168 additions and 125 deletions

View File

@@ -240,13 +240,6 @@ public abstract class BukkitCustomCropsPlugin implements CustomCropsPlugin {
return configManager;
}
/**
* Logs a debug message.
*
* @param message the message to log
*/
public abstract void debug(Object message);
/**
* Logs a debug message using a {@link Supplier}.
*

View File

@@ -57,7 +57,8 @@ public abstract class AbstractActionManager<T> implements ActionManager<T> {
this.registerHologramAction();
this.registerPlantAction();
this.registerBreakAction();
this.registerSpawnEntity();
this.registerSpawnEntityAction();
this.registerVariationAction();
}
@Override
@@ -308,7 +309,7 @@ public abstract class AbstractActionManager<T> implements ActionManager<T> {
this.registerAction((args, chance) -> new ActionBreak<>(plugin, args, chance), "break");
}
protected void registerSpawnEntity() {
protected void registerSpawnEntityAction() {
this.registerAction((args, chance) -> {
if (args instanceof Section section) {
return new ActionSpawnEntity<>(plugin, section, chance);
@@ -318,4 +319,15 @@ public abstract class AbstractActionManager<T> implements ActionManager<T> {
}
}, "spawn-entity", "spawn-mob");
}
protected void registerVariationAction() {
this.registerAction((args, chance) -> {
if (args instanceof Section section) {
return new ActionVariation<>(plugin, section, chance);
} else {
plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at spawn-entity action which is expected to be `Section`");
return Action.empty();
}
}, "variation");
}
}

View File

@@ -49,7 +49,7 @@ public class ActionBreak<T> extends AbstractBuiltInAction<T> {
double chance
) {
super(plugin, chance);
this.triggerEvent = (boolean) args;
this.triggerEvent = Optional.ofNullable(args).map(it -> (boolean) it).orElse(true);
}
@Override

View File

@@ -0,0 +1,124 @@
/*
* Copyright (C) <2024> <XiaoMoMi>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package net.momirealms.customcrops.api.action.builtin;
import dev.dejvokep.boostedyaml.block.implementation.Section;
import net.momirealms.customcrops.api.BukkitCustomCropsPlugin;
import net.momirealms.customcrops.api.context.Context;
import net.momirealms.customcrops.api.context.ContextKeys;
import net.momirealms.customcrops.api.core.BuiltInBlockMechanics;
import net.momirealms.customcrops.api.core.CustomForm;
import net.momirealms.customcrops.api.core.ExistenceForm;
import net.momirealms.customcrops.api.core.FurnitureRotation;
import net.momirealms.customcrops.api.core.block.CropBlock;
import net.momirealms.customcrops.api.core.block.PotBlock;
import net.momirealms.customcrops.api.core.mechanic.crop.VariationData;
import net.momirealms.customcrops.api.core.mechanic.fertilizer.Fertilizer;
import net.momirealms.customcrops.api.core.mechanic.fertilizer.FertilizerConfig;
import net.momirealms.customcrops.api.core.world.CustomCropsBlockState;
import net.momirealms.customcrops.api.core.world.CustomCropsWorld;
import net.momirealms.customcrops.api.core.world.Pos3;
import org.bukkit.Location;
import java.util.*;
import static java.util.Objects.requireNonNull;
public class ActionVariation<T> extends AbstractBuiltInAction<T> {
private final VariationData[] variations;
private final boolean ignore;
public ActionVariation(
BukkitCustomCropsPlugin plugin,
Section section,
double chance
) {
super(plugin, chance);
ignore = section.getBoolean("ignore-fertilizer", false);
List<VariationData> variationDataList = new ArrayList<>();
for (Map.Entry<String, Object> entry : section.getStringRouteMappedValues(false).entrySet()) {
if (entry.getValue() instanceof Section inner) {
VariationData variationData = new VariationData(
inner.getString("item"),
CustomForm.valueOf(inner.getString("type", "BLOCK").toUpperCase(Locale.ENGLISH)).existenceForm(),
inner.getDouble("chance")
);
variationDataList.add(variationData);
}
}
variations = variationDataList.toArray(new VariationData[0]);
}
@Override
protected void triggerAction(Context<T> context) {
Fertilizer[] fertilizers = null;
Location location = requireNonNull(context.arg(ContextKeys.LOCATION));
Optional<CustomCropsWorld<?>> world = plugin.getWorldManager().getWorld(location.getWorld());
if (world.isEmpty()) {
return;
}
Pos3 pos3 = Pos3.from(location);
if (context.holder() instanceof CustomCropsBlockState state) {
if (!(state.type() instanceof CropBlock)) {
return;
}
} else {
Optional<CustomCropsBlockState> cropBlockState = world.get().getBlockState(pos3);
if (cropBlockState.isEmpty() || !(cropBlockState.get().type() instanceof CropBlock)) {
return;
}
}
if (!ignoreFertilizers()) {
Pos3 potLocation = pos3.add(0, -1, 0);
Optional<CustomCropsBlockState> optionalState = world.get().getBlockState(potLocation);
if (optionalState.isPresent()) {
if (optionalState.get().type() instanceof PotBlock potBlock) {
fertilizers = potBlock.fertilizers(optionalState.get());
}
}
}
ArrayList<FertilizerConfig> configs = new ArrayList<>();
if (fertilizers != null) {
for (Fertilizer fertilizer : fertilizers) {
Optional.ofNullable(fertilizer.config()).ifPresent(configs::add);
}
}
for (VariationData variationData : variations()) {
double variationChance = variationData.chance();
for (FertilizerConfig fertilizer : configs) {
variationChance = fertilizer.processVariationChance(variationChance);
}
if (Math.random() < variationChance) {
plugin.getItemManager().remove(location, ExistenceForm.ANY);
world.get().removeBlockState(pos3);
plugin.getItemManager().place(location, variationData.existenceForm(), variationData.id(), FurnitureRotation.random());
((CropBlock) BuiltInBlockMechanics.CROP.mechanic()).fixOrGetState(world.get(), pos3, variationData.id());
break;
}
}
}
public VariationData[] variations() {
return variations;
}
public boolean ignoreFertilizers() {
return ignore;
}
}

View File

@@ -139,7 +139,8 @@ public class WateringCanItem extends AbstractCustomCropsItem {
int water = getCurrentWater(itemInHand);
String blockID = BukkitCustomCropsPlugin.getInstance().getItemManager().blockID(targetBlock);
BukkitCustomCropsPlugin.getInstance().debug(blockID);
String finalBlockID = blockID;
BukkitCustomCropsPlugin.getInstance().debug(() -> finalBlockID);
for (FillMethod method : config.fillMethods()) {
if (method.getID().equals(blockID)) {
@@ -340,7 +341,8 @@ public class WateringCanItem extends AbstractCustomCropsItem {
// for old config compatibility
context.updateLocation(new Location(player.getWorld(), vector.getX() - 0.5,vector.getY() - 1, vector.getZ() - 0.5));
String blockID = BukkitCustomCropsPlugin.getInstance().getItemManager().blockID(targetBlock);
BukkitCustomCropsPlugin.getInstance().debug(blockID);
String finalBlockID = blockID;
BukkitCustomCropsPlugin.getInstance().debug(() -> finalBlockID);
for (FillMethod method : wateringCanConfig.fillMethods()) {
if (method.getID().equals(blockID)) {

View File

@@ -209,7 +209,7 @@ public class CustomCropsWorldImpl<W> implements CustomCropsWorld<W> {
this.adaptor.saveRegion(this, region);
}
long time2 = System.currentTimeMillis();
BukkitCustomCropsPlugin.getInstance().debug("Took " + (time2-time1) + "ms to save world " + worldName + ". Saved " + (lazyChunks.size() + loadedChunks.size()) + " chunks.");
BukkitCustomCropsPlugin.getInstance().debug(() -> "Took " + (time2-time1) + "ms to save world " + worldName + ". Saved " + (lazyChunks.size() + loadedChunks.size()) + " chunks.");
}
@Override
@@ -346,7 +346,7 @@ public class CustomCropsWorldImpl<W> implements CustomCropsWorld<W> {
public boolean loadChunk(CustomCropsChunk chunk) {
Optional<CustomCropsChunk> previousChunk = getLoadedChunk(chunk.chunkPos());
if (previousChunk.isPresent()) {
BukkitCustomCropsPlugin.getInstance().debug("Chunk " + chunk.chunkPos() + " already loaded.");
BukkitCustomCropsPlugin.getInstance().debug(() -> "Chunk " + chunk.chunkPos() + " already loaded.");
if (previousChunk.get() != chunk) {
BukkitCustomCropsPlugin.getInstance().getPluginLogger().severe("Failed to load the chunk. There is already a different chunk instance with the same coordinates in the cache. " + chunk.chunkPos());
return false;
@@ -447,7 +447,7 @@ public class CustomCropsWorldImpl<W> implements CustomCropsWorld<W> {
public boolean loadRegion(CustomCropsRegion region) {
Optional<CustomCropsRegion> previousRegion = getLoadedRegion(region.regionPos());
if (previousRegion.isPresent()) {
BukkitCustomCropsPlugin.getInstance().debug("Region " + region.regionPos() + " already loaded.");
BukkitCustomCropsPlugin.getInstance().debug(() -> "Region " + region.regionPos() + " already loaded.");
if (previousRegion.get() != region) {
BukkitCustomCropsPlugin.getInstance().getPluginLogger().severe("Failed to load the region. There is already a different region instance with the same coordinates in the cache. " + region.regionPos());
return false;

View File

@@ -132,7 +132,7 @@ public class SlimeWorldAdaptorR1 extends AbstractWorldAdaptor<SlimeWorld> {
}
CustomCropsChunk chunk = tagToChunk(world, chunkCompoundTag.get());
long time2 = System.currentTimeMillis();
BukkitCustomCropsPlugin.getInstance().debug("Took " + (time2-time1) + "ms to load chunk " + pos);
BukkitCustomCropsPlugin.getInstance().debug(() -> "Took " + (time2-time1) + "ms to load chunk " + pos);
return chunk;
}

View File

@@ -89,7 +89,7 @@ public class WorldEditListener implements Reloadable, Listener {
try {
event.setExtent(new CustomCropsDelegateExtent(event));
} catch (Exception e) {
BukkitCustomCropsPlugin.getInstance().debug(e.getMessage());
BukkitCustomCropsPlugin.getInstance().debug(e::getMessage);
}
}

View File

@@ -1,6 +1,6 @@
# Project settings
# Rule: [major update].[feature update].[bug fix]
project_version=3.6.9
project_version=3.6.10
config_version=40
project_group=net.momirealms

View File

@@ -91,11 +91,6 @@ public class BukkitCustomCropsPluginImpl extends BukkitCustomCropsPlugin {
this.registryAccess = SimpleRegistryAccess.getInstance();
}
@Override
public void debug(Object message) {
this.debugger.accept(message::toString);
}
@Override
public void debug(Supplier<String> message) {
this.debugger.accept(message);
@@ -224,7 +219,7 @@ public class BukkitCustomCropsPluginImpl extends BukkitCustomCropsPlugin {
this.placeholderManager.reload();
this.configManager.reload();
this.debugger = ConfigManager.debug() ? (s) -> logger.info("[DEBUG] " + s.toString()) : (s) -> {};
this.debugger = ConfigManager.debug() ? (s) -> logger.info("[DEBUG] " + s.get()) : (s) -> {};
this.coolDownManager.reload();
this.translationManager.reload();
this.hologramManager.reload();

View File

@@ -17,28 +17,9 @@
package net.momirealms.customcrops.bukkit.action;
import dev.dejvokep.boostedyaml.block.implementation.Section;
import net.momirealms.customcrops.api.BukkitCustomCropsPlugin;
import net.momirealms.customcrops.api.action.AbstractActionManager;
import net.momirealms.customcrops.api.action.Action;
import net.momirealms.customcrops.api.context.ContextKeys;
import net.momirealms.customcrops.api.core.CustomForm;
import net.momirealms.customcrops.api.core.ExistenceForm;
import net.momirealms.customcrops.api.core.FurnitureRotation;
import net.momirealms.customcrops.api.core.block.CropBlock;
import net.momirealms.customcrops.api.core.block.PotBlock;
import net.momirealms.customcrops.api.core.mechanic.crop.VariationData;
import net.momirealms.customcrops.api.core.mechanic.fertilizer.Fertilizer;
import net.momirealms.customcrops.api.core.mechanic.fertilizer.FertilizerConfig;
import net.momirealms.customcrops.api.core.world.CustomCropsBlockState;
import net.momirealms.customcrops.api.core.world.CustomCropsChunk;
import net.momirealms.customcrops.api.core.world.CustomCropsWorld;
import net.momirealms.customcrops.api.core.world.Pos3;
import org.bukkit.Location;
import java.util.*;
import static java.util.Objects.requireNonNull;
public class BlockActionManager extends AbstractActionManager<CustomCropsBlockState> {
@@ -55,73 +36,5 @@ public class BlockActionManager extends AbstractActionManager<CustomCropsBlockSt
protected void registerBuiltInActions() {
super.registerBuiltInActions();
super.registerBundleAction(CustomCropsBlockState.class);
this.registerVariationAction();
}
private void registerVariationAction() {
registerAction((args, chance) -> {
if (args instanceof Section section) {
boolean ignore = section.getBoolean("ignore-fertilizer", false);
List<VariationData> variationDataList = new ArrayList<>();
for (Map.Entry<String, Object> entry : section.getStringRouteMappedValues(false).entrySet()) {
if (entry.getValue() instanceof Section inner) {
VariationData variationData = new VariationData(
inner.getString("item"),
CustomForm.valueOf(inner.getString("type", "BLOCK").toUpperCase(Locale.ENGLISH)).existenceForm(),
inner.getDouble("chance")
);
variationDataList.add(variationData);
}
}
VariationData[] variations = variationDataList.toArray(new VariationData[0]);
return context -> {
if (Math.random() > chance) return;
if (!(context.holder().type() instanceof CropBlock cropBlock)) {
return;
}
Fertilizer[] fertilizers = null;
Location location = requireNonNull(context.arg(ContextKeys.LOCATION));
Optional<CustomCropsWorld<?>> world = plugin.getWorldManager().getWorld(location.getWorld());
if (world.isEmpty()) {
return;
}
Pos3 pos3 = Pos3.from(location);
if (!ignore) {
Pos3 potLocation = pos3.add(0, -1, 0);
Optional<CustomCropsChunk> chunk = world.get().getChunk(potLocation.toChunkPos());
if (chunk.isPresent()) {
Optional<CustomCropsBlockState> state = chunk.get().getBlockState(potLocation);
if (state.isPresent()) {
if (state.get().type() instanceof PotBlock potBlock) {
fertilizers = potBlock.fertilizers(state.get());
}
}
}
}
ArrayList<FertilizerConfig> configs = new ArrayList<>();
if (fertilizers != null) {
for (Fertilizer fertilizer : fertilizers) {
Optional.ofNullable(fertilizer.config()).ifPresent(configs::add);
}
}
for (VariationData variationData : variations) {
double variationChance = variationData.chance();
for (FertilizerConfig fertilizer : configs) {
variationChance = fertilizer.processVariationChance(variationChance);
}
if (Math.random() < variationChance) {
plugin.getItemManager().remove(location, ExistenceForm.ANY);
world.get().removeBlockState(pos3);
plugin.getItemManager().place(location, variationData.existenceForm(), variationData.id(), FurnitureRotation.random());
cropBlock.fixOrGetState(world.get(), pos3, variationData.id());
break;
}
}
};
} else {
plugin.getPluginLogger().warn("Invalid value type: " + args.getClass().getSimpleName() + " found at variation action which is expected to be `Section`");
return Action.empty();
}
}, "variation");
}
}

View File

@@ -290,14 +290,18 @@ public class PlayerActionManager extends AbstractActionManager<Player> {
registerAction((args, chance) -> {
if (args instanceof Section section) {
String id = section.getString("item");
if (id == null) {
id = section.getString("id");
}
String finalID = id;
int amount = section.getInt("amount", 1);
boolean toInventory = section.getBoolean("to-inventory", false);
return context -> {
if (Math.random() > chance) return;
Player player = context.holder();
if (player == null) return;
ItemStack itemStack = plugin.getItemManager().build(context.holder(), id);
if (itemStack != null) {
ItemStack itemStack = plugin.getItemManager().build(context.holder(), finalID);
if (itemStack != null && itemStack.getType() != Material.AIR) {
int maxStack = itemStack.getMaxStackSize();
int amountToGive = amount;
while (amountToGive > 0) {

View File

@@ -98,11 +98,11 @@ public class BukkitConfigManager extends ConfigManager {
}
this.loadSettings();
this.loadConfigs();
plugin.debug("Loaded " + Registries.CROP.size() + " crops");
plugin.debug("Loaded " + Registries.SPRINKLER.size() + " sprinklers");
plugin.debug("Loaded " + Registries.WATERING_CAN.size() + " watering-cans");
plugin.debug("Loaded " + Registries.POT.size() + " pots");
plugin.debug("Loaded " + Registries.FERTILIZER.size() + " fertilizers");
plugin.debug(() -> "Loaded " + Registries.CROP.size() + " crops");
plugin.debug(() -> "Loaded " + Registries.SPRINKLER.size() + " sprinklers");
plugin.debug(() -> "Loaded " + Registries.WATERING_CAN.size() + " watering-cans");
plugin.debug(() -> "Loaded " + Registries.POT.size() + " pots");
plugin.debug(() -> "Loaded " + Registries.FERTILIZER.size() + " fertilizers");
}
private void loadSettings() {

View File

@@ -171,7 +171,7 @@ public class BukkitWorldAdaptor extends AbstractWorldAdaptor<World> {
CustomCropsChunk chunk = deserializeChunk(world, dataStream);
dataStream.close();
long time2 = System.currentTimeMillis();
BukkitCustomCropsPlugin.getInstance().debug("[" + world.worldName() + "] Took " + (time2-time1) + "ms to load chunk " + pos + " from cached region");
BukkitCustomCropsPlugin.getInstance().debug(() -> "[" + world.worldName() + "] Took " + (time2-time1) + "ms to load chunk " + pos + " from cached region");
return chunk;
} catch (IOException e) {
BukkitCustomCropsPlugin.getInstance().getPluginLogger().severe("[" + world.worldName() + "] Failed to load CustomCrops data at " + pos, e);
@@ -198,7 +198,7 @@ public class BukkitWorldAdaptor extends AbstractWorldAdaptor<World> {
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
bos.write(serializeRegion(region));
long time2 = System.currentTimeMillis();
BukkitCustomCropsPlugin.getInstance().debug("[" + world.worldName() + "] Took " + (time2-time1) + "ms to save region " + region.regionPos());
BukkitCustomCropsPlugin.getInstance().debug(() -> "[" + world.worldName() + "] Took " + (time2-time1) + "ms to save region " + region.regionPos());
} catch (IOException e) {
BukkitCustomCropsPlugin.getInstance().getPluginLogger().severe("[" + world.worldName() + "] Failed to save CustomCrops region data." + region.regionPos(), e);
}

View File

@@ -92,9 +92,9 @@ public class BukkitItemManager extends AbstractItemManager {
public void load() {
this.resetItemDetectionOrder();
for (ItemProvider provider : itemProviders.values()) {
plugin.debug("Registered ItemProvider: " + provider.identifier());
plugin.debug(() -> "Registered ItemProvider: " + provider.identifier());
}
plugin.debug("Item order: " + Arrays.toString(Arrays.stream(itemDetectArray).map(ExternalProvider::identifier).toList().toArray(new String[0])));
plugin.debug(() -> "Item order: " + Arrays.toString(Arrays.stream(itemDetectArray).map(ExternalProvider::identifier).toList().toArray(new String[0])));
}
@Override
@@ -105,14 +105,14 @@ public class BukkitItemManager extends AbstractItemManager {
}
this.eventListener = listener;
Bukkit.getPluginManager().registerEvents(this.eventListener, plugin.getBootstrap());
plugin.debug("Custom event listener set to " + listener.getClass().getName());
plugin.debug(() -> "Custom event listener set to " + listener.getClass().getName());
}
@Override
public void setCustomItemProvider(@NotNull CustomItemProvider provider) {
Objects.requireNonNull(provider, "provider cannot be null");
this.provider = provider;
plugin.debug("Custom item provider set to " + provider.getClass().getName());
plugin.debug(() -> "Custom item provider set to " + provider.getClass().getName());
}
public boolean registerItemProvider(ItemProvider item) {
@@ -382,7 +382,7 @@ public class BukkitItemManager extends AbstractItemManager {
ItemMeta previousMeta = itemStack.getItemMeta().clone();
PlayerItemDamageEvent itemDamageEvent = new PlayerItemDamageEvent(player, itemStack, amount);
if (EventUtils.fireAndCheckCancel(itemDamageEvent)) {
plugin.debug("Another plugin modified the item from `PlayerItemDamageEvent` called by CustomCrops");
plugin.debug(() -> "Another plugin modified the item from `PlayerItemDamageEvent` called by CustomCrops");
return;
}
if (!itemStack.getItemMeta().equals(previousMeta)) {