diff --git a/README.md b/README.md new file mode 100644 index 0000000..e0e97e7 --- /dev/null +++ b/README.md @@ -0,0 +1,22 @@ +# GastinelTpa + +Téléportations pour NeoForge 1.21.1 (21.1.234). **Mod côté serveur uniquement.** + +## Commandes +- `/tpa `, `/tpahere `, `/tpaccept [joueur]`, `/tpadeny [joueur]` : demandes entre joueurs (expiration 1 min). +- `/spawn` : téléporte au point de spawn du monde (lu dans le monde via `getSharedSpawnPos()`, celui de `/setworldspawn`, aucune coordonnée en dur). Délai 3 s annulé si le joueur bouge ou est blessé, recharge 60 s. +- `/rtp` : endroit aléatoire dans la zone **déjà générée**, jamais de nouveau chunk. Délai 3 s (annulable), recharge 300 s. Atterrissage sûr : sol solide, pas d'eau (ni profonde à côté), pas de lave/feu/magma/cactus/baies/neige poudreuse/stalactite/rose du wither autour, pas de falaise > 3 blocs, pas sur les feuilles. Évite les claims GastinelClaims des autres (par réflexion, sans dépendance). +- `/rtp spawn [joueurs]` : **blocs de commande uniquement** (plaque de pression de l'entrée) ; joueur ou console -> refus avec un message clair. Sans argument : le joueur le plus proche du bloc (4 blocs). Choisit un « beau spot » de `beaux-spots.json` parmi les N meilleurs, tirage pondéré par le score (repli sur la zone /rtp si fichier absent). +- `/rtp diagnostic [spawn]` (op 2) : cherche un point comme /rtp sans téléporter personne et affiche les motifs de rejet. `/rtp recharger` (op 2) : relit `beaux-spots.json`. + +## Comment /rtp évite toute génération +Un point n'est examiné que si le chunk **et ses 8 voisins** sont déjà chargés, ou présents sur le disque avec le statut `minecraft:full` (lecture asynchrone du NBT). Fichier région absent -> pas lu du tout (sinon Minecraft crée un `r.X.Z.mca` vide). Charger un chunk dont un voisin manque créerait un proto-chunk voisin pour l'éclairage, d'où la règle des voisins. Vérifié sur une copie du monde : 115 925 chunks avant/après, aucun fichier créé. + +## Config +`/serverconfig/gastineltpa-server.toml` (rechargé à chaud) : délais, recharges, `essais` (100), zone `zoneXMin/XMax/ZMin/ZMax` (-512..6831 × -5632..1167, étendue mesurée le 09/10/2026 : 89 397 chunks complets, beaucoup d'océan), disque optionnel `zoneCentreX/Z` + `zoneRayon` (0 = rectangle seul), `rtpSpawn.topN` (60), `fichierSpots` (`config/gastineltpa/beaux-spots.json`). + +## Beaux spots (notation v0) +`outils/beaux_spots.py` (+ `nbt_anvil.py`, `beaux-spots-config.json`) : lit une **copie** des fichiers région (jamais le monde en service), note chaque chunk complet (relief, vue, eau 5-30 %, végétation, variété/rareté des biomes, Terralith, sûreté ; pénalités océan profond, désert plat, danger), garde 300 spots espacés d'au moins 96 blocs, score 0-10. Lancer sur cornafserver : `nice -n 19 python3 -I beaux_spots.py --monde --config beaux-spots-config.json --sortie beaux-spots.json` (82 s pour 89 397 chunks). Limite : les scores saturent près de 10 en tête (42 spots ≥ 9,5), le tirage pondéré du top 60 est donc presque uniforme. + +## Build (sur cornafserver) +`sh envoyer-et-compiler.sh` depuis le PC, ou `sh build-sur-cornafserver.sh` sur le serveur (JDK 21 jetable, `nice`, 4 Go max). Tests JUnit (`core/`) puis `build/libs/gastineltpa-neoforge-1.21.1-1.1.0.jar`. diff --git a/build-sur-cornafserver.sh b/build-sur-cornafserver.sh index 243bdc2..628a7a3 100644 --- a/build-sur-cornafserver.sh +++ b/build-sur-cornafserver.sh @@ -4,7 +4,7 @@ set -e cd "$(dirname "$0")" mkdir -p "$HOME/.cache/gastineltpa-gradle" -docker run --rm \ +nice -n 10 docker run --rm --memory 4g --cpus 4 \ -u "$(id -u):$(id -g)" \ -e GRADLE_USER_HOME=/gradle-home \ -v "$HOME/.cache/gastineltpa-gradle:/gradle-home" \ diff --git a/envoyer-et-compiler.sh b/envoyer-et-compiler.sh index 7785e77..8a1ac87 100644 --- a/envoyer-et-compiler.sh +++ b/envoyer-et-compiler.sh @@ -2,9 +2,9 @@ # Depuis le PC : envoie les sources sur cornafserver (~/staging/GastinelTpa), compile, rapatrie le jar dans build-out/. set -e cd "$(dirname "$0")" -tar czf /tmp/gastineltpa-src.tgz --exclude=build --exclude=.gradle --exclude=build-out --exclude=run . +tar czf /tmp/gastineltpa-src.tgz --exclude=build --exclude=.gradle --exclude=build-out --exclude=run --exclude=outils . scp /tmp/gastineltpa-src.tgz cornafserver:gastineltpa-src.tgz ssh cornafserver 'set -e; rm -rf "$HOME/staging/GastinelTpa"; mkdir -p "$HOME/staging/GastinelTpa"; tar xzf "$HOME/gastineltpa-src.tgz" -C "$HOME/staging/GastinelTpa"; rm "$HOME/gastineltpa-src.tgz"; cd "$HOME/staging/GastinelTpa" && sh build-sur-cornafserver.sh' mkdir -p build-out -scp 'cornafserver:staging/GastinelTpa/build/libs/gastineltpa-neoforge-1.21.1-1.0.0.jar' build-out/ +scp 'cornafserver:staging/GastinelTpa/build/libs/gastineltpa-neoforge-1.21.1-1.1.0.jar' build-out/ ls -l build-out diff --git a/gradle.properties b/gradle.properties index 3a3a188..2f71e3d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,7 @@ org.gradle.jvmargs=-Xmx2G org.gradle.parallel=true -mod_version=1.0.0 +mod_version=1.1.0 mod_group_id=com.gastineltpa mod_id=gastineltpa diff --git a/outils/beaux-spots-config.json b/outils/beaux-spots-config.json new file mode 100644 index 0000000..0579c4d --- /dev/null +++ b/outils/beaux-spots-config.json @@ -0,0 +1,37 @@ +{ + "_doc": "Réglages de beaux_spots.py (version 0). Poids : importance relative de chaque critère (0 = ignoré). Les poids pen_* sont soustraits. Score final ramené sur 0-10.", + "zone": null, + "pas_grille_chunks": 1, + "rayon_voisinage_chunks": 3, + "rayon_vue_chunks": 6, + "espacement_min_blocs": 96, + "nombre_spots_max": 300, + "criteres": { + "relief_min": 6, + "relief_ideal": 45, + "relief_std_plat": 6, + "vue_ideal": 20, + "eau_min_ideal": 0.05, + "eau_max_ideal": 0.30, + "eau_trop": 0.75, + "canopee_min_ideal": 0.20, + "canopee_max_ideal": 0.60, + "biomes_varietes_ideal": 4, + "ocean_prof_seuil": 0.25, + "surete_vue_max": 40 + }, + "poids": { + "relief": 2.0, + "vue": 2.0, + "eau": 2.0, + "vegetation": 1.5, + "biome_variete": 1.0, + "biome_rarete": 1.0, + "terralith": 0.5, + "surete": 1.0, + "pen_ocean_profond": 3.0, + "pen_desert_plat": 2.0, + "pen_village": 0.0, + "pen_danger": 2.0 + } +} diff --git a/outils/beaux_spots.py b/outils/beaux_spots.py new file mode 100644 index 0000000..54f9c99 --- /dev/null +++ b/outils/beaux_spots.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +"""Notation de « beauté » des lieux d'un monde Minecraft prégénéré (version 0). + +Lit en LECTURE SEULE les régions (.mca) d'une COPIE du monde, résume chaque chunk +(hauteurs, eau, arbres, biomes, sûreté d'atterrissage), puis note des candidats +(un par chunk, sur une grille) avec des critères pondérés définis dans un fichier JSON. +Produit beaux-spots.json, lu par le mod GastinelTpa pour /rtp spawn. + +Usage (sur cornafserver, avec nice) : + nice -n 19 python3 -I beaux_spots.py --monde \ + --config beaux-spots-config.json --sortie beaux-spots.json [--echantillon 20] + +Aucune écriture dans le monde : seuls level.dat et region/*.mca sont ouverts en lecture. +""" +import argparse +import glob +import json +import math +import os +import re +import sys +import time +from collections import Counter +from multiprocessing import Pool + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from nbt_anvil import bits_pour, chunks_de_region, deplier, heightmap, lire_level_dat # noqa: E402 + +# Blocs sur lesquels on n'atterrit jamais (ou qu'on ne veut pas à côté des pieds). +DANGEREUX = { + "minecraft:lava", "minecraft:fire", "minecraft:soul_fire", "minecraft:magma_block", + "minecraft:cactus", "minecraft:sweet_berry_bush", "minecraft:campfire", "minecraft:soul_campfire", + "minecraft:powder_snow", "minecraft:pointed_dripstone", "minecraft:wither_rose", +} +LIQUIDES = {"minecraft:water", "minecraft:lava", "minecraft:bubble_column"} +SABLE = {"minecraft:sand", "minecraft:red_sand", "minecraft:sandstone", "minecraft:red_sandstone", + "minecraft:terracotta"} +RE_PAS_SOL = re.compile(r"(_log|_wood|_stem|_hyphae|leaves|_fence|_wall|_pane|glass|ice|" + r"bamboo|_slab|_stairs|_door|_trapdoor|scaffolding|chest|barrel|bed$|" + r"_sign|lantern|chain|bell|_rail|rail$|piston|hopper)") + + +def bloc_sur(nom): + """Bloc plein « naturel » où l'on peut poser les pieds.""" + if nom in DANGEREUX or nom in LIQUIDES: + return False + if nom in ("minecraft:air", "minecraft:cave_air", "minecraft:void_air"): + return False + return not RE_PAS_SOL.search(nom) + + +def _sections(nbt): + out = {} + for s in nbt.get("sections", []): + out[s.get("Y")] = s + return out + + +def _blocs_section(section, cache): + """Tableau (4096,) d'indices + palette des noms, décodé une fois par section.""" + y = section.get("Y") + if y in cache: + return cache[y] + bs = section.get("block_states") or {} + pal = [p.get("Name", "minecraft:air") for p in bs.get("palette", [])] or ["minecraft:air"] + data = bs.get("data") + if data is None or len(pal) == 1: + idx = np.zeros(4096, dtype=np.int64) + else: + idx = deplier(data, 4096, bits_pour(len(pal), 4)) + cache[y] = (idx, pal) + return cache[y] + + +def _bloc(sections, cache, x, y, z): + sy = y >> 4 + s = sections.get(sy) + if s is None: + return "minecraft:air" + idx, pal = _blocs_section(s, cache) + i = idx[((y & 15) * 16 + z) * 16 + x] + return pal[i] if i < len(pal) else "minecraft:air" + + +def _biome(sections, x, y, z): + s = sections.get(y >> 4) + if s is None: + return "?" + bm = s.get("biomes") or {} + pal = bm.get("palette", []) + if not pal: + return "?" + if len(pal) == 1 or bm.get("data") is None: + return pal[0] + vals = deplier(bm["data"], 64, bits_pour(len(pal), 1)) + i = vals[(((y & 15) >> 2) * 4 + (z >> 2)) * 4 + (x >> 2)] + return pal[i] if i < len(pal) else "?" + + +def resumer_chunk(nbt): + """Résumé compact d'un chunk FULL (None sinon).""" + if nbt.get("Status") not in ("minecraft:full", "full"): + return None + hm = nbt.get("Heightmaps") or {} + min_y = nbt.get("yPos", -4) * 16 + sol = heightmap(hm.get("MOTION_BLOCKING_NO_LEAVES"), min_y) # sol, eau comprise, sans feuilles + fond = heightmap(hm.get("OCEAN_FLOOR"), min_y) # sol solide (sans liquides) + haut = heightmap(hm.get("MOTION_BLOCKING"), min_y) # avec feuilles + if sol is None or fond is None or haut is None: + return None + sections = _sections(nbt) + cache = {} + prof = sol - fond + canopee = haut > sol + # Blocs de surface : un sur deux (64 colonnes) + surf = Counter() + danger = 0 + for z in range(0, 16, 2): + for x in range(0, 16, 2): + b = _bloc(sections, cache, x, int(sol[z, x]) - 1, z) + surf[b] += 1 + if b in DANGEREUX: + danger += 1 + # Colonne d'atterrissage : la plus proche du centre qui est sûre + meilleure = None + for d2, x, z in sorted(((x - 7.5) ** 2 + (z - 7.5) ** 2, x, z) + for x in range(2, 14) for z in range(2, 14)): + if prof[z, x] > 0: + continue + y = int(sol[z, x]) + voisins = sol[z - 1:z + 2, x - 1:x + 2] + if voisins.max() - voisins.min() > 2 or (prof[z - 1:z + 2, x - 1:x + 2] > 0).any(): + continue + if not bloc_sur(_bloc(sections, cache, x, y - 1, z)): + continue + if _bloc(sections, cache, x, y, z) not in ("minecraft:air", "minecraft:cave_air") and \ + not _bloc(sections, cache, x, y, z).endswith(("short_grass", "fern", "snow")): + continue + if _bloc(sections, cache, x, y + 1, z) not in ("minecraft:air", "minecraft:cave_air"): + continue + if any(_bloc(sections, cache, x + dx, y - 1 + dy, z + dz) in DANGEREUX + for dx in (-1, 0, 1) for dz in (-1, 0, 1) for dy in (0, 1)): + continue + meilleure = (x, y, z) + break + biomes = Counter(_biome(sections, x, int(sol[z, x]), z) for x in (2, 13) for z in (2, 13)) + centre_biome = _biome(sections, 8, int(sol[8, 8]), 8) + biomes[centre_biome] += 1 + refs = (nbt.get("structures") or {}).get("References") or {} + village = any("village" in k for k in refs) + total = 64 + return { + "h": float(sol.mean()), "hmin": int(sol.min()), "hmax": int(sol.max()), + "eau": float((prof > 0).mean()), "eau_prof": float((prof >= 4).mean()), + "canopee": float(canopee.mean()), "danger": danger / total, + "sable": sum(v for k, v in surf.items() if k in SABLE) / total, + "biome": centre_biome, "biomes": sorted(biomes), + "atterrissage": meilleure, "village": village, + } + + +def traiter_region(chemin): + m = re.search(r"r\.(-?\d+)\.(-?\d+)\.mca$", chemin) + rx, rz = int(m.group(1)), int(m.group(2)) + out = {} + for lx, lz, nbt in chunks_de_region(chemin): + try: + r = resumer_chunk(nbt) + except Exception: + r = None + if r is not None: + out[(rx * 32 + lx, rz * 32 + lz)] = r + return out + + +# ---------- Notation ---------- + +def rampe(v, a, b): + """0 sous a, 1 au-dessus de b, linéaire entre les deux.""" + if b == a: + return 1.0 if v >= b else 0.0 + return min(1.0, max(0.0, (v - a) / (b - a))) + + +def plateau(v, a, b, c, d): + """0 avant a, monte jusqu'à b, 1 entre b et c, redescend à 0 en d.""" + return min(rampe(v, a, b), 1.0 - rampe(v, c, d)) + + +def noter(chunks, cfg): + c = cfg["criteres"] + p = cfg["poids"] + R = cfg.get("rayon_voisinage_chunks", 3) + RV = cfg.get("rayon_vue_chunks", 6) + pas = cfg.get("pas_grille_chunks", 1) + freq = Counter(r["biome"] for r in chunks.values()) + fmax = max(freq.values()) + candidats = [] + for (cx, cz), r in chunks.items(): + if cx % pas or cz % pas or r["atterrissage"] is None: + continue + voisins = [chunks.get((cx + dx, cz + dz)) for dx in range(-R, R + 1) for dz in range(-R, R + 1)] + voisins = [v for v in voisins if v is not None] + if len(voisins) < 0.8 * (2 * R + 1) ** 2: + continue # bord de la zone générée : voisinage incomplet + loin = [chunks.get((cx + dx, cz + dz)) for dx in range(-RV, RV + 1, 2) for dz in range(-RV, RV + 1, 2)] + loin = [v for v in loin if v is not None] + lx, ly, lz = r["atterrissage"] + hs = [v["h"] for v in voisins] + relief = max(v["hmax"] for v in voisins) - min(v["hmin"] for v in voisins) + vue = ly - float(np.mean([v["h"] for v in loin])) + eau = float(np.mean([v["eau"] for v in voisins])) + eau_prof = float(np.mean([v["eau_prof"] for v in voisins])) + canopee = float(np.mean([v["canopee"] for v in voisins])) + sable = float(np.mean([v["sable"] for v in voisins])) + danger = float(np.mean([v["danger"] for v in voisins])) + biomes = set() + for v in voisins: + biomes.update(v["biomes"]) + biomes.discard("?") + rarete = 1.0 - freq[r["biome"]] / fmax + terralith = 1.0 if r["biome"].startswith("terralith:") else 0.0 + s_relief = rampe(relief, c["relief_min"], c["relief_ideal"]) + s_vue = rampe(vue, 0, c["vue_ideal"]) + s_eau = plateau(eau, 0.0, c["eau_min_ideal"], c["eau_max_ideal"], c["eau_trop"]) + s_veg = plateau(canopee, 0.0, c["canopee_min_ideal"], c["canopee_max_ideal"], 1.0) + s_var = rampe(len(biomes), 1, c["biomes_varietes_ideal"]) + plat = 1.0 - rampe(float(np.std(hs)), 0, c["relief_std_plat"]) + pen_ocean = rampe(eau_prof, c["ocean_prof_seuil"], 1.0) + pen_desert = sable * plat + pen_village = 1.0 if any(v["village"] for v in voisins) else 0.0 + pen_danger = rampe(danger, 0.0, 0.1) + s_surete = 1.0 if abs(vue) < c["surete_vue_max"] else 0.5 + detail = { + "relief": round(s_relief, 2), "vue": round(s_vue, 2), "eau": round(s_eau, 2), + "vegetation": round(s_veg, 2), "biome_variete": round(s_var, 2), + "biome_rarete": round(rarete, 2), "terralith": terralith, "surete": s_surete, + "pen_ocean_profond": round(pen_ocean, 2), "pen_desert_plat": round(pen_desert, 2), + "pen_village": pen_village, "pen_danger": round(pen_danger, 2), + } + positif = sum(p[k] for k in p if not k.startswith("pen_")) + brut = sum(p[k] * detail[k] for k in p if not k.startswith("pen_")) \ + - sum(p[k] * detail[k] for k in p if k.startswith("pen_")) + score = 10.0 * min(1.0, max(0.0, brut / positif)) + candidats.append({ + "x": cx * 16 + lx, "y": ly, "z": cz * 16 + lz, "score": round(score, 2), + "biome": r["biome"], + "mesures": {"relief_blocs": relief, "vue_blocs": round(vue, 1), "eau": round(eau, 2), + "canopee": round(canopee, 2), "biomes_proches": len(biomes)}, + "detail": detail, + }) + candidats.sort(key=lambda s: -s["score"]) + # Espacement minimal entre spots retenus + dmin2 = cfg.get("espacement_min_blocs", 96) ** 2 + retenus = [] + for s in candidats: + if all((s["x"] - t["x"]) ** 2 + (s["z"] - t["z"]) ** 2 >= dmin2 for t in retenus): + retenus.append(s) + if len(retenus) >= cfg.get("nombre_spots_max", 300): + break + return candidats, retenus, freq + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--monde", required=True) + ap.add_argument("--config", required=True) + ap.add_argument("--sortie", required=True) + ap.add_argument("--processus", type=int, default=3) + ap.add_argument("--echantillon", type=int, default=20) + a = ap.parse_args() + with open(a.config, encoding="utf-8") as f: + cfg = json.load(f) + t0 = time.time() + level = lire_level_dat(os.path.join(a.monde, "level.dat")) + zone = cfg.get("zone") + fichiers = sorted(glob.glob(os.path.join(a.monde, "region", "r.*.mca"))) + if zone: + def dans_zone(fp): + m = re.search(r"r\.(-?\d+)\.(-?\d+)\.mca$", fp) + rx, rz = int(m.group(1)), int(m.group(2)) + return (rx * 512 + 511 >= zone["xmin"] and rx * 512 <= zone["xmax"] + and rz * 512 + 511 >= zone["zmin"] and rz * 512 <= zone["zmax"]) + fichiers = [fp for fp in fichiers if dans_zone(fp)] + chunks = {} + with Pool(a.processus) as pool: + for i, res in enumerate(pool.imap_unordered(traiter_region, fichiers)): + chunks.update(res) + print(f"\r{i + 1}/{len(fichiers)} régions, {len(chunks)} chunks", end="", file=sys.stderr) + print(file=sys.stderr) + if zone: + chunks = {k: v for k, v in chunks.items() + if zone["xmin"] <= k[0] * 16 + 8 <= zone["xmax"] and zone["zmin"] <= k[1] * 16 + 8 <= zone["zmax"]} + xs = [k[0] for k in chunks] + zs = [k[1] for k in chunks] + candidats, retenus, freq = noter(chunks, cfg) + scores = np.array([c["score"] for c in candidats]) if candidats else np.zeros(1) + sortie = { + "version": 0, + "genere_le": time.strftime("%Y-%m-%d %H:%M:%S"), + "monde": os.path.basename(os.path.normpath(a.monde)), + "spawn_monde": [level.get("SpawnX"), level.get("SpawnY"), level.get("SpawnZ")], + "bordure_monde": {"centre": [level.get("BorderCenterX"), level.get("BorderCenterZ")], + "taille": level.get("BorderSize")}, + "etendue_generee": {"chunks_full": len(chunks), + "xmin": min(xs) * 16, "xmax": max(xs) * 16 + 15, + "zmin": min(zs) * 16, "zmax": max(zs) * 16 + 15}, + "candidats_notes": len(candidats), + "repartition_scores": {"p50": round(float(np.percentile(scores, 50)), 2), + "p90": round(float(np.percentile(scores, 90)), 2), + "max": round(float(scores.max()), 2)}, + "biomes_frequents": freq.most_common(15), + "config": cfg, + "spots": retenus, + } + with open(a.sortie, "w", encoding="utf-8") as f: + json.dump(sortie, f, ensure_ascii=False, indent=1) + print(f"{len(chunks)} chunks, {len(candidats)} candidats, {len(retenus)} spots retenus " + f"en {time.time() - t0:.0f} s -> {a.sortie}", file=sys.stderr) + for s in retenus[:a.echantillon]: + print(f"{s['score']:5.2f} ({s['x']}, {s['y']}, {s['z']}) {s['biome']} {s['mesures']}") + + +if __name__ == "__main__": + main() diff --git a/outils/nbt_anvil.py b/outils/nbt_anvil.py new file mode 100644 index 0000000..9c4a5cc --- /dev/null +++ b/outils/nbt_anvil.py @@ -0,0 +1,144 @@ +"""Lecture minimale (lecture seule) du format NBT et des régions Anvil (.mca) de Minecraft 1.21. + +Aucune dépendance hors numpy. Ne modifie jamais les fichiers lus. +""" +import gzip +import struct +import zlib + +import numpy as np + +TAG_END, TAG_BYTE, TAG_SHORT, TAG_INT, TAG_LONG, TAG_FLOAT, TAG_DOUBLE = 0, 1, 2, 3, 4, 5, 6 +TAG_BYTE_ARRAY, TAG_STRING, TAG_LIST, TAG_COMPOUND, TAG_INT_ARRAY, TAG_LONG_ARRAY = 7, 8, 9, 10, 11, 12 + + +class _Lecteur: + __slots__ = ("b", "p") + + def __init__(self, data): + self.b = data + self.p = 0 + + def u(self, fmt, n): + v = struct.unpack_from(fmt, self.b, self.p)[0] + self.p += n + return v + + def chaine(self): + n = self.u(">H", 2) + s = self.b[self.p:self.p + n].decode("utf-8", "replace") + self.p += n + return s + + def charge(self, t): + if t == TAG_BYTE: + return self.u(">b", 1) + if t == TAG_SHORT: + return self.u(">h", 2) + if t == TAG_INT: + return self.u(">i", 4) + if t == TAG_LONG: + return self.u(">q", 8) + if t == TAG_FLOAT: + return self.u(">f", 4) + if t == TAG_DOUBLE: + return self.u(">d", 8) + if t == TAG_BYTE_ARRAY: + n = self.u(">i", 4) + v = self.b[self.p:self.p + n] + self.p += n + return v + if t == TAG_STRING: + return self.chaine() + if t == TAG_LIST: + et = self.u(">b", 1) + n = self.u(">i", 4) + return [self.charge(et) for _ in range(n)] + if t == TAG_COMPOUND: + d = {} + while True: + ct = self.u(">b", 1) + if ct == TAG_END: + return d + nom = self.chaine() + d[nom] = self.charge(ct) + if t == TAG_INT_ARRAY: + n = self.u(">i", 4) + v = np.frombuffer(self.b, dtype=">i4", count=n, offset=self.p) + self.p += 4 * n + return v + if t == TAG_LONG_ARRAY: + n = self.u(">i", 4) + v = np.frombuffer(self.b, dtype=">u8", count=n, offset=self.p) + self.p += 8 * n + return v + raise ValueError(f"tag NBT inconnu {t}") + + +def lire_nbt(data): + r = _Lecteur(data) + t = r.u(">b", 1) + if t != TAG_COMPOUND: + raise ValueError("racine NBT non compound") + r.chaine() + return r.charge(TAG_COMPOUND) + + +def lire_level_dat(chemin): + with gzip.open(chemin, "rb") as f: + return lire_nbt(f.read())["Data"] + + +def chunks_de_region(chemin): + """Itère (cx_local, cz_local, nbt) pour chaque chunk présent dans un fichier .mca.""" + with open(chemin, "rb") as f: + data = f.read() + if len(data) < 8192: + return + for i in range(1024): + off = int.from_bytes(data[i * 4:i * 4 + 3], "big") + nsec = data[i * 4 + 3] + if off == 0 or nsec == 0: + continue + p = off * 4096 + if p + 5 > len(data): + continue + longueur = int.from_bytes(data[p:p + 4], "big") + comp = data[p + 4] + brut = data[p + 5:p + 4 + longueur] + try: + if comp == 2: + nbt = lire_nbt(zlib.decompress(brut)) + elif comp == 1: + nbt = lire_nbt(gzip.decompress(brut)) + elif comp == 3: + nbt = lire_nbt(brut) + else: + continue # chunk externe (.mcc) ou compression inconnue : ignoré + except Exception: + continue + yield i % 32, i // 32, nbt + + +def deplier(longs, n_valeurs, bits): + """Décode un tableau compacté (format 1.16+ : les valeurs ne chevauchent pas deux longs).""" + par_long = 64 // bits + masque = np.uint64((1 << bits) - 1) + a = np.asarray(longs, dtype=np.uint64) + decal = (np.arange(par_long, dtype=np.uint64) * np.uint64(bits)) + vals = ((a[:, None] >> decal[None, :]) & masque).reshape(-1) + return vals[:n_valeurs].astype(np.int64) + + +def heightmap(longs, min_y): + """Heightmap 16x16 -> tableau [z, x] de hauteurs absolues (premier bloc libre au-dessus).""" + if longs is None or len(longs) == 0: + return None + par_long = -(-256 // len(longs)) + bits = 64 // par_long + return (deplier(longs, 256, bits) + min_y).reshape(16, 16) + + +def bits_pour(n, minimum): + b = max(1, (n - 1).bit_length()) + return max(minimum, b) if n > 1 else 0 diff --git a/src/main/java/com/gastineltpa/ClaimsBridge.java b/src/main/java/com/gastineltpa/ClaimsBridge.java new file mode 100644 index 0000000..101f302 --- /dev/null +++ b/src/main/java/com/gastineltpa/ClaimsBridge.java @@ -0,0 +1,54 @@ +package com.gastineltpa; + +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.neoforged.fml.ModList; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.UUID; + +/** + * Lien optionnel vers GastinelClaims, par réflexion (pas de dépendance de compilation) : + * si le mod est absent ou change d'API, on considère qu'il n'y a pas de claim (et on le journalise une fois). + */ +final class ClaimsBridge { + + private static boolean init; + private static Method get, registry, canAccess; + private static Constructor chunkKey; + + private ClaimsBridge() {} + + private static synchronized boolean pret() { + if (init) return get != null; + init = true; + if (!ModList.get().isLoaded("gastinelclaims")) return false; + try { + Class data = Class.forName("com.gastinelclaims.ClaimsData"); + Class reg = Class.forName("com.gastinelclaims.core.ClaimRegistry"); + Class key = Class.forName("com.gastinelclaims.core.ChunkKey"); + get = data.getMethod("get", MinecraftServer.class); + registry = data.getMethod("registry"); + canAccess = reg.getMethod("canAccess", UUID.class, key, boolean.class); + chunkKey = key.getConstructor(String.class, int.class, int.class); + GastinelTpa.LOGGER.info("[GastinelTpa] GastinelClaims détecté : /rtp évite les claims des autres."); + } catch (ReflectiveOperationException e) { + get = null; + GastinelTpa.LOGGER.warn("[GastinelTpa] API GastinelClaims introuvable, claims ignorés : {}", e.toString()); + } + return get != null; + } + + /** Vrai si le joueur a le droit d'être dans ce chunk (pas de claim, le sien, ou celui d'un ami). */ + static boolean autorise(ServerLevel level, UUID joueur, int blocX, int blocZ) { + if (!pret()) return true; + try { + Object reg = registry.invoke(get.invoke(null, level.getServer())); + Object key = chunkKey.newInstance(level.dimension().location().toString(), blocX >> 4, blocZ >> 4); + return (Boolean) canAccess.invoke(reg, joueur, key, false); + } catch (ReflectiveOperationException | RuntimeException e) { + return true; + } + } +} diff --git a/src/main/java/com/gastineltpa/GastinelTpa.java b/src/main/java/com/gastineltpa/GastinelTpa.java index b34b6e3..9fc95a5 100644 --- a/src/main/java/com/gastineltpa/GastinelTpa.java +++ b/src/main/java/com/gastineltpa/GastinelTpa.java @@ -1,7 +1,9 @@ package com.gastineltpa; 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; @@ -12,8 +14,11 @@ public class GastinelTpa { public static final String MOD_ID = "gastineltpa"; public static final Logger LOGGER = LoggerFactory.getLogger(GastinelTpa.class); - public GastinelTpa(IEventBus modEventBus) { + public GastinelTpa(IEventBus modEventBus, ModContainer modContainer) { + // Config serveur : /serverconfig/gastineltpa-server.toml + modContainer.registerConfig(ModConfig.Type.SERVER, TpConfig.SPEC); NeoForge.EVENT_BUS.register(TpaCommands.class); - LOGGER.info("[GastinelTpa] Demandes de téléportation chargées."); + NeoForge.EVENT_BUS.register(SpawnRtpCommands.class); + LOGGER.info("[GastinelTpa] Téléportations chargées (/tpa, /spawn, /rtp)."); } } diff --git a/src/main/java/com/gastineltpa/SpawnRtpCommands.java b/src/main/java/com/gastineltpa/SpawnRtpCommands.java new file mode 100644 index 0000000..acef973 --- /dev/null +++ b/src/main/java/com/gastineltpa/SpawnRtpCommands.java @@ -0,0 +1,506 @@ +package com.gastineltpa; + +import com.gastineltpa.core.Cooldowns; +import com.gastineltpa.core.RtpLogic; +import com.gastineltpa.core.RtpLogic.Spot; +import com.gastineltpa.core.RtpLogic.Zone; +import com.gastineltpa.core.Warmups; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.mojang.brigadier.CommandDispatcher; +import com.mojang.brigadier.context.CommandContext; +import com.mojang.brigadier.exceptions.CommandSyntaxException; +import net.minecraft.ChatFormatting; +import net.minecraft.commands.CommandSource; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.EntityArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.chat.Component; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.tags.BlockTags; +import net.minecraft.world.level.BaseCommandBlock; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.levelgen.Heightmap; +import net.minecraft.world.phys.Vec3; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.RegisterCommandsEvent; +import net.neoforged.neoforge.event.entity.living.LivingDamageEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.server.ServerStartedEvent; +import net.neoforged.neoforge.event.tick.ServerTickEvent; + +import java.io.Reader; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.function.Consumer; +import java.util.function.Supplier; + +/** /spawn, /rtp, /rtp spawn (blocs de commande), /rtp recharger (op). */ +public final class SpawnRtpCommands { + + private static final Cooldowns RECHARGES = new Cooldowns(System::currentTimeMillis); + private static final Warmups ATTENTES = new Warmups(); + /** Action à lancer quand l'attente d'un joueur se termine. */ + private static final Map ACTIONS = new HashMap<>(); + /** Joueurs dont une recherche /rtp est en cours (évite les doublons). */ + private static final java.util.Set RECHERCHES = new java.util.HashSet<>(); + private static volatile List SPOTS = List.of(); + + @SubscribeEvent + public static void onRegister(RegisterCommandsEvent event) { + CommandDispatcher d = event.getDispatcher(); + d.register(Commands.literal("spawn").executes(SpawnRtpCommands::spawn)); + d.register(Commands.literal("rtp") + .executes(SpawnRtpCommands::rtp) + .then(Commands.literal("spawn") + .executes(ctx -> rtpSpawn(ctx, null)) + .then(Commands.argument("joueurs", EntityArgument.players()) + .executes(ctx -> rtpSpawn(ctx, EntityArgument.getPlayers(ctx, "joueurs"))))) + .then(Commands.literal("diagnostic") + .requires(s -> s.hasPermission(2)) + .executes(ctx -> diagnostic(ctx, false)) + .then(Commands.literal("spawn").executes(ctx -> diagnostic(ctx, true)))) + .then(Commands.literal("recharger") + .requires(s -> s.hasPermission(2)) + .executes(ctx -> { + int n = chargerSpots(ctx.getSource().getServer()); + ctx.getSource().sendSuccess(() -> info(n + " beaux spots chargés."), true); + return n; + }))); + } + + @SubscribeEvent + public static void onStarted(ServerStartedEvent event) { + chargerSpots(event.getServer()); + } + + // --- /spawn --- + + private static int spawn(CommandContext ctx) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + if (!disponible(ctx, p, "spawn")) return 0; + int delai = TpConfig.get(TpConfig.SPAWN_DELAI); + demarrer(p, "spawn", delai, () -> { + ServerLevel monde = p.server.overworld(); + BlockPos s = monde.getSharedSpawnPos(); + BlockPos pieds = libre(monde, s) ? s + : new BlockPos(s.getX(), monde.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, s.getX(), s.getZ()), s.getZ()); + teleporter(p, monde, pieds, monde.getSharedSpawnAngle()); + RECHARGES.start(p.getUUID(), "spawn", TpConfig.get(TpConfig.SPAWN_RECHARGE)); + p.sendSystemMessage(succes("Bienvenue au spawn !")); + }); + return 1; + } + + // --- /rtp --- + + private static int rtp(CommandContext ctx) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + if (!disponible(ctx, p, "rtp")) return 0; + if (RECHERCHES.contains(p.getUUID())) return echec(ctx, "Une recherche est déjà en cours."); + Zone zone = zone(); + demarrer(p, "rtp", TpConfig.get(TpConfig.RTP_DELAI), () -> { + p.sendSystemMessage(info("Recherche d'un endroit sûr…")); + chercher(p, TpConfig.get(TpConfig.RTP_ESSAIS), () -> { + int[] xz = zone.tirer(ThreadLocalRandom.current()); + return xz == null ? null : new BlockPos(xz[0], 0, xz[1]); + }, pos -> { + RECHARGES.start(p.getUUID(), "rtp", TpConfig.get(TpConfig.RTP_RECHARGE)); + p.sendSystemMessage(succes("Téléporté en " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + ". Bonne exploration !")); + }); + }); + return 1; + } + + // --- /rtp spawn (blocs de commande uniquement) --- + + private static int rtpSpawn(CommandContext ctx, Collection cibles) { + CommandSourceStack src = ctx.getSource(); + if (!depuisBlocDeCommande(src)) { + return echec(ctx, "/rtp spawn est réservé à la plaque de pression de l'entrée (bloc de commande). " + + "Utilise /rtp pour une téléportation aléatoire."); + } + List joueurs = new ArrayList<>(); + if (cibles != null) { + joueurs.addAll(cibles); + } else { + // Sans argument : le joueur le plus proche du bloc, à 4 blocs maximum. + Vec3 o = src.getPosition(); + ServerPlayer proche = null; + double best = 16.0; + for (ServerPlayer sp : src.getLevel().players()) { + double d2 = sp.position().distanceToSqr(o); + if (d2 <= best) { + best = d2; + proche = sp; + } + } + if (proche != null) joueurs.add(proche); + } + if (SPOTS.isEmpty()) { + GastinelTpa.LOGGER.warn("[GastinelTpa] /rtp spawn : aucun beau spot chargé ({}).", TpConfig.get(TpConfig.SPOTS_FICHIER)); + } + int n = 0; + for (ServerPlayer p : joueurs) { + if (RECHERCHES.contains(p.getUUID())) continue; + if (RECHARGES.remaining(p.getUUID(), "rtpspawn") > 0) continue; // plaque : silencieux + RECHARGES.start(p.getUUID(), "rtpspawn", TpConfig.get(TpConfig.SPAWN_RTP_RECHARGE)); + List top = RtpLogic.top(SPOTS, TpConfig.get(TpConfig.SPAWN_RTP_TOP)); + Zone zone = zone(); + p.sendSystemMessage(info("En route vers un bel endroit de la carte…")); + chercher(p, TpConfig.get(TpConfig.RTP_ESSAIS), () -> { + ThreadLocalRandom r = ThreadLocalRandom.current(); + Spot s = RtpLogic.tirerPondere(top, r); + if (s != null) return new BlockPos(s.x() + r.nextInt(-2, 3), 0, s.z() + r.nextInt(-2, 3)); + int[] xz = zone.tirer(r); // aucun spot : repli sur la zone /rtp + return xz == null ? null : new BlockPos(xz[0], 0, xz[1]); + }, pos -> p.sendSystemMessage(succes("Bienvenue ! Tape /guide si tu veux de l'aide."))); + n++; + } + return n; + } + + /** Op : cherche un point comme /rtp (ou /rtp spawn) sans téléporter personne, et l'affiche. */ + private static int diagnostic(CommandContext ctx, boolean beauxSpots) { + CommandSourceStack src = ctx.getSource(); + Zone zone = zone(); + List top = RtpLogic.top(SPOTS, TpConfig.get(TpConfig.SPAWN_RTP_TOP)); + int[] tires = {0}; + RAISONS.clear(); + UUID personne = new UUID(0L, 0L); + rechercher(src.getServer(), personne, () -> true, TpConfig.get(TpConfig.RTP_ESSAIS), () -> { + tires[0]++; + ThreadLocalRandom r = ThreadLocalRandom.current(); + if (beauxSpots && !top.isEmpty()) { + Spot s = RtpLogic.tirerPondere(top, r); + return new BlockPos(s.x() + r.nextInt(-2, 3), 0, s.z() + r.nextInt(-2, 3)); + } + int[] xz = zone.tirer(r); + return xz == null ? null : new BlockPos(xz[0], 0, xz[1]); + }, pos -> { + String m = "[diagnostic] point sûr " + pos.getX() + " " + pos.getY() + " " + pos.getZ() + " après " + tires[0] + " tirage(s)" + " ; rejets : " + RAISONS; + GastinelTpa.LOGGER.info("[GastinelTpa] {}", m); + src.sendSuccess(() -> info(m), false); + }, () -> { + String m = "[diagnostic] aucun point sûr après " + tires[0] + " tirage(s)" + " ; rejets : " + RAISONS; + GastinelTpa.LOGGER.info("[GastinelTpa] {}", m); + src.sendSuccess(() -> erreur(m), false); + }); + return 1; + } + + /** Vrai si la commande vient d'un bloc de commande (ou d'un minecart de commande). */ + static boolean depuisBlocDeCommande(CommandSourceStack src) { + if (src.getEntity() instanceof ServerPlayer) return false; + try { + Field f = CommandSourceStack.class.getDeclaredField("source"); + f.setAccessible(true); + CommandSource s = (CommandSource) f.get(src); + return s instanceof BaseCommandBlock; + } catch (ReflectiveOperationException | RuntimeException e) { + GastinelTpa.LOGGER.warn("[GastinelTpa] Source de commande illisible, /rtp spawn refusé : {}", e.toString()); + return false; + } + } + + // --- Recherche asynchrone d'un point sûr (jamais de génération de chunk) --- + + /** Recherche pour un joueur : téléporte au premier point sûr, sinon message d'échec. */ + private static void chercher(ServerPlayer p, int essais, Supplier tirage, Consumer ok) { + RECHERCHES.add(p.getUUID()); + rechercher(p.server, p.getUUID(), () -> !p.isRemoved() && p.server.getPlayerList().getPlayer(p.getUUID()) != null, + essais, tirage, pos -> { + RECHERCHES.remove(p.getUUID()); + teleporter(p, p.server.overworld(), pos, p.getYRot()); + ok.accept(pos); + }, () -> { + RECHERCHES.remove(p.getUUID()); + p.sendSystemMessage(erreur("Aucun endroit sûr trouvé après plusieurs essais. Réessaie dans un instant.")); + }); + } + + /** + * Essaie jusqu'à {@code restants} points tirés. Un point n'est examiné que si son chunk est déjà chargé ou + * présent sur le disque avec le statut « full » ; la colonne testée est gardée à l'intérieur du chunk + * (bords exclus) pour que la vérification des voisins ne touche jamais un autre chunk. + */ + static void rechercher(MinecraftServer server, UUID joueur, java.util.function.BooleanSupplier actif, int restants, + Supplier tirage, Consumer ok, Runnable echec) { + if (!actif.getAsBoolean()) { + RECHERCHES.remove(joueur); + return; + } + BlockPos tire = restants > 0 ? tirage.get() : null; + if (tire == null) { + echec.run(); + return; + } + int cx = tire.getX() >> 4, cz = tire.getZ() >> 4; + BlockPos xz = new BlockPos((cx << 4) + Math.clamp(tire.getX() & 15, 1, 14), 0, + (cz << 4) + Math.clamp(tire.getZ() & 15, 1, 14)); + ServerLevel monde = server.overworld(); + Runnable suivant = () -> rechercher(server, joueur, actif, restants - 1, tirage, ok, echec); + if (!monde.getWorldBorder().isWithinBounds(xz) || !ClaimsBridge.autorise(monde, joueur, xz.getX(), xz.getZ())) { + note("bordure-ou-claim"); + server.execute(suivant); + return; + } + Runnable verifier = () -> { + if (!actif.getAsBoolean()) { + RECHERCHES.remove(joueur); + return; + } + Optional pieds = pointSur(monde, xz.getX(), xz.getZ()); + if (pieds.isPresent()) ok.accept(pieds.get()); + else server.execute(suivant); + }; + // Le chunk ET ses 8 voisins doivent être complets (chargés, ou « full » sur le disque) : charger un chunk + // dont un voisin manque ferait créer ce voisin (proto-chunk) pour l'éclairage = génération. Lecture sur + // le thread d'E/S ; absent ou incomplet -> point refusé, rien n'est généré. + List> lectures = new ArrayList<>(); + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + int ccx = cx + i, ccz = cz + j; + if (monde.getChunkSource().getChunkNow(ccx, ccz) != null) continue; + // Fichier région absent : on ne le lit pas (la lecture créerait un r.X.Z.mca vide). + Path region = server.getWorldPath(net.minecraft.world.level.storage.LevelResource.ROOT) + .resolve("region").resolve("r." + (ccx >> 5) + "." + (ccz >> 5) + ".mca"); + try { + if (!Files.isRegularFile(region) || Files.size(region) < 8192) { + note("region-absente"); + server.execute(suivant); + return; + } + } catch (java.io.IOException e) { + note("region-illisible"); + server.execute(suivant); + return; + } + lectures.add(monde.getChunkSource().chunkMap.read(new ChunkPos(ccx, ccz)) + .handle((opt, err) -> err != null ? "lecture-erreur" + : opt.isEmpty() ? "chunk-absent" + : complet(opt.get()) ? null : "chunk-incomplet")); + } + } + if (lectures.isEmpty()) { + verifier.run(); + return; + } + java.util.concurrent.CompletableFuture.allOf(lectures.toArray(new java.util.concurrent.CompletableFuture[0])) + .whenComplete((v, e) -> server.execute(() -> { + String probleme = null; + for (var f : lectures) { + String r = f.getNow("lecture-erreur"); + if (r != null) { + probleme = r; + break; + } + } + if (probleme == null) verifier.run(); + else { + note(probleme); + suivant.run(); + } + })); + } + + /** Motifs de rejet (pour /rtp diagnostic). */ + static final java.util.concurrent.ConcurrentHashMap RAISONS = new java.util.concurrent.ConcurrentHashMap<>(); + + private static void note(String raison) { + RAISONS.merge(raison.length() > 60 ? raison.substring(0, 60) : raison, 1, Integer::sum); + } + + private static Optional rejet(String raison) { + note(raison); + return Optional.empty(); + } + + private static boolean complet(CompoundTag tag) { + String s = tag.getString("Status"); + return "minecraft:full".equals(s) || "full".equals(s); + } + + /** Position des pieds si la colonne (x, z) est sûre, sinon vide. Le chunk doit exister (complet). */ + static Optional pointSur(ServerLevel monde, int x, int z) { + // Chargement explicite (depuis le disque, chunk complet vérifié avant) : Level.getHeight() renvoie + // la hauteur minimale pour un chunk non chargé. + net.minecraft.world.level.chunk.LevelChunk chunk = monde.getChunk(x >> 4, z >> 4); + int y = chunk.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x & 15, z & 15) + 1; + if (y <= monde.getMinBuildHeight() + 5 || y >= monde.getMaxBuildHeight() - 2) return rejet("hauteur"); + BlockPos pieds = new BlockPos(x, y, z); + BlockPos sol = pieds.below(); + BlockState s = monde.getBlockState(sol); + if (!s.getFluidState().isEmpty() || s.is(BlockTags.LEAVES) || s.is(BlockTags.LOGS) + || dangereux(s) || !s.isFaceSturdy(monde, sol, Direction.UP)) return rejet("sol:" + BuiltInRegistries.BLOCK.getKey(s.getBlock()).getPath()); + if (!libre(monde, pieds)) return rejet("pas-libre"); + for (int dx = -1; dx <= 1; dx++) { + for (int dz = -1; dz <= 1; dz++) { + for (int dy = -1; dy <= 1; dy++) { + BlockState v = monde.getBlockState(pieds.offset(dx, dy, dz)); + if (dangereux(v) || v.getFluidState().is(net.minecraft.tags.FluidTags.LAVA)) return rejet("danger-voisin"); + } + // Pas de falaise ni de trou juste à côté + int h = monde.getHeight(Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, x + dx, z + dz); + if (Math.abs(h - y) > 3) return rejet("pente"); + if (!monde.getBlockState(new BlockPos(x + dx, h - 1, z + dz)).getFluidState().isEmpty() && (dx != 0 || dz != 0)) { + // eau voisine tolérée seulement si peu profonde + if (!monde.getBlockState(new BlockPos(x + dx, h - 3, z + dz)).getFluidState().isEmpty()) return rejet("eau-profonde-voisine"); + } + } + } + return Optional.of(pieds); + } + + private static boolean dangereux(BlockState s) { + return RtpLogic.dangereux(BuiltInRegistries.BLOCK.getKey(s.getBlock()).toString()); + } + + private static boolean libre(ServerLevel monde, BlockPos pieds) { + for (BlockPos b : new BlockPos[]{pieds, pieds.above()}) { + BlockState s = monde.getBlockState(b); + if (!s.getCollisionShape(monde, b).isEmpty() || !s.getFluidState().isEmpty() || dangereux(s)) return false; + } + return true; + } + + // --- Délai, annulation, recharge --- + + private static boolean disponible(CommandContext ctx, ServerPlayer p, String cmd) { + int reste = RECHARGES.remaining(p.getUUID(), cmd); + if (reste > 0) { + echec(ctx, "Patiente encore " + duree(reste) + " avant de refaire /" + cmd + "."); + return false; + } + return true; + } + + private static void demarrer(ServerPlayer p, String cmd, int delaiSecondes, Runnable action) { + if (delaiSecondes <= 0) { + action.run(); + return; + } + ATTENTES.start(p.getUUID(), cmd, p.getX(), p.getY(), p.getZ(), delaiSecondes * 20); + ACTIONS.put(p.getUUID(), action); + p.sendSystemMessage(info("Téléportation dans " + delaiSecondes + " s, ne bouge pas…")); + } + + @SubscribeEvent + public static void onTick(ServerTickEvent.Post event) { + MinecraftServer server = event.getServer(); + for (Warmups.Resultat r : ATTENTES.tick(id -> { + ServerPlayer sp = server.getPlayerList().getPlayer(id); + return sp == null ? null : new double[]{sp.getX(), sp.getY(), sp.getZ()}; + })) { + Runnable action = ACTIONS.remove(r.joueur()); + ServerPlayer sp = server.getPlayerList().getPlayer(r.joueur()); + if (sp == null) continue; + if (r.fin() == Warmups.Fin.BOUGE) { + sp.sendSystemMessage(erreur("Téléportation annulée : tu as bougé.")); + } else if (action != null) { + action.run(); + } + } + } + + @SubscribeEvent + public static void onDamage(LivingDamageEvent.Post event) { + if (event.getEntity() instanceof ServerPlayer sp && ATTENTES.cancel(sp.getUUID()) != null) { + ACTIONS.remove(sp.getUUID()); + sp.sendSystemMessage(erreur("Téléportation annulée : tu as été blessé.")); + } + } + + @SubscribeEvent + public static void onLogout(PlayerEvent.PlayerLoggedOutEvent event) { + UUID id = event.getEntity().getUUID(); + ATTENTES.cancel(id); + ACTIONS.remove(id); + RECHERCHES.remove(id); + } + + // --- Beaux spots --- + + static int chargerSpots(MinecraftServer server) { + Path f = server.getServerDirectory().resolve(TpConfig.get(TpConfig.SPOTS_FICHIER)); + if (!Files.isRegularFile(f)) { + SPOTS = List.of(); + GastinelTpa.LOGGER.warn("[GastinelTpa] Fichier de beaux spots absent : {} (/rtp spawn utilisera la zone /rtp).", f); + return 0; + } + try (Reader r = Files.newBufferedReader(f, StandardCharsets.UTF_8)) { + JsonObject racine = JsonParser.parseReader(r).getAsJsonObject(); + JsonArray tab = racine.getAsJsonArray("spots"); + List l = new ArrayList<>(); + for (JsonElement e : tab) { + JsonObject o = e.getAsJsonObject(); + l.add(new Spot(o.get("x").getAsInt(), o.get("y").getAsInt(), o.get("z").getAsInt(), + o.get("score").getAsDouble(), o.has("biome") ? o.get("biome").getAsString() : "?")); + } + SPOTS = List.copyOf(l); + GastinelTpa.LOGGER.info("[GastinelTpa] {} beaux spots chargés depuis {}.", l.size(), f); + return l.size(); + } catch (Exception e) { + GastinelTpa.LOGGER.error("[GastinelTpa] Lecture de {} impossible : {}", f, e.toString()); + return 0; + } + } + + private static Zone zone() { + return new Zone(TpConfig.get(TpConfig.ZONE_X_MIN), TpConfig.get(TpConfig.ZONE_X_MAX), + TpConfig.get(TpConfig.ZONE_Z_MIN), TpConfig.get(TpConfig.ZONE_Z_MAX), + TpConfig.get(TpConfig.ZONE_CENTRE_X), TpConfig.get(TpConfig.ZONE_CENTRE_Z), + TpConfig.get(TpConfig.ZONE_RAYON)); + } + + // --- Utilitaires --- + + private static void teleporter(ServerPlayer p, ServerLevel monde, BlockPos pieds, float yaw) { + p.stopRiding(); + p.teleportTo(monde, pieds.getX() + 0.5, pieds.getY(), pieds.getZ() + 0.5, yaw, p.getXRot()); + p.fallDistance = 0; + } + + private static String duree(int s) { + return s >= 60 ? (s / 60) + " min " + (s % 60) + " s" : s + " s"; + } + + private static int echec(CommandContext ctx, String message) { + ctx.getSource().sendFailure(Component.literal(message)); + return 0; + } + + private static Component info(String s) { + return Component.literal("[TP] ").withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.YELLOW)); + } + + private static Component succes(String s) { + return Component.literal("[TP] ").withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.GREEN)); + } + + private static Component erreur(String s) { + return Component.literal("[TP] ").withStyle(ChatFormatting.GOLD) + .append(Component.literal(s).withStyle(ChatFormatting.RED)); + } +} diff --git a/src/main/java/com/gastineltpa/TpConfig.java b/src/main/java/com/gastineltpa/TpConfig.java new file mode 100644 index 0000000..953e72a --- /dev/null +++ b/src/main/java/com/gastineltpa/TpConfig.java @@ -0,0 +1,75 @@ +package com.gastineltpa; + +import net.neoforged.neoforge.common.ModConfigSpec; + +/** config/gastineltpa-server.toml (fichier serveur, rechargé à chaud par NeoForge). */ +public final class TpConfig { + + public static final ModConfigSpec SPEC; + + public static final ModConfigSpec.IntValue SPAWN_DELAI; + public static final ModConfigSpec.IntValue SPAWN_RECHARGE; + + public static final ModConfigSpec.IntValue RTP_DELAI; + public static final ModConfigSpec.IntValue RTP_RECHARGE; + public static final ModConfigSpec.IntValue RTP_ESSAIS; + public static final ModConfigSpec.IntValue ZONE_X_MIN, ZONE_X_MAX, ZONE_Z_MIN, ZONE_Z_MAX; + public static final ModConfigSpec.IntValue ZONE_CENTRE_X, ZONE_CENTRE_Z, ZONE_RAYON; + + public static final ModConfigSpec.IntValue SPAWN_RTP_RECHARGE; + public static final ModConfigSpec.IntValue SPAWN_RTP_TOP; + public static final ModConfigSpec.ConfigValue SPOTS_FICHIER; + + static { + ModConfigSpec.Builder b = new ModConfigSpec.Builder(); + + b.comment("/spawn : téléporte au point de spawn du monde (lu dans level.dat, défini par /setworldspawn).") + .push("spawn"); + SPAWN_DELAI = b.comment("Délai avant téléportation, en secondes (annulé si le joueur bouge ou est blessé).") + .defineInRange("delaiSecondes", 3, 0, 60); + SPAWN_RECHARGE = b.comment("Temps de recharge entre deux /spawn, en secondes.") + .defineInRange("rechargeSecondes", 60, 0, 86400); + b.pop(); + + b.comment("/rtp : téléportation aléatoire dans la zone DÉJÀ générée (jamais de nouveau chunk).") + .push("rtp"); + RTP_DELAI = b.comment("Délai avant téléportation, en secondes.").defineInRange("delaiSecondes", 3, 0, 60); + RTP_RECHARGE = b.comment("Temps de recharge entre deux /rtp, en secondes.") + .defineInRange("rechargeSecondes", 300, 0, 86400); + RTP_ESSAIS = b.comment("Nombre d'endroits essayés avant d'abandonner.").defineInRange("essais", 100, 1, 300); + b.comment("Zone de tirage (blocs). Mesuré le 09/10/2026 sur une copie de neW512 (outils/beaux_spots.py) :", + "89 397 chunks complets, de x -512..6831 et z -5632..1167 (pas un rectangle plein : beaucoup", + "d'océan). Pas de worldborder (vanilla). Les chunks absents du disque sont toujours refusés."); + ZONE_X_MIN = b.defineInRange("zoneXMin", -512, -30000000, 30000000); + ZONE_X_MAX = b.defineInRange("zoneXMax", 6831, -30000000, 30000000); + ZONE_Z_MIN = b.defineInRange("zoneZMin", -5632, -30000000, 30000000); + ZONE_Z_MAX = b.defineInRange("zoneZMax", 1167, -30000000, 30000000); + ZONE_CENTRE_X = b.comment("Centre du disque autorisé (avec zoneRayon).") + .defineInRange("zoneCentreX", 5566, -30000000, 30000000); + ZONE_CENTRE_Z = b.defineInRange("zoneCentreZ", -990, -30000000, 30000000); + ZONE_RAYON = b.comment("Rayon du disque autorisé ; 0 = rectangle seul.") + .defineInRange("zoneRayon", 0, 0, 30000000); + b.pop(); + + b.comment("/rtp spawn : réservé aux blocs de commande (plaque de pression de l'entrée).").push("rtpSpawn"); + SPAWN_RTP_RECHARGE = b.comment("Recharge par joueur, en secondes (évite les doubles déclenchements).") + .defineInRange("rechargeSecondes", 10, 0, 86400); + SPAWN_RTP_TOP = b.comment("Tirage parmi les N meilleurs spots de beaux-spots.json (pondéré par le score).") + .defineInRange("topN", 60, 1, 100000); + SPOTS_FICHIER = b.comment("Fichier des spots, relatif au dossier du serveur. Rechargé par /rtp recharger (op).") + .define("fichierSpots", "config/gastineltpa/beaux-spots.json"); + b.pop(); + + SPEC = b.build(); + } + + static int get(ModConfigSpec.IntValue v) { + return SPEC.isLoaded() ? v.get() : v.getDefault(); + } + + static String get(ModConfigSpec.ConfigValue v) { + return SPEC.isLoaded() ? v.get() : v.getDefault(); + } + + private TpConfig() {} +} diff --git a/src/main/java/com/gastineltpa/core/Cooldowns.java b/src/main/java/com/gastineltpa/core/Cooldowns.java new file mode 100644 index 0000000..a6e1bd8 --- /dev/null +++ b/src/main/java/com/gastineltpa/core/Cooldowns.java @@ -0,0 +1,42 @@ +package com.gastineltpa.core; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.function.LongSupplier; + +/** Temps de recharge par joueur et par commande. Logique pure, horloge injectable. */ +public final class Cooldowns { + + private final LongSupplier clock; + private final Map fin = new HashMap<>(); + + public Cooldowns(LongSupplier clockMs) { + this.clock = clockMs; + } + + private static String cle(UUID joueur, String commande) { + return commande + "|" + joueur; + } + + /** Démarre la recharge (durée en secondes ; 0 ou moins = pas de recharge). */ + public void start(UUID joueur, String commande, int secondes) { + if (secondes <= 0) { + fin.remove(cle(joueur, commande)); + return; + } + fin.put(cle(joueur, commande), clock.getAsLong() + secondes * 1000L); + } + + /** Secondes restantes (arrondi supérieur), 0 si la commande est disponible. */ + public int remaining(UUID joueur, String commande) { + Long f = fin.get(cle(joueur, commande)); + if (f == null) return 0; + long reste = f - clock.getAsLong(); + if (reste <= 0) { + fin.remove(cle(joueur, commande)); + return 0; + } + return (int) ((reste + 999) / 1000); + } +} diff --git a/src/main/java/com/gastineltpa/core/RtpLogic.java b/src/main/java/com/gastineltpa/core/RtpLogic.java new file mode 100644 index 0000000..6431b96 --- /dev/null +++ b/src/main/java/com/gastineltpa/core/RtpLogic.java @@ -0,0 +1,67 @@ +package com.gastineltpa.core; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.random.RandomGenerator; + +/** Règles pures de /rtp : zone, blocs dangereux, tirage pondéré des beaux spots. */ +public final class RtpLogic { + + private RtpLogic() {} + + /** Blocs sur lesquels (ou à côté desquels) on n'atterrit jamais. */ + public static final Set DANGEREUX = Set.of( + "minecraft:lava", "minecraft:fire", "minecraft:soul_fire", "minecraft:magma_block", + "minecraft:cactus", "minecraft:sweet_berry_bush", "minecraft:campfire", "minecraft:soul_campfire", + "minecraft:powder_snow", "minecraft:pointed_dripstone", "minecraft:wither_rose"); + + public static boolean dangereux(String id) { + return DANGEREUX.contains(id); + } + + /** Rectangle de la zone autorisée (bornes incluses, en blocs) + rayon optionnel autour d'un centre. */ + public record Zone(int xMin, int xMax, int zMin, int zMax, int centreX, int centreZ, int rayon) { + public boolean contient(int x, int z) { + if (x < xMin || x > xMax || z < zMin || z > zMax) return false; + if (rayon <= 0) return true; + long dx = x - centreX, dz = z - centreZ; + return dx * dx + dz * dz <= (long) rayon * rayon; + } + + /** Tire un point de la zone (rejet si hors du disque) ; null si la zone est vide. */ + public int[] tirer(RandomGenerator rnd) { + if (xMax < xMin || zMax < zMin) return null; + for (int i = 0; i < 64; i++) { + int x = xMin + rnd.nextInt(xMax - xMin + 1); + int z = zMin + rnd.nextInt(zMax - zMin + 1); + if (contient(x, z)) return new int[]{x, z}; + } + return null; + } + } + + public record Spot(int x, int y, int z, double score, String biome) {} + + /** Les N meilleurs spots (score décroissant). */ + public static List top(List spots, int n) { + List l = new ArrayList<>(spots); + l.sort(Comparator.comparingDouble(Spot::score).reversed()); + return l.subList(0, Math.min(Math.max(0, n), l.size())); + } + + /** Tirage pondéré par le score (score <= 0 : poids nul, sauf si tous sont nuls). */ + public static Spot tirerPondere(List spots, RandomGenerator rnd) { + if (spots.isEmpty()) return null; + double total = 0; + for (Spot s : spots) total += Math.max(0, s.score()); + if (total <= 0) return spots.get(rnd.nextInt(spots.size())); + double r = rnd.nextDouble() * total; + for (Spot s : spots) { + r -= Math.max(0, s.score()); + if (r < 0) return s; + } + return spots.get(spots.size() - 1); + } +} diff --git a/src/main/java/com/gastineltpa/core/Warmups.java b/src/main/java/com/gastineltpa/core/Warmups.java new file mode 100644 index 0000000..1b84d1e --- /dev/null +++ b/src/main/java/com/gastineltpa/core/Warmups.java @@ -0,0 +1,71 @@ +package com.gastineltpa.core; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * Téléportations en attente (délai avant départ). Annulées si le joueur bouge ou est blessé. + * Logique pure : on lui donne les positions à chaque tick. + */ +public final class Warmups { + + /** Distance maximale tolérée (en blocs) avant annulation. */ + public static final double TOLERANCE = 0.6; + + public enum Fin { PRET, BOUGE } + + public record Attente(UUID joueur, String commande, double x, double y, double z, int ticksRestants) {} + + public record Resultat(UUID joueur, String commande, Fin fin) {} + + private final Map attentes = new HashMap<>(); + + /** Démarre (ou remplace) l'attente d'un joueur. */ + public void start(UUID joueur, String commande, double x, double y, double z, int ticks) { + attentes.put(joueur, new Attente(joueur, commande, x, y, z, Math.max(0, ticks))); + } + + public boolean has(UUID joueur) { + return attentes.containsKey(joueur); + } + + /** Retire l'attente (blessure, déconnexion). Renvoie la commande annulée ou null. */ + public String cancel(UUID joueur) { + Attente a = attentes.remove(joueur); + return a == null ? null : a.commande(); + } + + public interface Positions { + /** Position actuelle du joueur, ou null s'il n'est plus là. */ + double[] of(UUID joueur); + } + + /** Avance d'un tick : renvoie les attentes terminées (prêtes ou annulées pour mouvement). */ + public List tick(Positions positions) { + List out = new ArrayList<>(); + for (Iterator> it = attentes.entrySet().iterator(); it.hasNext(); ) { + Map.Entry e = it.next(); + Attente a = e.getValue(); + double[] p = positions.of(a.joueur()); + if (p == null) { + it.remove(); + continue; + } + double dx = p[0] - a.x(), dy = p[1] - a.y(), dz = p[2] - a.z(); + if (dx * dx + dy * dy + dz * dz > TOLERANCE * TOLERANCE) { + it.remove(); + out.add(new Resultat(a.joueur(), a.commande(), Fin.BOUGE)); + } else if (a.ticksRestants() <= 1) { + it.remove(); + out.add(new Resultat(a.joueur(), a.commande(), Fin.PRET)); + } else { + e.setValue(new Attente(a.joueur(), a.commande(), a.x(), a.y(), a.z(), a.ticksRestants() - 1)); + } + } + return out; + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml index 0f4bdc0..d2e2641 100644 --- a/src/main/resources/META-INF/neoforge.mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -4,10 +4,10 @@ license="MIT" [[mods]] modId="gastineltpa" -version="1.0.0" +version="1.1.0" displayName="GastinelTpa" authors="Théo Gastinel" -description='''Demandes de téléportation entre joueurs (/tpa, /tpahere, /tpaccept, /tpadeny). Mod côté serveur uniquement.''' +description='''Demandes de téléportation entre joueurs (/tpa, /tpahere, /tpaccept, /tpadeny), /spawn, /rtp et /rtp spawn (blocs de commande). Mod côté serveur uniquement.''' # Les clients n'ont pas besoin du mod : ne pas exiger sa présence côté client. displayTest="IGNORE_ALL_VERSION" diff --git a/src/test/java/com/gastineltpa/core/SpawnRtpCoreTest.java b/src/test/java/com/gastineltpa/core/SpawnRtpCoreTest.java new file mode 100644 index 0000000..825aac9 --- /dev/null +++ b/src/test/java/com/gastineltpa/core/SpawnRtpCoreTest.java @@ -0,0 +1,85 @@ +package com.gastineltpa.core; + +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.jupiter.api.Assertions.*; + +class SpawnRtpCoreTest { + + @Test + void recharge() { + AtomicLong t = new AtomicLong(0); + Cooldowns c = new Cooldowns(t::get); + UUID a = UUID.randomUUID(); + assertEquals(0, c.remaining(a, "spawn")); + c.start(a, "spawn", 60); + assertEquals(60, c.remaining(a, "spawn")); + assertEquals(0, c.remaining(a, "rtp")); + t.set(59_001); + assertEquals(1, c.remaining(a, "spawn")); + t.set(60_000); + assertEquals(0, c.remaining(a, "spawn")); + } + + @Test + void attentePuisDepart() { + Warmups w = new Warmups(); + UUID a = UUID.randomUUID(); + w.start(a, "spawn", 0, 64, 0, 3); + assertTrue(w.tick(id -> new double[]{0, 64, 0}).isEmpty()); + assertTrue(w.tick(id -> new double[]{0.2, 64, 0}).isEmpty()); + List r = w.tick(id -> new double[]{0, 64, 0}); + assertEquals(Warmups.Fin.PRET, r.get(0).fin()); + assertFalse(w.has(a)); + } + + @Test + void attenteAnnuleeSiMouvementOuBlessure() { + Warmups w = new Warmups(); + UUID a = UUID.randomUUID(); + w.start(a, "rtp", 0, 64, 0, 60); + assertEquals(Warmups.Fin.BOUGE, w.tick(id -> new double[]{1, 64, 0}).get(0).fin()); + w.start(a, "rtp", 0, 64, 0, 60); + assertEquals("rtp", w.cancel(a)); + assertNull(w.cancel(a)); + } + + @Test + void zoneEtDisque() { + RtpLogic.Zone z = new RtpLogic.Zone(-100, 100, -100, 100, 0, 0, 50); + assertTrue(z.contient(30, 30)); + assertFalse(z.contient(60, 60)); + Random r = new Random(1); + for (int i = 0; i < 200; i++) { + int[] p = z.tirer(r); + assertNotNull(p); + assertTrue(z.contient(p[0], p[1])); + } + assertNull(new RtpLogic.Zone(1, 0, 0, 0, 0, 0, 0).tirer(r)); + } + + @Test + void tirageParmiLesMeilleurs() { + List s = List.of(new RtpLogic.Spot(0, 0, 0, 9, "a"), new RtpLogic.Spot(1, 0, 0, 1, "b"), + new RtpLogic.Spot(2, 0, 0, 5, "c")); + List top = RtpLogic.top(s, 2); + assertEquals(List.of(9.0, 5.0), top.stream().map(RtpLogic.Spot::score).toList()); + Random r = new Random(2); + int a = 0; + for (int i = 0; i < 1400; i++) if (RtpLogic.tirerPondere(top, r).biome().equals("a")) a++; + assertTrue(a > 800 && a < 1000, "≈ 9/14 attendu, obtenu " + a); + assertNull(RtpLogic.tirerPondere(List.of(), r)); + } + + @Test + void blocsDangereux() { + assertTrue(RtpLogic.dangereux("minecraft:cactus")); + assertTrue(RtpLogic.dangereux("minecraft:sweet_berry_bush")); + assertFalse(RtpLogic.dangereux("minecraft:grass_block")); + } +}