commit c6f61950a304a9e16df91c2c32e4dfa8f8160c80 Author: Theo Gastinel Date: Thu Oct 8 11:28:00 2026 +0200 Mod GastinelMindPNJ : Mind en PNJ, /msg mind en chuchotement, entrée TAB Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cb3b3a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +build/ +build-out/ +.gradle/ +run/ +*.jar +!gradle/wrapper/gradle-wrapper.jar diff --git a/build-sur-cornafserver.sh b/build-sur-cornafserver.sh new file mode 100644 index 0000000..7a423b8 --- /dev/null +++ b/build-sur-cornafserver.sh @@ -0,0 +1,14 @@ +#!/bin/sh +# Compile GastinelMindPNJ dans un conteneur JDK 21 jetable (rien n'est installé sur l'hôte). +# Usage (sur cornafserver) : sh build-sur-cornafserver.sh -> build/libs/*.jar +set -e +cd "$(dirname "$0")" +mkdir -p "$HOME/.cache/gastinelmind-gradle" +docker run --rm \ + -u "$(id -u):$(id -g)" \ + -e GRADLE_USER_HOME=/gradle-home \ + -v "$HOME/.cache/gastinelmind-gradle:/gradle-home" \ + -v "$(pwd):/src" -w /src \ + eclipse-temurin:21-jdk \ + sh ./gradlew --no-daemon clean test build +ls -l build/libs diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..eebf26f --- /dev/null +++ b/build.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'net.neoforged.moddev' version '2.0.142' +} + +version = project.mod_version +group = project.mod_group_id +base { archivesName = "${project.mod_id}-neoforge-1.21.1" } + +java { toolchain { languageVersion = JavaLanguageVersion.of(21) } } + +repositories { + mavenCentral() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } +} + +neoForge { + version = project.neoforge_version + runs { + server { + server() + } + } + mods { + "${project.mod_id}" { + sourceSet sourceSets.main + } + } +} + +dependencies { + // Tests de la logique pure (package core, sans Minecraft) + testImplementation platform('org.junit:junit-bom:5.11.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +test { + useJUnitPlatform() + testLogging { events 'passed', 'failed'; exceptionFormat 'full' } +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release = 21 +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..7d20005 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +org.gradle.jvmargs=-Xmx2G +org.gradle.parallel=true + +mod_version=1.0.0 +mod_group_id=com.gastinelmind +mod_id=gastinelmind + +minecraft_version=1.21.1 +neoforge_version=21.1.234 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..5dd3c01 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b9bb139 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..24c62d5 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..a28ad05 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + maven { name = 'NeoForged'; url = 'https://maven.neoforged.net/releases' } + } +} +rootProject.name = 'gastinelmind-neoforge-1.21.1' diff --git a/src/main/java/com/gastinelmind/GastinelMind.java b/src/main/java/com/gastinelmind/GastinelMind.java new file mode 100644 index 0000000..24d7e36 --- /dev/null +++ b/src/main/java/com/gastinelmind/GastinelMind.java @@ -0,0 +1,22 @@ +package com.gastinelmind; + +import net.neoforged.bus.api.IEventBus; +import net.neoforged.fml.ModContainer; +import net.neoforged.fml.common.Mod; +import net.neoforged.neoforge.common.NeoForge; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Mod(GastinelMind.MOD_ID) +public class GastinelMind { + + public static final String MOD_ID = "gastinelmind"; + public static final Logger LOGGER = LoggerFactory.getLogger(GastinelMind.class); + + public GastinelMind(IEventBus modEventBus, ModContainer modContainer) { + NeoForge.EVENT_BUS.register(MindChat.class); + NeoForge.EVENT_BUS.register(MindNpc.class); + NeoForge.EVENT_BUS.register(MindTabList.class); + LOGGER.info("[GastinelMind] Mind PNJ chargé."); + } +} diff --git a/src/main/java/com/gastinelmind/MindChat.java b/src/main/java/com/gastinelmind/MindChat.java new file mode 100644 index 0000000..11741b0 --- /dev/null +++ b/src/main/java/com/gastinelmind/MindChat.java @@ -0,0 +1,33 @@ +package com.gastinelmind; + +import com.gastinelmind.core.MindRequest; +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.neoforged.bus.api.EventPriority; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.CommandEvent; + +import java.util.Optional; + +/** + * Intercepte /msg, /tell, /w mind : la commande vanilla est annulée, le joueur voit son + * chuchotement, et une ligne marquée part dans le journal serveur pour le pont Python. + */ +public final class MindChat { + + @SubscribeEvent(priority = EventPriority.HIGHEST) + public static void onCommand(CommandEvent event) { + ServerPlayer player = event.getParseResults().getContext().getSource().getPlayer(); + if (player == null) return; // console, blocs de commande : comportement vanilla + + Optional text = MindRequest.parse(event.getParseResults().getReader().getString()); + if (text.isEmpty()) return; + + event.setCanceled(true); + player.sendSystemMessage(Component.literal("Vous chuchotez à Mind : " + text.get()) + .withStyle(ChatFormatting.GRAY, ChatFormatting.ITALIC)); + String name = MindRequest.clean(player.getGameProfile().getName()); + GastinelMind.LOGGER.info("[GastinelMind] DEMANDE {} {} :: {}", name, player.getUUID(), text.get()); + } +} diff --git a/src/main/java/com/gastinelmind/MindData.java b/src/main/java/com/gastinelmind/MindData.java new file mode 100644 index 0000000..a691b9a --- /dev/null +++ b/src/main/java/com/gastinelmind/MindData.java @@ -0,0 +1,44 @@ +package com.gastinelmind; + +import net.minecraft.core.HolderLookup; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.server.MinecraftServer; +import net.minecraft.world.level.saveddata.SavedData; + +import java.util.UUID; + +/** Retient l'UUID du PNJ Mind actuel (data/gastinelmind.dat) : tout autre PNJ marqué est retiré. */ +public final class MindData extends SavedData { + + private static final String NAME = "gastinelmind"; + + public static final SavedData.Factory FACTORY = + new SavedData.Factory<>(MindData::new, MindData::load, null); + + private UUID current; + + public static MindData get(MinecraftServer server) { + return server.overworld().getDataStorage().computeIfAbsent(FACTORY, NAME); + } + + public UUID current() { + return current; + } + + public void setCurrent(UUID uuid) { + current = uuid; + setDirty(); + } + + static MindData load(CompoundTag tag, HolderLookup.Provider provider) { + MindData data = new MindData(); + if (tag.hasUUID("current")) data.current = tag.getUUID("current"); + return data; + } + + @Override + public CompoundTag save(CompoundTag tag, HolderLookup.Provider provider) { + if (current != null) tag.putUUID("current", current); + return tag; + } +} diff --git a/src/main/java/com/gastinelmind/MindNpc.java b/src/main/java/com/gastinelmind/MindNpc.java new file mode 100644 index 0000000..559a365 --- /dev/null +++ b/src/main/java/com/gastinelmind/MindNpc.java @@ -0,0 +1,158 @@ +package com.gastinelmind; + +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.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.DamageTypeTags; +import net.minecraft.util.Mth; +import net.minecraft.world.entity.Entity; +import net.minecraft.world.entity.EntityType; +import net.minecraft.world.entity.monster.Evoker; +import net.minecraft.world.entity.player.Player; +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.LivingIncomingDamageEvent; +import net.neoforged.neoforge.event.entity.living.MobDespawnEvent; +import net.neoforged.neoforge.event.tick.EntityTickEvent; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** PNJ décoratif : un évocateur « Mind » immobile, invulnérable, qui regarde le joueur le plus proche. */ +public final class MindNpc { + + public static final String TAG = "gastinel_mind"; + private static final String ANCHOR = "gastinel_mind_ancre"; + private static final double LOOK_RANGE = 10.0; + + // --- Commandes --- + + @SubscribeEvent + public static void onRegister(RegisterCommandsEvent event) { + event.getDispatcher().register(Commands.literal("mind") + .requires(s -> s.hasPermission(2)) + .then(Commands.literal("spawn").executes(MindNpc::spawn)) + .then(Commands.literal("remove").executes(MindNpc::remove))); + } + + private static int spawn(CommandContext ctx) throws CommandSyntaxException { + ServerPlayer p = ctx.getSource().getPlayerOrException(); + ServerLevel level = p.serverLevel(); + int removed = removeAll(p.server); + + Evoker mind = EntityType.EVOKER.create(level); + if (mind == null) { + ctx.getSource().sendFailure(Component.literal("Impossible de créer le PNJ.")); + return 0; + } + mind.moveTo(p.getX(), p.getY(), p.getZ(), p.getYRot(), 0.0F); + mind.setYHeadRot(p.getYRot()); + mind.setYBodyRot(p.getYRot()); + mind.setCustomName(Component.literal("Mind")); + mind.setCustomNameVisible(true); + mind.setNoAi(true); // pas d'IA : ni déplacement ni sorts + mind.setInvulnerable(true); + mind.setSilent(true); + mind.setPersistenceRequired(); + mind.addTag(TAG); + CompoundTag anchor = new CompoundTag(); + anchor.putDouble("x", p.getX()); + anchor.putDouble("y", p.getY()); + anchor.putDouble("z", p.getZ()); + mind.getPersistentData().put(ANCHOR, anchor); + level.addFreshEntity(mind); + MindData.get(p.server).setCurrent(mind.getUUID()); + + String msg = removed > 0 ? "PNJ Mind déplacé ici." : "PNJ Mind créé ici."; + ctx.getSource().sendSuccess(() -> Component.literal(msg), true); + return 1; + } + + private static int remove(CommandContext ctx) { + MinecraftServer server = ctx.getSource().getServer(); + int removed = removeAll(server); + // Un ancien PNJ dans un chunk non chargé sera retiré à son chargement (voir onTick). + MindData.get(server).setCurrent(null); + ctx.getSource().sendSuccess(() -> Component.literal( + removed > 0 ? "PNJ Mind retiré." : "Aucun PNJ Mind chargé."), true); + return 1; + } + + /** Retire tous les PNJ Mind chargés, toutes dimensions. */ + private static int removeAll(MinecraftServer server) { + List found = new ArrayList<>(); + for (ServerLevel level : server.getAllLevels()) { + for (Entity e : level.getAllEntities()) { + if (isMind(e)) found.add(e); + } + } + found.forEach(Entity::discard); + return found.size(); + } + + private static boolean isMind(Entity e) { + return e instanceof Evoker && e.getTags().contains(TAG); + } + + // --- Comportement --- + + @SubscribeEvent + public static void onTick(EntityTickEvent.Pre event) { + Entity e = event.getEntity(); + if (!(e instanceof Evoker mind) || mind.level().isClientSide() || !isMind(mind)) return; + if (mind.tickCount % 5 != 0) return; + + MinecraftServer server = mind.getServer(); + if (server == null) return; + UUID current = MindData.get(server).current(); + if (!mind.getUUID().equals(current)) { // doublon ou PNJ retiré : un seul Mind à la fois + mind.discard(); + return; + } + + // Reste à sa place (ne peut pas être poussé) + CompoundTag anchor = mind.getPersistentData().getCompound(ANCHOR); + if (anchor.contains("x")) { + Vec3 home = new Vec3(anchor.getDouble("x"), anchor.getDouble("y"), anchor.getDouble("z")); + if (mind.position().distanceToSqr(home) > 0.01) { + mind.teleportTo(home.x, home.y, home.z); + } + mind.setDeltaMovement(Vec3.ZERO); + } + + // Tourne la tête vers le joueur le plus proche + Player target = mind.level().getNearestPlayer(mind, LOOK_RANGE); + if (target == null) return; + double dx = target.getX() - mind.getX(); + double dz = target.getZ() - mind.getZ(); + double dy = target.getEyeY() - mind.getEyeY(); + float yaw = (float) (Mth.atan2(dz, dx) * Mth.RAD_TO_DEG) - 90.0F; + float pitch = (float) -(Mth.atan2(dy, Math.sqrt(dx * dx + dz * dz)) * Mth.RAD_TO_DEG); + mind.setYRot(yaw); + mind.setYHeadRot(yaw); + mind.setYBodyRot(yaw); + mind.setXRot(pitch); + } + + /** Le serveur est en paisible : sans ça, l'évocateur (monstre) serait retiré aussitôt. */ + @SubscribeEvent + public static void onDespawn(MobDespawnEvent event) { + if (isMind(event.getEntity())) event.setResult(MobDespawnEvent.Result.DENY); + } + + /** Invulnérable même face aux joueurs en créatif ; seul /kill (dégâts qui ignorent l'invulnérabilité) passe. */ + @SubscribeEvent + public static void onDamage(LivingIncomingDamageEvent event) { + if (isMind(event.getEntity()) && !event.getSource().is(DamageTypeTags.BYPASSES_INVULNERABILITY)) { + event.setCanceled(true); + } + } +} diff --git a/src/main/java/com/gastinelmind/MindTabList.java b/src/main/java/com/gastinelmind/MindTabList.java new file mode 100644 index 0000000..6fe5c20 --- /dev/null +++ b/src/main/java/com/gastinelmind/MindTabList.java @@ -0,0 +1,75 @@ +package com.gastinelmind; + +import com.gastinelmind.core.MindProfile; +import com.mojang.authlib.properties.PropertyMap; +import io.netty.buffer.Unpooled; +import net.minecraft.core.RegistryAccess; +import net.minecraft.network.RegistryFriendlyByteBuf; +import net.minecraft.network.codec.ByteBufCodecs; +import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket; +import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket.Action; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.GameType; +import net.neoforged.bus.api.SubscribeEvent; +import net.neoforged.neoforge.event.OnDatapackSyncEvent; +import net.neoforged.neoforge.event.entity.player.PlayerEvent; +import net.neoforged.neoforge.event.server.ServerStartedEvent; + +import java.util.EnumSet; + +/** + * Fausse entrée « Mind » dans la liste TAB de chaque client (aucun vrai joueur côté serveur) : + * le client la propose donc dans l'autocomplétion de /msg. Skin par défaut. + */ +public final class MindTabList { + + private static final EnumSet ACTIONS = + EnumSet.of(Action.ADD_PLAYER, Action.UPDATE_GAME_MODE, Action.UPDATE_LISTED, Action.UPDATE_LATENCY); + + @SubscribeEvent + public static void onLogin(PlayerEvent.PlayerLoggedInEvent event) { + if (event.getEntity() instanceof ServerPlayer p) send(p); + } + + /** /reload : renvoyer l'entrée à tous les joueurs connectés. */ + @SubscribeEvent + public static void onReload(OnDatapackSyncEvent event) { + if (event.getPlayer() == null) event.getPlayerList().getPlayers().forEach(MindTabList::send); + } + + /** Vérification au démarrage : le paquet se construit bien (une erreur ici ne bloque pas le serveur). */ + @SubscribeEvent + public static void onStarted(ServerStartedEvent event) { + try { + var e = packet(event.getServer().registryAccess()).entries().get(0); + GastinelMind.LOGGER.info("[GastinelMind] Entrée TAB prête : {} {} listée={}", e.profile().getName(), e.profileId(), e.listed()); + } catch (Exception ex) { + GastinelMind.LOGGER.error("[GastinelMind] Entrée TAB impossible à construire", ex); + } + } + + private static void send(ServerPlayer p) { + p.connection.send(packet(p.server.registryAccess())); + } + + /** + * Le paquet n'a de constructeur public que pour un vrai ServerPlayer : on écrit les octets + * au format du protocole (même ordre que ClientboundPlayerInfoUpdatePacket.write) puis on le relit. + */ + static ClientboundPlayerInfoUpdatePacket packet(RegistryAccess access) { + RegistryFriendlyByteBuf buf = new RegistryFriendlyByteBuf(Unpooled.buffer(), access); + try { + buf.writeEnumSet(ACTIONS, Action.class); + buf.writeVarInt(1); // une entrée + buf.writeUUID(MindProfile.ID); + buf.writeUtf(MindProfile.NAME, 16); // ADD_PLAYER : nom + propriétés (aucune = skin par défaut) + ByteBufCodecs.GAME_PROFILE_PROPERTIES.encode(buf, new PropertyMap()); + buf.writeVarInt(GameType.SURVIVAL.getId()); // UPDATE_GAME_MODE + buf.writeBoolean(true); // UPDATE_LISTED + buf.writeVarInt(0); // UPDATE_LATENCY + return ClientboundPlayerInfoUpdatePacket.STREAM_CODEC.decode(buf); + } finally { + buf.release(); + } + } +} diff --git a/src/main/java/com/gastinelmind/core/MindProfile.java b/src/main/java/com/gastinelmind/core/MindProfile.java new file mode 100644 index 0000000..764a06b --- /dev/null +++ b/src/main/java/com/gastinelmind/core/MindProfile.java @@ -0,0 +1,13 @@ +package com.gastinelmind.core; + +import java.nio.charset.StandardCharsets; +import java.util.UUID; + +/** Identité fixe de la fausse entrée « Mind » dans la liste des joueurs (TAB). */ +public final class MindProfile { + + public static final String NAME = "Mind"; + public static final UUID ID = UUID.nameUUIDFromBytes("gastinel:mind".getBytes(StandardCharsets.UTF_8)); + + private MindProfile() { } +} diff --git a/src/main/java/com/gastinelmind/core/MindRequest.java b/src/main/java/com/gastinelmind/core/MindRequest.java new file mode 100644 index 0000000..5715714 --- /dev/null +++ b/src/main/java/com/gastinelmind/core/MindRequest.java @@ -0,0 +1,40 @@ +package com.gastinelmind.core; + +import java.util.Locale; +import java.util.Optional; + +/** Logique pure : reconnaît « /msg|/tell|/w mind » et nettoie le texte. */ +public final class MindRequest { + + public static final String TARGET = "mind"; + + private MindRequest() { } + + /** + * Renvoie le texte nettoyé si la commande est un message privé à Mind, sinon vide. + * Accepte avec ou sans « / » et le préfixe « minecraft: ». + */ + public static Optional parse(String input) { + if (input == null) return Optional.empty(); + String s = input.strip(); + if (s.startsWith("/")) s = s.substring(1); + String[] parts = s.split("\\s+", 3); + if (parts.length < 3) return Optional.empty(); + + String cmd = parts[0].toLowerCase(Locale.ROOT); + if (cmd.startsWith("minecraft:")) cmd = cmd.substring("minecraft:".length()); + if (!cmd.equals("msg") && !cmd.equals("tell") && !cmd.equals("w")) return Optional.empty(); + if (!parts[1].equalsIgnoreCase(TARGET)) return Optional.empty(); + + String text = clean(parts[2]); + return text.isEmpty() ? Optional.empty() : Optional.of(text); + } + + /** Une seule ligne : retours à la ligne et caractères de contrôle -> espace, codes § retirés, espaces réduits. */ + public static String clean(String text) { + if (text == null) return ""; + String t = text.replaceAll("§.?", ""); + t = t.replaceAll("[\\p{Cntrl}\\u0085\\u2028\\u2029]", " "); + return t.replaceAll("\\s+", " ").strip(); + } +} diff --git a/src/main/resources/META-INF/neoforge.mods.toml b/src/main/resources/META-INF/neoforge.mods.toml new file mode 100644 index 0000000..77f4d62 --- /dev/null +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -0,0 +1,26 @@ +modLoader="javafml" +loaderVersion="[1,)" +license="MIT" + +[[mods]] +modId="gastinelmind" +version="1.0.0" +displayName="GastinelMind PNJ" +authors="Théo Gastinel" +description='''Mind devient un PNJ : /msg mind est transmis à l'IA locale, /mind spawn|remove pour le PNJ évocateur. Mod côté serveur uniquement.''' +# Les clients n'ont pas besoin du mod. +displayTest="IGNORE_ALL_VERSION" + +[[dependencies.gastinelmind]] + modId="neoforge" + type="required" + versionRange="[21.1,)" + ordering="NONE" + side="SERVER" + +[[dependencies.gastinelmind]] + modId="minecraft" + type="required" + versionRange="[1.21.1,1.21.2)" + ordering="NONE" + side="SERVER" diff --git a/src/test/java/com/gastinelmind/core/MindProfileTest.java b/src/test/java/com/gastinelmind/core/MindProfileTest.java new file mode 100644 index 0000000..63b9918 --- /dev/null +++ b/src/test/java/com/gastinelmind/core/MindProfileTest.java @@ -0,0 +1,18 @@ +package com.gastinelmind.core; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class MindProfileTest { + + @Test + void uuidStableEtNomValide() { + // Même UUID à chaque démarrage : pas de doublon côté client + assertEquals(MindProfile.ID, java.util.UUID.nameUUIDFromBytes("gastinel:mind".getBytes())); + assertEquals(3, MindProfile.ID.version()); + assertTrue(MindProfile.NAME.length() <= 16); + // Le nom suggéré par l'autocomplétion est bien reconnu par l'interception + assertEquals(java.util.Optional.of("salut"), MindRequest.parse("msg " + MindProfile.NAME + " salut")); + } +} diff --git a/src/test/java/com/gastinelmind/core/MindRequestTest.java b/src/test/java/com/gastinelmind/core/MindRequestTest.java new file mode 100644 index 0000000..555c6a0 --- /dev/null +++ b/src/test/java/com/gastinelmind/core/MindRequestTest.java @@ -0,0 +1,49 @@ +package com.gastinelmind.core; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +class MindRequestTest { + + @Test + void reconnaitLesTroisCommandes() { + assertEquals(Optional.of("salut"), MindRequest.parse("msg mind salut")); + assertEquals(Optional.of("salut"), MindRequest.parse("tell mind salut")); + assertEquals(Optional.of("salut"), MindRequest.parse("w mind salut")); + } + + @Test + void slashPrefixeEtCasse() { + assertEquals(Optional.of("comment faire du pain ?"), MindRequest.parse("/MSG MiNd comment faire du pain ?")); + assertEquals(Optional.of("ok"), MindRequest.parse("minecraft:tell MIND ok")); + assertEquals(Optional.of("ok"), MindRequest.parse(" /w mind ok ")); + } + + @Test + void ignoreLesAutresCas() { + assertTrue(MindRequest.parse("msg Steve salut").isEmpty()); + assertTrue(MindRequest.parse("msg mindy salut").isEmpty()); + assertTrue(MindRequest.parse("msg mind").isEmpty()); + assertTrue(MindRequest.parse("msg mind ").isEmpty()); + assertTrue(MindRequest.parse("say mind salut").isEmpty()); + assertTrue(MindRequest.parse("message mind salut").isEmpty()); + assertTrue(MindRequest.parse("").isEmpty()); + assertTrue(MindRequest.parse(null).isEmpty()); + } + + @Test + void nettoyage() { + assertEquals("a b c", MindRequest.clean("a\nb\r\nc")); + assertEquals("rouge", MindRequest.clean("§crouge")); + assertEquals("x y", MindRequest.clean("x\t\u0000 y
")); + assertEquals("", MindRequest.clean(null)); + } + + @Test + void texteGardeSesCaracteres() { + assertEquals(Optional.of("l'\"épée\" :: {}"), MindRequest.parse("msg mind l'\"épée\" :: {}")); + } +}