602 lignes
27 KiB
Java
602 lignes
27 KiB
Java
package com.gastinelgarde;
|
|
|
|
import com.gastinelgarde.core.Controle;
|
|
import com.gastinelgarde.core.EtatJoueur;
|
|
import com.gastinelgarde.core.EtatMouvement;
|
|
import com.gastinelgarde.core.EtatVehicule;
|
|
import com.gastinelgarde.core.GardeConfig;
|
|
import com.gastinelgarde.core.GraceRecul;
|
|
import com.gastinelgarde.core.GraceTeleport;
|
|
import com.gastinelgarde.core.Mode;
|
|
import com.gastinelgarde.core.Moteur;
|
|
import com.gastinelgarde.core.RiptideSuivi;
|
|
import com.gastinelgarde.core.Sanction;
|
|
import com.gastinelgarde.core.Suivi;
|
|
import com.gastinelgarde.core.TraceFichier;
|
|
import com.gastinelgarde.core.TraceLigne;
|
|
import com.gastinelgarde.core.Verdict;
|
|
import java.io.IOException;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.StandardOpenOption;
|
|
import java.time.Instant;
|
|
import java.util.HashMap;
|
|
import java.util.HashSet;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Set;
|
|
import java.util.UUID;
|
|
import net.minecraft.ChatFormatting;
|
|
import net.minecraft.core.BlockPos;
|
|
import net.minecraft.core.Holder;
|
|
import net.minecraft.network.chat.Component;
|
|
import net.minecraft.tags.BlockTags;
|
|
import net.minecraft.world.effect.MobEffect;
|
|
import net.minecraft.world.effect.MobEffectInstance;
|
|
import net.minecraft.world.level.block.Blocks;
|
|
import net.minecraft.world.level.block.state.BlockState;
|
|
import net.minecraft.server.MinecraftServer;
|
|
import net.minecraft.server.level.ServerPlayer;
|
|
import net.minecraft.world.effect.MobEffects;
|
|
import net.minecraft.world.entity.Entity;
|
|
import net.minecraft.world.entity.player.Player;
|
|
import net.minecraft.world.item.UseAnim;
|
|
import net.minecraft.world.item.Items;
|
|
import net.minecraft.world.item.ItemStack;
|
|
import net.minecraft.world.item.enchantment.EnchantmentHelper;
|
|
import net.neoforged.fml.loading.FMLPaths;
|
|
|
|
/**
|
|
* État d'exécution du mod (une seule instance par serveur) et pont entre Minecraft et le moteur pur.
|
|
* Toute la logique de décision est dans {@code com.gastinelgarde.core} ; ici on ne fait que lire l'état du
|
|
* serveur, appeler le moteur et appliquer le résultat.
|
|
*/
|
|
public final class Garde {
|
|
|
|
/** Marques propres à un joueur, côté adaptateur (ticks du serveur). */
|
|
private static final class Marques {
|
|
int teleportTick = Integer.MIN_VALUE;
|
|
int reculTick = Integer.MIN_VALUE;
|
|
int dernierVerdictTick = Integer.MIN_VALUE;
|
|
int dernierTraceTick = Integer.MIN_VALUE;
|
|
final RiptideSuivi riptide = new RiptideSuivi();
|
|
final GraceTeleport graceTeleport = new GraceTeleport();
|
|
final GraceRecul graceRecul = new GraceRecul();
|
|
long exemptJusquaMs = 0;
|
|
double dernierX, dernierY, dernierZ;
|
|
boolean aDernierePosition;
|
|
// Mouvement (phase 2)
|
|
int mouvementTick = Integer.MIN_VALUE;
|
|
double mouvementX, mouvementY, mouvementZ;
|
|
// Véhicule piloté (F20)
|
|
int vehiculeId = -1;
|
|
int vehiculeTick;
|
|
double vehiculeX, vehiculeY, vehiculeZ;
|
|
// Cache de la détection de contraption (la requête d'entités coûte plus que le reste)
|
|
int contraptionTick = Integer.MIN_VALUE;
|
|
boolean contraptionProche;
|
|
}
|
|
|
|
private static final GardeConfig CONFIG = new GardeConfig();
|
|
private static final Moteur MOTEUR = new Moteur(CONFIG);
|
|
private static final Map<UUID, Marques> MARQUES = new HashMap<>();
|
|
private static final Set<UUID> ALERTES_COUPEES = new HashSet<>();
|
|
|
|
private static TraceFichier traces;
|
|
private static Path journal;
|
|
private static boolean tracesEnCours;
|
|
private static int gelTick = Integer.MIN_VALUE;
|
|
private static double tpsEstime = 20.0;
|
|
|
|
private Garde() { }
|
|
|
|
public static GardeConfig config() {
|
|
return CONFIG;
|
|
}
|
|
|
|
public static Moteur moteur() {
|
|
return MOTEUR;
|
|
}
|
|
|
|
// --- Cycle de vie ---
|
|
|
|
public static void surConfigChargee() {
|
|
GastinelGarde.LOGGER.info("[GastinelGarde] Configuration appliquée.");
|
|
}
|
|
|
|
public static synchronized void demarrer() {
|
|
GardeSpec.appliquer(CONFIG);
|
|
Path jeu = FMLPaths.GAMEDIR.get();
|
|
journal = jeu.resolve("logs").resolve("gastinelgarde.log");
|
|
try {
|
|
Files.createDirectories(journal.getParent());
|
|
traces = new TraceFichier(jeu.resolve("gastinelgarde-traces"), GardeSpec.tracesJours(), GardeSpec.tracesTailleOctets());
|
|
tracesEnCours = GardeSpec.tracesActives();
|
|
} catch (IOException e) {
|
|
GastinelGarde.LOGGER.error("[GastinelGarde] Impossible d'ouvrir le dossier de traces", e);
|
|
traces = null;
|
|
tracesEnCours = false;
|
|
}
|
|
}
|
|
|
|
public static synchronized void arreter() {
|
|
if (traces != null) {
|
|
try {
|
|
traces.close();
|
|
} catch (IOException ignored) {
|
|
// fermeture du serveur : rien à faire de plus
|
|
}
|
|
traces = null;
|
|
}
|
|
MARQUES.clear();
|
|
}
|
|
|
|
public static synchronized void flushTraces() {
|
|
if (traces == null) return;
|
|
try {
|
|
traces.flush();
|
|
} catch (IOException e) {
|
|
GastinelGarde.LOGGER.warn("[GastinelGarde] flush des traces : {}", e.toString());
|
|
}
|
|
}
|
|
|
|
public static boolean tracesEnCours() {
|
|
return tracesEnCours && traces != null;
|
|
}
|
|
|
|
public static void definirTraces(boolean actif) {
|
|
tracesEnCours = actif && traces != null;
|
|
}
|
|
|
|
public static void joueurParti(UUID id) {
|
|
MOTEUR.retirer(id);
|
|
MARQUES.remove(id);
|
|
ALERTES_COUPEES.remove(id);
|
|
}
|
|
|
|
// --- Faits collectés ---
|
|
|
|
/** Connexion, changement de dimension, réapparition : toujours une grâce. */
|
|
public static void noterTeleport(ServerPlayer p) {
|
|
if (!surThreadServeur(p)) return;
|
|
Marques m = marques(p.getUUID());
|
|
m.teleportTick = p.server.getTickCount();
|
|
m.mouvementTick = Integer.MIN_VALUE;
|
|
m.vehiculeId = -1;
|
|
}
|
|
|
|
/** Le prochain teleport() de ce joueur a cette origine (appelé par le mixin juste avant l'appel). */
|
|
public static void annoncerTeleport(ServerPlayer p, GraceTeleport.Origine origine) {
|
|
if (!surThreadServeur(p)) return;
|
|
marques(p.getUUID()).graceTeleport.annoncer(origine);
|
|
}
|
|
|
|
/**
|
|
* Tout teleport() du joueur (mixin) : la grâce ne s'ouvre que pour une origine externe (F05). Le mouvement
|
|
* suivant n'est jamais comparé à la position d'avant la téléportation.
|
|
*/
|
|
public static void teleportVanilla(ServerPlayer p) {
|
|
if (!surThreadServeur(p)) return;
|
|
Marques m = marques(p.getUUID());
|
|
if (m.graceTeleport.teleport()) m.teleportTick = p.server.getTickCount();
|
|
m.mouvementTick = Integer.MIN_VALUE;
|
|
m.vehiculeId = -1;
|
|
}
|
|
|
|
/** Recul réel (F06). Auto-infligé (charge de vent à ses pieds) : grâce limitée, voir GraceRecul. */
|
|
public static void noterRecul(ServerPlayer p, boolean autoInflige) {
|
|
if (!surThreadServeur(p)) return;
|
|
Marques m = marques(p.getUUID());
|
|
int tick = p.server.getTickCount();
|
|
if (m.graceRecul.recul(tick, autoInflige)) m.reculTick = tick;
|
|
}
|
|
|
|
public static void noterTickServeur(MinecraftServer server, long dureeNs) {
|
|
double ms = dureeNs / 1_000_000.0;
|
|
if (ms > 250.0) gelTick = server.getTickCount();
|
|
double moyenne = server.getAverageTickTimeNanos() / 1_000_000.0;
|
|
tpsEstime = moyenne <= 50.0 ? 20.0 : 1000.0 / moyenne;
|
|
}
|
|
|
|
public static void exempter(UUID id, long dureeMs) {
|
|
marques(id).exemptJusquaMs = System.currentTimeMillis() + dureeMs;
|
|
}
|
|
|
|
public static boolean estExempteManuellement(UUID id) {
|
|
Marques m = MARQUES.get(id);
|
|
return m != null && m.exemptJusquaMs > System.currentTimeMillis();
|
|
}
|
|
|
|
public static boolean alertesActivesPour(UUID id) {
|
|
return !ALERTES_COUPEES.contains(id);
|
|
}
|
|
|
|
public static void definirAlertes(UUID id, boolean actif) {
|
|
if (actif) ALERTES_COUPEES.remove(id);
|
|
else ALERTES_COUPEES.add(id);
|
|
}
|
|
|
|
/** L'état du mod n'est pas thread-safe : seul le thread du serveur y touche (F01). */
|
|
static boolean surThreadServeur(ServerPlayer p) {
|
|
return p.server == null || p.server.isSameThread();
|
|
}
|
|
|
|
private static Marques marques(UUID id) {
|
|
return MARQUES.computeIfAbsent(id, k -> new Marques());
|
|
}
|
|
|
|
// --- État d'un joueur pour le moteur ---
|
|
|
|
public static EtatJoueur etat(ServerPlayer p, boolean chercherContraption) {
|
|
int tick = p.server.getTickCount();
|
|
Marques m = marques(p.getUUID());
|
|
|
|
// F04 : tenir un trident Impulsion n'exempte plus ; seulement la vrille ou un relâchement valide, et 2 s après.
|
|
m.riptide.observer(tick, p.isAutoSpinAttack());
|
|
boolean riptideRecent = m.riptide.actif(tick);
|
|
|
|
boolean mange = false;
|
|
if (p.isUsingItem()) {
|
|
UseAnim anim = p.getUseItem().getUseAnimation();
|
|
mange = anim == UseAnim.EAT || anim == UseAnim.DRINK;
|
|
}
|
|
|
|
return EtatJoueur.builder()
|
|
.creatif(p.isCreative())
|
|
.spectateur(p.isSpectator())
|
|
.peutVoler(p.getAbilities().mayfly)
|
|
.riptide(riptideRecent)
|
|
.elytres(p.isFallFlying())
|
|
.levitation(p.hasEffect(MobEffects.LEVITATION))
|
|
.chuteLente(p.hasEffect(MobEffects.SLOW_FALLING))
|
|
.enVehicule(p.isPassenger())
|
|
.pocheContraption(chercherContraption && pocheContraptionEnCache(p, m, tick))
|
|
.utiliseObjet(mange)
|
|
.ticksDepuisTeleport(depuis(tick, m.teleportTick))
|
|
.ticksDepuisRecul(depuis(tick, m.reculTick))
|
|
.ticksDepuisGel(depuis(tick, gelTick))
|
|
.tps(tpsEstime)
|
|
.pingMs(p.connection.latency())
|
|
.build();
|
|
}
|
|
|
|
private static int depuis(int tick, int marque) {
|
|
if (marque == Integer.MIN_VALUE) return EtatJoueur.JAMAIS;
|
|
return Math.max(0, tick - marque);
|
|
}
|
|
|
|
private static boolean tridentImpulsion(ItemStack stack, ServerPlayer joueur) {
|
|
return stack.is(Items.TRIDENT) && EnchantmentHelper.getTridentSpinAttackStrength(stack, joueur) > 0.0F;
|
|
}
|
|
|
|
/** Un objet vient d'être relâché (événement Stop) : un trident Impulsion chargé ouvre la tolérance riptide. */
|
|
public static void noterRelache(ServerPlayer p, ItemStack stack, int ticksRestants) {
|
|
if (!surThreadServeur(p) || !tridentImpulsion(stack, p)) return;
|
|
int charge = stack.getUseDuration(p) - ticksRestants;
|
|
boolean ouvert = marques(p.getUUID()).riptide.relache(p.server.getTickCount(), true, charge,
|
|
p.isInWaterOrRain(), pluieProche(p));
|
|
if (ouvert) {
|
|
GastinelGarde.LOGGER.debug("[GastinelGarde] riptide : relâchement de {} (charge {} ticks)",
|
|
p.getGameProfile().getName(), charge);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Critère de pluie relâché par rapport à isInWaterOrRain (le client peut voir la pluie quand le serveur ne la
|
|
* voit pas : niveau de pluie qui monte, feuillage) : temps pluvieux (drapeau ou niveau), biome pluvieux et ciel
|
|
* visible aux pieds ou à la tête, comme vanilla. Seul le contrôle de la carte des hauteurs MOTION_BLOCKING est
|
|
* omis. Un toit (même d'un bloc) ou un temps sec : non.
|
|
*/
|
|
private static boolean pluieProche(ServerPlayer p) {
|
|
net.minecraft.world.level.Level l = p.level();
|
|
if (!l.getLevelData().isRaining() && l.getRainLevel(1.0F) <= 0.0F) return false;
|
|
BlockPos pieds = p.blockPosition();
|
|
BlockPos tete = BlockPos.containing(p.getX(), p.getBoundingBox().maxY, p.getZ());
|
|
for (BlockPos pos : new BlockPos[] {pieds, tete}) {
|
|
if (l.canSeeSky(pos) && l.getBiome(pos).value().getPrecipitationAt(pos)
|
|
== net.minecraft.world.level.biome.Biome.Precipitation.RAIN) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Seuil vanilla « moved too quickly » (appelé par RiptideMoveMixin) : relevé seulement pendant un riptide réel. */
|
|
public static float seuilMouvementVanilla(ServerPlayer p, float seuil) {
|
|
RiptideSuivi r = marques(p.getUUID()).riptide;
|
|
int tick = p.server.getTickCount();
|
|
r.observer(tick, p.isAutoSpinAttack());
|
|
float resultat = r.seuil(seuil, tick, p.isAutoSpinAttack());
|
|
if (resultat != seuil) {
|
|
GastinelGarde.LOGGER.debug("[GastinelGarde] riptide : seuil relevé pour {} (vrille={}, depuis={} ticks)",
|
|
p.getGameProfile().getName(), p.isAutoSpinAttack(), r.ticksDepuis(tick));
|
|
}
|
|
return resultat;
|
|
}
|
|
|
|
/** Vrille en cours ou dans les 2 s (appelé par RiptideMoveMixin pour le contrôle anti-vol vanilla). */
|
|
public static boolean riptideRecent(ServerPlayer p) {
|
|
RiptideSuivi r = marques(p.getUUID()).riptide;
|
|
int tick = p.server.getTickCount();
|
|
r.observer(tick, p.isAutoSpinAttack());
|
|
return r.actif(tick);
|
|
}
|
|
|
|
/** La détection est refaite au plus toutes les 10 ticks par joueur. */
|
|
private static boolean pocheContraptionEnCache(Player p, Marques m, int tick) {
|
|
if (m.contraptionTick == Integer.MIN_VALUE || tick - m.contraptionTick >= 10 || tick < m.contraptionTick) {
|
|
m.contraptionProche = pocheContraption(p);
|
|
m.contraptionTick = tick;
|
|
}
|
|
return m.contraptionProche;
|
|
}
|
|
|
|
/** Une entité de contraption (Create, Aeronautics…) est-elle toute proche ? Détection par nom de classe. */
|
|
private static boolean pocheContraption(Player p) {
|
|
int dist = GardeSpec.distanceContraption();
|
|
if (dist <= 0) return false;
|
|
String[] prefixes = GardeSpec.prefixesContraption().split(",");
|
|
List<Entity> proches = p.level().getEntities(p, p.getBoundingBox().inflate(dist), e -> {
|
|
String nom = e.getClass().getName();
|
|
for (String pre : prefixes) {
|
|
String t = pre.trim();
|
|
if (!t.isEmpty() && nom.startsWith(t)) return true;
|
|
}
|
|
return false;
|
|
});
|
|
return !proches.isEmpty();
|
|
}
|
|
|
|
// --- Réaction aux verdicts ---
|
|
|
|
/**
|
|
* Journalise, prévient les ops et renvoie la pire sanction applicable. Ne modifie pas le joueur : l'appelant
|
|
* décide de l'action (annuler le coup, retour arrière, expulsion).
|
|
*/
|
|
public static Sanction traiter(ServerPlayer p, List<Verdict> verdicts) {
|
|
if (verdicts.isEmpty()) return Sanction.AUCUNE;
|
|
marques(p.getUUID()).dernierVerdictTick = p.server.getTickCount();
|
|
long maintenant = System.currentTimeMillis();
|
|
Suivi suivi = MOTEUR.suivi(p.getUUID());
|
|
for (Verdict v : verdicts) {
|
|
if (suivi.autoriserJournal(v.controle(), maintenant, 1000)) { // au plus une ligne par seconde et par contrôle
|
|
String ligne = String.format("%s %s mode=%s vl=%.1f (+%.1f) palier=%s applique=%s %s exemptions=%s",
|
|
p.getGameProfile().getName(), v.controle().id(), v.mode(), v.vl(), v.points(),
|
|
v.palier(), v.applicable(), v.details(), v.exemptions());
|
|
ecrireJournal(ligne);
|
|
}
|
|
if (v.notifier()) alerterOps(p, v);
|
|
}
|
|
return Verdict.pire(verdicts);
|
|
}
|
|
|
|
private static void alerterOps(ServerPlayer cible, Verdict v) {
|
|
Component msg = Component.literal(String.format("[Garde] %s : %s VL=%.1f (%s, %s)",
|
|
cible.getGameProfile().getName(), v.controle().id(), v.vl(), v.mode(), v.applicable()))
|
|
.withStyle(ChatFormatting.GOLD);
|
|
for (ServerPlayer op : cible.server.getPlayerList().getPlayers()) {
|
|
if (op.hasPermissions(2) && alertesActivesPour(op.getUUID())) op.sendSystemMessage(msg);
|
|
}
|
|
}
|
|
|
|
private static synchronized void ecrireJournal(String ligne) {
|
|
GastinelGarde.LOGGER.warn("[GastinelGarde] {}", ligne);
|
|
if (journal == null) return;
|
|
try {
|
|
Files.writeString(journal, Instant.now() + " " + ligne + System.lineSeparator(), StandardCharsets.UTF_8,
|
|
StandardOpenOption.CREATE, StandardOpenOption.APPEND);
|
|
} catch (IOException e) {
|
|
GastinelGarde.LOGGER.warn("[GastinelGarde] journal : {}", e.toString());
|
|
}
|
|
}
|
|
|
|
// --- Traces ---
|
|
|
|
public static synchronized void tracer(TraceLigne l) {
|
|
if (!tracesEnCours()) return;
|
|
try {
|
|
traces.ecrire(System.currentTimeMillis(), l.json());
|
|
} catch (IOException e) {
|
|
GastinelGarde.LOGGER.warn("[GastinelGarde] trace : {}", e.toString());
|
|
tracesEnCours = false;
|
|
}
|
|
}
|
|
|
|
// --- Paquet de mouvement (appelé par le mixin) ---
|
|
|
|
/** Début du traitement d'un paquet de mouvement : contrôle du débit. */
|
|
public static void avantMouvement(ServerPlayer p) {
|
|
if (!surThreadServeur(p)) return; // F01 : jamais depuis le thread réseau (le mixin l'évite déjà)
|
|
if (estExempteManuellement(p.getUUID())) return;
|
|
EtatJoueur etat = etat(p, false);
|
|
List<Verdict> v = MOTEUR.paquetMouvement(p.getUUID(), System.currentTimeMillis(), etat);
|
|
Sanction s = traiter(p, v);
|
|
if (s.ordinal() >= Sanction.SETBACK.ordinal()) appliquerSanctionMouvement(p, s, v);
|
|
}
|
|
|
|
/** Fin du traitement d'un paquet accepté : mémorise la position valide et trace. */
|
|
public static void apresMouvement(ServerPlayer p) {
|
|
if (!surThreadServeur(p)) return;
|
|
int tick = p.server.getTickCount();
|
|
Marques m = marques(p.getUUID());
|
|
boolean solServeur = auSolServeur(p);
|
|
|
|
// Phase 2 : no-fall (divergence), vitesse horizontale, vol.
|
|
boolean controler = mouvementControlesActifs() && !estExempteManuellement(p.getUUID());
|
|
EtatMouvement em = null;
|
|
EtatJoueur etatMouvement = null;
|
|
if ((controler || tracesEnCours()) && m.mouvementTick != Integer.MIN_VALUE) {
|
|
double dx = p.getX() - m.mouvementX;
|
|
double dz = p.getZ() - m.mouvementZ;
|
|
em = new EtatMouvement(Math.sqrt(dx * dx + dz * dz), p.getY() - m.mouvementY,
|
|
tick - m.mouvementTick, p.onGround(), solServeur, p.isSprinting(), p.isShiftKeyDown(),
|
|
p.isUsingItem(), niveau(p, MobEffects.MOVEMENT_SPEED), niveau(p, MobEffects.MOVEMENT_SLOWDOWN),
|
|
milieuSpecial(p), frictionAnormale(p));
|
|
etatMouvement = etat(p, true);
|
|
}
|
|
if (controler && em != null) {
|
|
List<Verdict> v = MOTEUR.mouvement(p.getUUID(), tick * 50L, etatMouvement, em);
|
|
Sanction s = traiter(p, v);
|
|
if (s.ordinal() >= Sanction.SETBACK.ordinal()) appliquerSanctionMouvement(p, s, v);
|
|
}
|
|
m.mouvementTick = tick;
|
|
m.mouvementX = p.getX();
|
|
m.mouvementY = p.getY();
|
|
m.mouvementZ = p.getZ();
|
|
|
|
if (m.dernierVerdictTick != tick) {
|
|
MOTEUR.suivi(p.getUUID()).memoriserPosition(p.getX(), p.getY(), p.getZ(), p.getYRot(), p.getXRot(),
|
|
p.level().dimension().location().toString());
|
|
}
|
|
if (tracesEnCours() && m.dernierTraceTick != tick) {
|
|
m.dernierTraceTick = tick;
|
|
double vx = m.aDernierePosition ? p.getX() - m.dernierX : 0;
|
|
double vy = m.aDernierePosition ? p.getY() - m.dernierY : 0;
|
|
double vz = m.aDernierePosition ? p.getZ() - m.dernierZ : 0;
|
|
m.dernierX = p.getX();
|
|
m.dernierY = p.getY();
|
|
m.dernierZ = p.getZ();
|
|
m.aDernierePosition = true;
|
|
EtatJoueur etatTrace = etatMouvement != null ? etatMouvement : etat(p, true);
|
|
tracer(new TraceLigne(tick, p.getGameProfile().getName(), "move", p.getX(), p.getY(), p.getZ(),
|
|
vx, vy, vz, p.onGround(), solServeur, TraceLigne.masqueMouvement(etatTrace, em, CONFIG),
|
|
-1, Double.NaN, null));
|
|
}
|
|
}
|
|
|
|
// --- Paquet de mouvement de véhicule (F20, appelé par le mixin à la fin de handleMoveVehicle) ---
|
|
|
|
/**
|
|
* Fin du traitement d'un paquet de véhicule. Vanilla n'applique le paquet que si le joueur pilote son
|
|
* véhicule racine ; sinon (ou au changement de véhicule) on repart de zéro. Un paquet refusé (« moved too
|
|
* quickly », « moved wrongly ») ne passe pas ici : la position de référence reste la dernière acceptée.
|
|
*/
|
|
public static void apresVehicule(ServerPlayer p) {
|
|
if (!surThreadServeur(p)) return;
|
|
Marques m = marques(p.getUUID());
|
|
Entity v = p.getRootVehicle();
|
|
if (v == p || v.getControllingPassenger() != p) {
|
|
m.vehiculeId = -1;
|
|
return;
|
|
}
|
|
int tick = p.server.getTickCount();
|
|
if (v.getId() != m.vehiculeId) {
|
|
m.vehiculeId = v.getId();
|
|
MOTEUR.nouveauVehicule(p.getUUID());
|
|
} else {
|
|
boolean controler = (CONFIG.mode(Controle.VEHICULE_VITESSE) != Mode.OFF
|
|
|| CONFIG.mode(Controle.VEHICULE_VOL) != Mode.OFF) && !estExempteManuellement(p.getUUID());
|
|
if (controler || tracesEnCours()) {
|
|
double dx = v.getX() - m.vehiculeX;
|
|
double dz = v.getZ() - m.vehiculeZ;
|
|
EtatVehicule ev = etatVehicule(v, Math.sqrt(dx * dx + dz * dz), v.getY() - m.vehiculeY,
|
|
tick - m.vehiculeTick);
|
|
EtatJoueur etat = etat(p, true);
|
|
if (controler) {
|
|
List<Verdict> verdicts = MOTEUR.vehicule(p.getUUID(), tick * 50L, etat, ev);
|
|
Sanction s = traiter(p, verdicts);
|
|
if (s.ordinal() >= Sanction.SETBACK.ordinal()) {
|
|
p.stopRiding(); // le retour arrière ramène le joueur, pas le véhicule
|
|
appliquerSanctionMouvement(p, s, verdicts);
|
|
}
|
|
}
|
|
if (tracesEnCours()) {
|
|
int f = TraceLigne.masque(etat);
|
|
if (ev.milieuSpecial()) f |= TraceLigne.F_MILIEU;
|
|
if (ev.frictionAnormale()) f |= TraceLigne.F_FRICTION;
|
|
tracer(new TraceLigne(tick, p.getGameProfile().getName(), "veh", v.getX(), v.getY(), v.getZ(),
|
|
dx, ev.dy(), dz, v.onGround(), ev.auSolServeur(), f, -1, Double.NaN,
|
|
ev.type() + " " + v.getType().builtInRegistryHolder().key().location()));
|
|
}
|
|
}
|
|
}
|
|
m.vehiculeTick = tick;
|
|
m.vehiculeX = v.getX();
|
|
m.vehiculeY = v.getY();
|
|
m.vehiculeZ = v.getZ();
|
|
}
|
|
|
|
private static EtatVehicule etatVehicule(Entity v, double dxz, double dy, int ticks) {
|
|
EtatVehicule.Type type;
|
|
double attribut = 0;
|
|
if (v instanceof net.minecraft.world.entity.vehicle.Boat) {
|
|
type = EtatVehicule.Type.BATEAU; // bateaux, bateaux à coffre, radeaux
|
|
} else if (v instanceof net.minecraft.world.entity.LivingEntity l) {
|
|
type = EtatVehicule.Type.MONTURE;
|
|
attribut = l.getAttributeValue(net.minecraft.world.entity.ai.attributes.Attributes.MOVEMENT_SPEED);
|
|
} else {
|
|
type = EtatVehicule.Type.AUTRE;
|
|
}
|
|
net.minecraft.world.level.Level l = v.level();
|
|
BlockPos pos = v.blockPosition();
|
|
boolean auSol = !l.noCollision(v, v.getBoundingBox().move(0.0, -0.05, 0.0));
|
|
boolean milieu = v.isInWater() || v.isInLava() || !l.getFluidState(pos.below()).isEmpty()
|
|
|| l.getBlockState(pos).is(Blocks.BUBBLE_COLUMN) || l.getBlockState(pos.below()).is(Blocks.BUBBLE_COLUMN)
|
|
|| l.getBlockState(pos).is(Blocks.COBWEB);
|
|
if (v instanceof net.minecraft.world.entity.LivingEntity le) {
|
|
milieu |= le.onClimbable() || le.hasEffect(MobEffects.LEVITATION) || le.hasEffect(MobEffects.SLOW_FALLING);
|
|
}
|
|
BlockState sous = l.getBlockState(v.getBlockPosBelowThatAffectsMyMovement());
|
|
boolean friction = sous.getBlock().getFriction() > 0.6F || sous.getBlock().getSpeedFactor() > 1.0F;
|
|
return new EtatVehicule(type, dxz, dy, ticks, auSol, milieu, friction, attribut, v.isNoGravity());
|
|
}
|
|
|
|
/**
|
|
* Drapeau « au sol » à donner aux dégâts de chute (appelé par le mixin). En OBSERVE ou hors exemption
|
|
* inapplicable, c'est celui du client : comportement vanilla.
|
|
*/
|
|
public static boolean auSolPourChute(ServerPlayer p, boolean auSolClient) {
|
|
if (!auSolClient) return false;
|
|
if (!surThreadServeur(p)) return auSolClient;
|
|
if (CONFIG.mode(Controle.NO_FALL) != Mode.ENFORCE) return auSolClient;
|
|
if (estExempteManuellement(p.getUUID())) return auSolClient;
|
|
return MOTEUR.auSolPourDegatsDeChute(etat(p, true), auSolClient, auSolServeur(p));
|
|
}
|
|
|
|
private static boolean mouvementControlesActifs() {
|
|
return CONFIG.mode(Controle.NO_FALL) != Mode.OFF || CONFIG.mode(Controle.VITESSE) != Mode.OFF
|
|
|| CONFIG.mode(Controle.VOL) != Mode.OFF;
|
|
}
|
|
|
|
/** Bloc solide sous la boîte du joueur, vu par le serveur (0,05 bloc de marge). */
|
|
private static boolean auSolServeur(ServerPlayer p) {
|
|
return !p.level().noCollision(p, p.getBoundingBox().move(0.0, -0.05, 0.0));
|
|
}
|
|
|
|
private static int niveau(ServerPlayer p, Holder<MobEffect> effet) {
|
|
MobEffectInstance e = p.getEffect(effet);
|
|
return e == null ? 0 : e.getAmplifier() + 1;
|
|
}
|
|
|
|
/** Eau, lave, échelle, vol créatif, toile, neige poudreuse, miel, slime, lit : la vitesse et le vol vanilla ne s'appliquent pas. */
|
|
private static boolean milieuSpecial(ServerPlayer p) {
|
|
if (p.isInWater() || p.isInLava() || p.onClimbable() || p.isSwimming() || p.getAbilities().flying) return true;
|
|
BlockPos pos = p.blockPosition();
|
|
BlockState pied = p.level().getBlockState(pos);
|
|
BlockState sous = p.level().getBlockState(pos.below());
|
|
return pied.is(Blocks.COBWEB) || pied.is(Blocks.POWDER_SNOW) || pied.is(Blocks.SWEET_BERRY_BUSH)
|
|
|| sous.is(Blocks.SLIME_BLOCK) || sous.is(BlockTags.BEDS);
|
|
}
|
|
|
|
/** Glace, slime, âmes, miel : friction ou facteur de vitesse du bloc différents de la normale. */
|
|
private static boolean frictionAnormale(ServerPlayer p) {
|
|
BlockState sous = p.level().getBlockState(p.getBlockPosBelowThatAffectsMyMovement());
|
|
return sous.getBlock().getFriction() != 0.6F || sous.getBlock().getSpeedFactor() != 1.0F;
|
|
}
|
|
|
|
public static void appliquerSanctionMouvement(ServerPlayer p, Sanction s, List<Verdict> verdicts) {
|
|
String raison = verdicts.isEmpty() ? "anti-triche" : verdicts.get(0).controle().id();
|
|
if (s == Sanction.EXPULSION) {
|
|
ecrireJournal(p.getGameProfile().getName() + " EXPULSE (" + raison + ")");
|
|
p.connection.disconnect(Component.literal("Expulsé par l'anti-triche (" + raison + ")."));
|
|
} else if (s == Sanction.SETBACK) {
|
|
Suivi sv = MOTEUR.suivi(p.getUUID());
|
|
String dim = p.level().dimension().location().toString();
|
|
if (sv.aPositionValide() && sv.dimension().equals(dim)) {
|
|
annoncerTeleport(p, GraceTeleport.Origine.SETBACK);
|
|
p.connection.teleport(sv.x(), sv.y(), sv.z(), sv.yaw(), sv.pitch());
|
|
ecrireJournal(p.getGameProfile().getName() + " SETBACK (" + raison + ")");
|
|
}
|
|
}
|
|
}
|
|
}
|