Mod GastinelClaims : /claim, /unclaim, /friend (NeoForge 1.21.1, serveur seul)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
révision
f7ea72ed99
20 fichiers modifiés
+1267
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,197 @@
|
||||
package com.gastinelclaims;
|
||||
|
||||
import com.gastinelclaims.core.ChunkKey;
|
||||
import com.gastinelclaims.core.ClaimRegistry;
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import com.mojang.brigadier.CommandDispatcher;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import net.minecraft.commands.CommandSourceStack;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.minecraft.commands.SharedSuggestionProvider;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.event.RegisterCommandsEvent;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/** /claim, /claim info, /unclaim, /friend [add|unadd <pseudo>] */
|
||||
public final class ClaimCommands {
|
||||
|
||||
@SubscribeEvent
|
||||
public static void onRegister(RegisterCommandsEvent event) {
|
||||
CommandDispatcher<CommandSourceStack> d = event.getDispatcher();
|
||||
|
||||
d.register(Commands.literal("claim")
|
||||
.executes(ClaimCommands::claim)
|
||||
.then(Commands.literal("info").executes(ClaimCommands::info)));
|
||||
|
||||
d.register(Commands.literal("unclaim").executes(ClaimCommands::unclaim));
|
||||
|
||||
d.register(Commands.literal("friend")
|
||||
.executes(ClaimCommands::listFriends)
|
||||
.then(Commands.literal("add")
|
||||
.then(Commands.argument("pseudo", StringArgumentType.word())
|
||||
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(
|
||||
ctx.getSource().getServer().getPlayerNames(), b))
|
||||
.executes(ctx -> addFriend(ctx, StringArgumentType.getString(ctx, "pseudo")))))
|
||||
.then(Commands.literal("unadd")
|
||||
.then(Commands.argument("pseudo", StringArgumentType.word())
|
||||
.suggests((ctx, b) -> SharedSuggestionProvider.suggest(friendNames(ctx), b))
|
||||
.executes(ctx -> removeFriend(ctx, StringArgumentType.getString(ctx, "pseudo"))))));
|
||||
}
|
||||
|
||||
// --- Claims ---
|
||||
|
||||
private static int claim(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
ClaimsData data = ClaimsData.get(p.server);
|
||||
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
|
||||
int max = ClaimsConfig.maxClaims();
|
||||
ClaimRegistry r = data.registry();
|
||||
|
||||
switch (r.claim(p.getUUID(), key, max)) {
|
||||
case OK -> {
|
||||
data.setDirty();
|
||||
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] protégé. Claims : "
|
||||
+ r.countOf(p.getUUID()) + "/" + max + ".");
|
||||
return 1;
|
||||
}
|
||||
case ALREADY_YOURS -> fail(ctx, "Ce chunk est déjà à toi.");
|
||||
case CLAIMED_BY_OTHER -> fail(ctx, "Ce chunk est déjà claim par " + nameOf(p.server, r.ownerOf(key)) + ".");
|
||||
case LIMIT_REACHED -> fail(ctx, "Limite atteinte (" + max + " chunks). Fais /unclaim ailleurs d'abord.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int unclaim(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
ClaimsData data = ClaimsData.get(p.server);
|
||||
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
|
||||
|
||||
switch (data.registry().unclaim(p.getUUID(), key)) {
|
||||
case OK -> {
|
||||
data.setDirty();
|
||||
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] libéré.");
|
||||
return 1;
|
||||
}
|
||||
case NOT_CLAIMED -> fail(ctx, "Ce chunk n'est pas claim.");
|
||||
case NOT_OWNER -> fail(ctx, "Ce chunk appartient à " + nameOf(p.server, data.registry().ownerOf(key)) + ".");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int info(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
ClaimRegistry r = ClaimsData.get(p.server).registry();
|
||||
ChunkKey key = ClaimsData.key(p.level(), p.blockPosition());
|
||||
UUID owner = r.ownerOf(key);
|
||||
int max = ClaimsConfig.maxClaims();
|
||||
int left = Math.max(0, max - r.countOf(p.getUUID()));
|
||||
|
||||
String who = owner == null ? "libre" : "à " + nameOf(p.server, owner);
|
||||
ok(ctx, "Chunk [" + key.x() + ", " + key.z() + "] : " + who + ". Il te reste " + left + "/" + max + " claims.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// --- Amis ---
|
||||
|
||||
private static int listFriends(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
var friends = ClaimsData.get(p.server).registry().friendsOf(p.getUUID());
|
||||
if (friends.isEmpty()) {
|
||||
ok(ctx, "Aucun ami. Ajoute-en avec /friend add <pseudo>.");
|
||||
} else {
|
||||
List<String> names = new ArrayList<>();
|
||||
for (UUID u : friends) names.add(nameOf(p.server, u));
|
||||
ok(ctx, "Amis (" + names.size() + ") : " + String.join(", ", names));
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static int addFriend(CommandContext<CommandSourceStack> ctx, String name) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
Optional<GameProfile> target = resolve(p.server, name);
|
||||
if (target.isEmpty()) {
|
||||
fail(ctx, "Joueur inconnu du serveur : " + name + ".");
|
||||
return 0;
|
||||
}
|
||||
ClaimsData data = ClaimsData.get(p.server);
|
||||
switch (data.registry().addFriend(p.getUUID(), target.get().getId())) {
|
||||
case OK -> {
|
||||
data.setDirty();
|
||||
ok(ctx, target.get().getName() + " a maintenant accès à tous tes claims.");
|
||||
return 1;
|
||||
}
|
||||
case SELF -> fail(ctx, "Tu ne peux pas t'ajouter toi-même.");
|
||||
case ALREADY -> fail(ctx, target.get().getName() + " est déjà ton ami.");
|
||||
default -> { }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static int removeFriend(CommandContext<CommandSourceStack> ctx, String name) throws CommandSyntaxException {
|
||||
ServerPlayer p = ctx.getSource().getPlayerOrException();
|
||||
ClaimsData data = ClaimsData.get(p.server);
|
||||
// On cherche d'abord dans la liste d'amis (marche même si le cache de profils a oublié le pseudo)
|
||||
UUID friend = null;
|
||||
for (UUID u : data.registry().friendsOf(p.getUUID())) {
|
||||
if (nameOf(p.server, u).equalsIgnoreCase(name)) { friend = u; break; }
|
||||
}
|
||||
if (friend == null) {
|
||||
friend = resolve(p.server, name).map(GameProfile::getId).orElse(null);
|
||||
}
|
||||
if (friend == null || data.registry().removeFriend(p.getUUID(), friend) != ClaimRegistry.FriendResult.OK) {
|
||||
fail(ctx, name + " n'est pas dans ta liste d'amis.");
|
||||
return 0;
|
||||
}
|
||||
data.setDirty();
|
||||
ok(ctx, name + " n'a plus accès à tes claims.");
|
||||
return 1;
|
||||
}
|
||||
|
||||
// --- Utilitaires ---
|
||||
|
||||
/** Pseudo -> profil : joueur en ligne, sinon cache de profils du serveur (joueurs déjà venus). */
|
||||
private static Optional<GameProfile> resolve(MinecraftServer server, String name) {
|
||||
ServerPlayer online = server.getPlayerList().getPlayerByName(name);
|
||||
if (online != null) return Optional.of(online.getGameProfile());
|
||||
if (server.getProfileCache() == null) return Optional.empty();
|
||||
return server.getProfileCache().get(name);
|
||||
}
|
||||
|
||||
public static String nameOf(MinecraftServer server, UUID uuid) {
|
||||
if (uuid == null) return "?";
|
||||
ServerPlayer online = server.getPlayerList().getPlayer(uuid);
|
||||
if (online != null) return online.getGameProfile().getName();
|
||||
if (server.getProfileCache() != null) {
|
||||
Optional<GameProfile> prof = server.getProfileCache().get(uuid);
|
||||
if (prof.isPresent()) return prof.get().getName();
|
||||
}
|
||||
return uuid.toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private static List<String> friendNames(CommandContext<CommandSourceStack> ctx) {
|
||||
ServerPlayer p = ctx.getSource().getPlayer();
|
||||
if (p == null) return List.of();
|
||||
List<String> names = new ArrayList<>();
|
||||
for (UUID u : ClaimsData.get(p.server).registry().friendsOf(p.getUUID())) names.add(nameOf(p.server, u));
|
||||
return names;
|
||||
}
|
||||
|
||||
private static void ok(CommandContext<CommandSourceStack> ctx, String msg) {
|
||||
ctx.getSource().sendSuccess(() -> Component.literal(msg), false);
|
||||
}
|
||||
|
||||
private static void fail(CommandContext<CommandSourceStack> ctx, String msg) {
|
||||
ctx.getSource().sendFailure(Component.literal(msg));
|
||||
}
|
||||
|
||||
private ClaimCommands() {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.gastinelclaims;
|
||||
|
||||
import net.neoforged.neoforge.common.ModConfigSpec;
|
||||
|
||||
public final class ClaimsConfig {
|
||||
|
||||
public static final ModConfigSpec SPEC;
|
||||
public static final ModConfigSpec.IntValue MAX_CLAIMS;
|
||||
|
||||
static {
|
||||
ModConfigSpec.Builder b = new ModConfigSpec.Builder();
|
||||
MAX_CLAIMS = b.comment("Nombre maximum de chunks qu'un joueur peut claim.")
|
||||
.defineInRange("maxClaimsParJoueur", 25, 0, 100000);
|
||||
SPEC = b.build();
|
||||
}
|
||||
|
||||
public static int maxClaims() {
|
||||
// Si la config n'est pas encore chargée, on prend la valeur par défaut
|
||||
return SPEC.isLoaded() ? MAX_CLAIMS.get() : MAX_CLAIMS.getDefault();
|
||||
}
|
||||
|
||||
private ClaimsConfig() {}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.gastinelclaims;
|
||||
|
||||
import com.gastinelclaims.core.ChunkKey;
|
||||
import com.gastinelclaims.core.ClaimRegistry;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.nbt.ListTag;
|
||||
import net.minecraft.nbt.NbtUtils;
|
||||
import net.minecraft.nbt.Tag;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.saveddata.SavedData;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Sauvegarde des claims (toutes dimensions) dans data/gastinelclaims.dat de l'overworld.
|
||||
* Le registre en mémoire est une HashMap : recherche en O(1) par chunk.
|
||||
*/
|
||||
public final class ClaimsData extends SavedData {
|
||||
|
||||
private static final String NAME = "gastinelclaims";
|
||||
|
||||
private final ClaimRegistry registry = new ClaimRegistry();
|
||||
|
||||
public static final SavedData.Factory<ClaimsData> FACTORY =
|
||||
new SavedData.Factory<>(ClaimsData::new, ClaimsData::load, null);
|
||||
|
||||
public static ClaimsData get(MinecraftServer server) {
|
||||
return server.overworld().getDataStorage().computeIfAbsent(FACTORY, NAME);
|
||||
}
|
||||
|
||||
public ClaimRegistry registry() {
|
||||
return registry;
|
||||
}
|
||||
|
||||
public static ChunkKey key(Level level, BlockPos pos) {
|
||||
return ChunkKey.ofBlock(level.dimension().location().toString(), pos.getX(), pos.getZ());
|
||||
}
|
||||
|
||||
static ClaimsData load(CompoundTag tag, HolderLookup.Provider provider) {
|
||||
ClaimsData data = new ClaimsData();
|
||||
ListTag claims = tag.getList("claims", Tag.TAG_COMPOUND);
|
||||
for (int i = 0; i < claims.size(); i++) {
|
||||
CompoundTag c = claims.getCompound(i);
|
||||
data.registry.put(new ChunkKey(c.getString("dim"), c.getInt("x"), c.getInt("z")), c.getUUID("owner"));
|
||||
}
|
||||
ListTag friends = tag.getList("friends", Tag.TAG_COMPOUND);
|
||||
for (int i = 0; i < friends.size(); i++) {
|
||||
CompoundTag f = friends.getCompound(i);
|
||||
UUID owner = f.getUUID("owner");
|
||||
ListTag list = f.getList("friends", Tag.TAG_INT_ARRAY);
|
||||
for (Tag t : list) {
|
||||
data.registry.addFriend(owner, NbtUtils.loadUUID(t));
|
||||
}
|
||||
}
|
||||
GastinelClaims.LOGGER.info("[GastinelClaims] {} claims chargés.", claims.size());
|
||||
return data;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompoundTag save(CompoundTag tag, HolderLookup.Provider provider) {
|
||||
ListTag claims = new ListTag();
|
||||
for (Map.Entry<ChunkKey, UUID> e : registry.allClaims().entrySet()) {
|
||||
CompoundTag c = new CompoundTag();
|
||||
c.putString("dim", e.getKey().dimension());
|
||||
c.putInt("x", e.getKey().x());
|
||||
c.putInt("z", e.getKey().z());
|
||||
c.putUUID("owner", e.getValue());
|
||||
claims.add(c);
|
||||
}
|
||||
tag.put("claims", claims);
|
||||
|
||||
ListTag friends = new ListTag();
|
||||
for (Map.Entry<UUID, Set<UUID>> e : registry.allFriends().entrySet()) {
|
||||
CompoundTag f = new CompoundTag();
|
||||
f.putUUID("owner", e.getKey());
|
||||
ListTag list = new ListTag();
|
||||
for (UUID u : e.getValue()) list.add(NbtUtils.createUUID(u));
|
||||
f.put("friends", list);
|
||||
friends.add(f);
|
||||
}
|
||||
tag.put("friends", friends);
|
||||
return tag;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.gastinelclaims;
|
||||
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.ModContainer;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.fml.config.ModConfig;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
@Mod(GastinelClaims.MOD_ID)
|
||||
public class GastinelClaims {
|
||||
|
||||
public static final String MOD_ID = "gastinelclaims";
|
||||
public static final Logger LOGGER = LoggerFactory.getLogger(GastinelClaims.class);
|
||||
|
||||
public GastinelClaims(IEventBus modEventBus, ModContainer modContainer) {
|
||||
// Config serveur : <monde>/serverconfig/gastinelclaims-server.toml
|
||||
modContainer.registerConfig(ModConfig.Type.SERVER, ClaimsConfig.SPEC);
|
||||
|
||||
NeoForge.EVENT_BUS.register(ClaimCommands.class);
|
||||
NeoForge.EVENT_BUS.register(ProtectionEvents.class);
|
||||
|
||||
LOGGER.info("[GastinelClaims] Protection de terrains chargée.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package com.gastinelclaims;
|
||||
|
||||
import com.gastinelclaims.core.ChunkKey;
|
||||
import com.gastinelclaims.core.ClaimRegistry;
|
||||
import net.minecraft.ChatFormatting;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.npc.AbstractVillager;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.BucketItem;
|
||||
import net.minecraft.world.level.ClipContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.entity.monster.Enemy;
|
||||
import net.minecraft.world.phys.BlockHitResult;
|
||||
import net.minecraft.world.phys.HitResult;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
import net.neoforged.bus.api.EventPriority;
|
||||
import net.neoforged.bus.api.SubscribeEvent;
|
||||
import net.neoforged.neoforge.common.util.FakePlayer;
|
||||
import net.neoforged.neoforge.event.entity.EntityTeleportEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.AttackEntityEvent;
|
||||
import net.neoforged.neoforge.event.entity.player.PlayerInteractEvent;
|
||||
import net.neoforged.neoforge.event.level.BlockEvent;
|
||||
import net.neoforged.neoforge.event.level.ExplosionEvent;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Tous les refus dans les claims. Le passage à pied n'est jamais bloqué. */
|
||||
public final class ProtectionEvents {
|
||||
|
||||
private static final long SPAM_MS = 1500;
|
||||
private static final Map<UUID, Long> lastMessage = new HashMap<>();
|
||||
|
||||
// --- Règle centrale ---
|
||||
|
||||
/**
|
||||
* Le joueur peut-il agir sur ce bloc ?
|
||||
* FakePlayer (Create deployer...) : on prend comme "acteur" le propriétaire du chunk où se trouve
|
||||
* la machine. Une machine hors claim n'a donc accès à aucun claim.
|
||||
*/
|
||||
static boolean allowed(Player player, Level level, BlockPos target) {
|
||||
if (level.isClientSide() || player.getServer() == null) return true;
|
||||
ClaimRegistry r = ClaimsData.get(player.getServer()).registry();
|
||||
ChunkKey key = ClaimsData.key(level, target);
|
||||
if (r.ownerOf(key) == null) return true; // cas le plus fréquent, on sort vite
|
||||
|
||||
if (player instanceof FakePlayer) {
|
||||
UUID machineOwner = r.ownerOf(ClaimsData.key(level, player.blockPosition()));
|
||||
return r.canAccess(machineOwner, key, false);
|
||||
}
|
||||
return r.canAccess(player.getUUID(), key, player.hasPermissions(2));
|
||||
}
|
||||
|
||||
/** Vérifie et, si refusé, prévient le joueur (actionbar, anti-spam). */
|
||||
private static boolean deny(Player player, Level level, BlockPos target) {
|
||||
if (allowed(player, level, target)) return false;
|
||||
warn(player, level, target);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void warn(Player player, Level level, BlockPos target) {
|
||||
if (!(player instanceof ServerPlayer sp) || player instanceof FakePlayer) return;
|
||||
long now = System.currentTimeMillis();
|
||||
Long last = lastMessage.get(sp.getUUID());
|
||||
if (last != null && now - last < SPAM_MS) return;
|
||||
lastMessage.put(sp.getUUID(), now);
|
||||
MinecraftServer server = sp.server;
|
||||
UUID owner = ClaimsData.get(server).registry().ownerOf(ClaimsData.key(level, target));
|
||||
sp.displayClientMessage(Component.literal("Terrain protégé (" + ClaimCommands.nameOf(server, owner) + ")")
|
||||
.withStyle(ChatFormatting.RED), true);
|
||||
}
|
||||
|
||||
/** Entités "non hostiles" protégées : animaux, cadres, supports d'armure, villageois... (pas les joueurs). */
|
||||
private static boolean isProtectedEntity(Entity e) {
|
||||
return !(e instanceof Enemy) && !(e instanceof Player);
|
||||
}
|
||||
|
||||
// --- Blocs ---
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onBreak(BlockEvent.BreakEvent event) {
|
||||
if (event.getLevel() instanceof Level level && deny(event.getPlayer(), level, event.getPos())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onPlace(BlockEvent.EntityPlaceEvent event) {
|
||||
// Couvre aussi EntityMultiPlaceEvent (lits, portes...)
|
||||
if (event.getEntity() instanceof Player p && event.getLevel() instanceof Level level
|
||||
&& deny(p, level, event.getPos())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onTrample(BlockEvent.FarmlandTrampleEvent event) {
|
||||
if (event.getEntity() instanceof Player p && event.getLevel() instanceof Level level
|
||||
&& !allowed(p, level, event.getPos())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Clic droit sur un bloc : coffres, portes, leviers, boutons, machines Create, briquet, seaux... */
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event) {
|
||||
Player p = event.getEntity();
|
||||
Level level = event.getLevel();
|
||||
BlockPos pos = event.getPos();
|
||||
boolean refuse = deny(p, level, pos);
|
||||
// Avec un objet en main, ce qui est posé atterrit sur la case voisine (feu, liquide, bloc)
|
||||
if (!refuse && !event.getItemStack().isEmpty() && event.getFace() != null) {
|
||||
refuse = deny(p, level, pos.relative(event.getFace()));
|
||||
}
|
||||
if (refuse) event.setCanceled(true);
|
||||
}
|
||||
|
||||
/** Seau utilisé "dans le vide" (vise un liquide ou un bloc à distance). */
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onRightClickItem(PlayerInteractEvent.RightClickItem event) {
|
||||
if (!(event.getItemStack().getItem() instanceof BucketItem)) return;
|
||||
Player p = event.getEntity();
|
||||
Level level = event.getLevel();
|
||||
Vec3 eye = p.getEyePosition();
|
||||
Vec3 end = eye.add(p.getViewVector(1.0F).scale(p.blockInteractionRange()));
|
||||
BlockHitResult hit = level.clip(new ClipContext(eye, end, ClipContext.Block.OUTLINE,
|
||||
ClipContext.Fluid.SOURCE_ONLY, p));
|
||||
if (hit.getType() != HitResult.Type.BLOCK) return;
|
||||
if (deny(p, level, hit.getBlockPos()) || deny(p, level, hit.getBlockPos().relative(hit.getDirection()))) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Entités ---
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onAttack(AttackEntityEvent event) {
|
||||
Entity target = event.getTarget();
|
||||
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Clic droit sur une entité (cadre, support d'armure, laisse, cisailles...). Commerce avec les villageois autorisé. */
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onEntityInteract(PlayerInteractEvent.EntityInteract event) {
|
||||
Entity target = event.getTarget();
|
||||
if (target instanceof AbstractVillager) return;
|
||||
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onEntityInteractSpecific(PlayerInteractEvent.EntityInteractSpecific event) {
|
||||
Entity target = event.getTarget();
|
||||
if (target instanceof AbstractVillager) return;
|
||||
if (isProtectedEntity(target) && deny(event.getEntity(), target.level(), target.blockPosition())) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Perles de l'Ender ---
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onPearl(EntityTeleportEvent.EnderPearl event) {
|
||||
ServerPlayer p = event.getPlayer();
|
||||
BlockPos dest = BlockPos.containing(event.getTargetX(), event.getTargetY(), event.getTargetZ());
|
||||
if (deny(p, p.level(), dest)) {
|
||||
event.setCanceled(true);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Explosions ---
|
||||
|
||||
@SubscribeEvent(priority = EventPriority.HIGH)
|
||||
public static void onExplosion(ExplosionEvent.Detonate event) {
|
||||
Level level = event.getLevel();
|
||||
if (level.isClientSide() || level.getServer() == null) return;
|
||||
ClaimRegistry r = ClaimsData.get(level.getServer()).registry();
|
||||
event.getAffectedBlocks().removeIf(pos -> r.ownerOf(ClaimsData.key(level, pos)) != null);
|
||||
event.getAffectedEntities().removeIf(e -> isProtectedEntity(e)
|
||||
&& r.ownerOf(ClaimsData.key(level, e.blockPosition())) != null);
|
||||
}
|
||||
|
||||
private ProtectionEvents() {}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.gastinelclaims.core;
|
||||
|
||||
/** Identifie une colonne de chunk : dimension (ex. "minecraft:overworld") + coordonnées de chunk. */
|
||||
public record ChunkKey(String dimension, int x, int z) {
|
||||
|
||||
/** Chunk contenant le bloc (x, z) en coordonnées de bloc. */
|
||||
public static ChunkKey ofBlock(String dimension, int blockX, int blockZ) {
|
||||
return new ChunkKey(dimension, blockX >> 4, blockZ >> 4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.gastinelclaims.core;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Registre des claims et des amis. Logique pure : aucune classe Minecraft ici,
|
||||
* pour pouvoir la tester avec JUnit.
|
||||
*
|
||||
* Un claim = une colonne de chunk entière (toute la hauteur) dans une dimension.
|
||||
*/
|
||||
public final class ClaimRegistry {
|
||||
|
||||
public enum ClaimResult { OK, ALREADY_YOURS, CLAIMED_BY_OTHER, LIMIT_REACHED }
|
||||
public enum UnclaimResult { OK, NOT_CLAIMED, NOT_OWNER }
|
||||
public enum FriendResult { OK, SELF, ALREADY, NOT_FRIEND }
|
||||
|
||||
private final Map<ChunkKey, UUID> owners = new HashMap<>();
|
||||
private final Map<UUID, Integer> counts = new HashMap<>();
|
||||
private final Map<UUID, Set<UUID>> friends = new HashMap<>();
|
||||
|
||||
// --- Claims ---
|
||||
|
||||
public ClaimResult claim(UUID player, ChunkKey key, int maxClaims) {
|
||||
UUID owner = owners.get(key);
|
||||
if (owner != null) {
|
||||
return owner.equals(player) ? ClaimResult.ALREADY_YOURS : ClaimResult.CLAIMED_BY_OTHER;
|
||||
}
|
||||
if (countOf(player) >= maxClaims) {
|
||||
return ClaimResult.LIMIT_REACHED;
|
||||
}
|
||||
put(key, player);
|
||||
return ClaimResult.OK;
|
||||
}
|
||||
|
||||
public UnclaimResult unclaim(UUID player, ChunkKey key) {
|
||||
UUID owner = owners.get(key);
|
||||
if (owner == null) return UnclaimResult.NOT_CLAIMED;
|
||||
if (!owner.equals(player)) return UnclaimResult.NOT_OWNER;
|
||||
owners.remove(key);
|
||||
counts.merge(player, -1, (a, b) -> a + b <= 0 ? null : a + b);
|
||||
return UnclaimResult.OK;
|
||||
}
|
||||
|
||||
/** Ajout brut (chargement depuis la sauvegarde), sans contrôle de limite. */
|
||||
public void put(ChunkKey key, UUID owner) {
|
||||
UUID previous = owners.put(key, owner);
|
||||
if (previous != null) {
|
||||
counts.merge(previous, -1, (a, b) -> a + b <= 0 ? null : a + b);
|
||||
}
|
||||
counts.merge(owner, 1, Integer::sum);
|
||||
}
|
||||
|
||||
public UUID ownerOf(ChunkKey key) {
|
||||
return owners.get(key);
|
||||
}
|
||||
|
||||
public int countOf(UUID player) {
|
||||
return counts.getOrDefault(player, 0);
|
||||
}
|
||||
|
||||
public Map<ChunkKey, UUID> allClaims() {
|
||||
return Collections.unmodifiableMap(owners);
|
||||
}
|
||||
|
||||
// --- Amis ---
|
||||
|
||||
public FriendResult addFriend(UUID owner, UUID friend) {
|
||||
if (owner.equals(friend)) return FriendResult.SELF;
|
||||
boolean added = friends.computeIfAbsent(owner, k -> new LinkedHashSet<>()).add(friend);
|
||||
return added ? FriendResult.OK : FriendResult.ALREADY;
|
||||
}
|
||||
|
||||
public FriendResult removeFriend(UUID owner, UUID friend) {
|
||||
Set<UUID> set = friends.get(owner);
|
||||
if (set == null || !set.remove(friend)) return FriendResult.NOT_FRIEND;
|
||||
if (set.isEmpty()) friends.remove(owner);
|
||||
return FriendResult.OK;
|
||||
}
|
||||
|
||||
public Set<UUID> friendsOf(UUID owner) {
|
||||
return Collections.unmodifiableSet(friends.getOrDefault(owner, Set.of()));
|
||||
}
|
||||
|
||||
public Map<UUID, Set<UUID>> allFriends() {
|
||||
return Collections.unmodifiableMap(friends);
|
||||
}
|
||||
|
||||
// --- Règle d'accès ---
|
||||
|
||||
/**
|
||||
* @param actor joueur qui agit ; null = inconnu (ex. machine hors claim) -> refusé dans un claim
|
||||
* @param bypass vrai pour un op (niveau 2+)
|
||||
*/
|
||||
public boolean canAccess(UUID actor, ChunkKey key, boolean bypass) {
|
||||
UUID owner = owners.get(key);
|
||||
if (owner == null || bypass) return true;
|
||||
if (actor == null) return false;
|
||||
return owner.equals(actor) || friendsOf(owner).contains(actor);
|
||||
}
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur