diff --git a/build.gradle b/build.gradle index b3c381d..7dd0f60 100644 --- a/build.gradle +++ b/build.gradle @@ -4,29 +4,28 @@ import java.time.temporal.ChronoUnit buildscript { repositories { - maven { url = 'https://files.minecraftforge.net/maven' } + maven { url = 'https://maven.minecraftforge.net' } + maven { url = 'https://maven.parchmentmc.org' } mavenCentral() } dependencies { - classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '4.+', changing: true + classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true + classpath 'org.parchmentmc:librarian:1.+' } } apply plugin: 'net.minecraftforge.gradle' +apply plugin: 'org.parchmentmc.librarian.forgegradle' apply plugin: 'eclipse' apply plugin: 'maven-publish' version = '0.1.6' group = 'org.teacon' -archivesBaseName = 'SignMeUp-Forge-1.16' +archivesBaseName = 'SignMeUp-Forge-1.18' -sourceCompatibility = targetCompatibility = JavaVersion.VERSION_1_8 - -compileJava { - sourceCompatibility = targetCompatibility = JavaVersion.VERSION_1_8 -} +java.toolchain.languageVersion = JavaLanguageVersion.of(17) minecraft { - mappings channel: 'snapshot', version: '20210309-1.16.4' + mappings channel: 'parchment', version: '2022.01.23-1.18.1' accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') runs { @@ -70,7 +69,7 @@ minecraft { } dependencies { - minecraft 'net.minecraftforge:forge:1.16.4-35.1.0' + minecraft 'net.minecraftforge:forge:1.18.1-39.0.40' } jar { @@ -94,11 +93,11 @@ publishing { publications { release(MavenPublication) { groupId = "org.teacon" - artifactId = "SignMeUp-Forge-1.16" + artifactId = "SignMeUp-Forge-1.18" artifact jar pom { - name = 'SignMeUp for Minecraft 1.16' + name = 'SignMeUp for Minecraft 1.18' description = 'In-game sign-up, sign-in system and more' url = 'https://github.com/teaconmc/SignMeUp' licenses { diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 94336fc..7454180 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 7665b0f..e750102 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index cccdd3d..c53aefa 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,129 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 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. +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# 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/master/subprojects/plugins/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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # 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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || 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 @@ -89,84 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=$((i+1)) + # 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 - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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 index e95643d..ac1b06f 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@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 + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=. 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= +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%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,28 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell diff --git a/src/main/java/org/teacon/signin/SignMeUp.java b/src/main/java/org/teacon/signin/SignMeUp.java index 268f17b..47f5107 100644 --- a/src/main/java/org/teacon/signin/SignMeUp.java +++ b/src/main/java/org/teacon/signin/SignMeUp.java @@ -1,20 +1,18 @@ package org.teacon.signin; -import net.minecraft.command.CommandSource; -import net.minecraft.command.Commands; -import net.minecraft.command.ISuggestionProvider; -import net.minecraft.command.arguments.BlockPosArgument; -import net.minecraft.command.arguments.ResourceLocationArgument; -import net.minecraft.entity.player.ServerPlayerEntity; +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.Commands; +import net.minecraft.commands.arguments.ResourceLocationArgument; +import net.minecraft.commands.arguments.coordinates.BlockPosArgument; +import net.minecraft.core.Vec3i; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.StringTextComponent; -import net.minecraft.world.World; -import net.minecraftforge.api.distmarker.Dist; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; import net.minecraftforge.common.MinecraftForge; -import net.minecraftforge.common.capabilities.CapabilityManager; +import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent; import net.minecraftforge.event.AddReloadListenerEvent; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.event.RegisterCommandsEvent; @@ -23,8 +21,9 @@ import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.loading.FMLEnvironment; -import net.minecraftforge.fml.network.NetworkRegistry; -import net.minecraftforge.fml.network.simple.SimpleChannel; +import net.minecraftforge.network.NetworkRegistry; +import net.minecraftforge.network.simple.SimpleChannel; + import org.teacon.signin.client.SignMeUpClient; import org.teacon.signin.command.CommandImpl; import org.teacon.signin.data.DynamicLocationStorage; @@ -50,7 +49,7 @@ public SignMeUp() { } public static void setup(FMLCommonSetupEvent event) { - CapabilityManager.INSTANCE.register(DynamicLocationStorage.class, new DynamicLocationStorage.Serializer(), DynamicLocationStorage::new); + //CapabilityManager.INSTANCE.register(DynamicLocationStorage.class, new DynamicLocationStorage.Serializer(), DynamicLocationStorage::new); channel.registerMessage(0, SyncGuideMapPacket.class, SyncGuideMapPacket::write, SyncGuideMapPacket::new, SyncGuideMapPacket::handle); channel.registerMessage(1, PartialUpdatePacket.class, PartialUpdatePacket::write, PartialUpdatePacket::new, PartialUpdatePacket::handle); channel.registerMessage(2, MapScreenPacket.class, MapScreenPacket::write, MapScreenPacket::new, MapScreenPacket::handle); @@ -58,6 +57,11 @@ public static void setup(FMLCommonSetupEvent event) { channel.registerMessage(4, TriggerFromWaypointPacket.class, TriggerFromWaypointPacket::write, TriggerFromWaypointPacket::new, TriggerFromWaypointPacket::handle); } + @SubscribeEvent + public void registerCaps(RegisterCapabilitiesEvent event) { + event.register(DynamicLocationStorage.class); + } + @SubscribeEvent public static void dataLoading(AddReloadListenerEvent event) { event.addListener(MANAGER); @@ -69,11 +73,11 @@ public static void command(RegisterCommandsEvent event) { .then(Commands.literal("map") .then(Commands.literal("list").executes(CommandImpl::listMaps)) .then(Commands.literal("close") - .then(Commands.argument("id", ResourceLocationArgument.resourceLocation()) + .then(Commands.argument("id", ResourceLocationArgument.id()) .executes(CommandImpl::closeSpecificMap)) .executes(CommandImpl::closeAnyMap)) .then(Commands.literal("open") - .then(Commands.argument("id", ResourceLocationArgument.resourceLocation()) + .then(Commands.argument("id", ResourceLocationArgument.id()) .executes(CommandImpl::openSpecificMap)) .executes(CommandImpl::openNearestMap))) .then(Commands.literal("point") @@ -82,44 +86,48 @@ public static void command(RegisterCommandsEvent event) { .executes(CommandImpl::listWaypointPos)) .executes(CommandImpl::listWaypoints)) .then(Commands.literal("get") - .then(Commands.argument("id", ResourceLocationArgument.resourceLocation()) + .then(Commands.argument("id", ResourceLocationArgument.id()) .then(Commands.literal("location") .executes(CommandImpl::getWaypointPos)))) .then(Commands.literal("set") - .then(Commands.argument("id", ResourceLocationArgument.resourceLocation()) + .then(Commands.argument("id", ResourceLocationArgument.id()) .then(Commands.literal("actual") .then(Commands.argument("pos", BlockPosArgument.blockPos()).executes(CommandImpl::setWaypointActualPos))) .then(Commands.literal("render") .then(Commands.argument("pos", BlockPosArgument.blockPos()).executes(CommandImpl::setWaypointRenderPos)))))) .then(Commands.literal("trigger") - .then(Commands.argument("id", ResourceLocationArgument.resourceLocation()) - .suggests((src, builder) -> ISuggestionProvider.suggest(FMLEnvironment.dist.isClient() - ? SignMeUpClient.MANAGER.getAllTriggers().stream().map(ResourceLocation::toString) - : SignMeUp.MANAGER.getAllTriggers().stream().map(ResourceLocation::toString), builder)) - .executes(CommandImpl::trigger)))); + .then(Commands.argument("id", ResourceLocationArgument.id()) + .suggests((src, builder) -> { + if(FMLEnvironment.dist.isClient()) { + SignMeUpClient.MANAGER.getAllTriggers().stream().forEach(location -> builder.suggest(location.toString())); + } else { + SignMeUp.MANAGER.getAllTriggers().stream().forEach(location -> builder.suggest(location.toString())); + } + return builder.buildFuture(); + }).executes(CommandImpl::trigger)))); } @SubscribeEvent - public static void attachCap(AttachCapabilitiesEvent event) { + public static void attachCap(AttachCapabilitiesEvent event) { event.addCapability(new ResourceLocation("sign_up"), new DynamicLocationStorage.Holder()); } - public static boolean trigger(ServerPlayerEntity player, Vector3i pos, ResourceLocation triggerId, boolean isCommand) { + public static boolean trigger(ServerPlayer player, Vec3i pos, ResourceLocation triggerId, boolean isCommand) { final Trigger trigger = MANAGER.findTrigger(triggerId); if (trigger != null && trigger.isVisibleTo(player)) { final MinecraftServer server = player.getServer(); if (server != null) { - final Vector3d pos3d = Vector3d.copy(pos); - final CommandSource source = isCommand - ? player.getCommandSource().withPos(pos3d).withPermissionLevel(2) - : player.getCommandSource().withPos(pos3d).withFeedbackDisabled().withMinPermissionLevel(2); + final Vec3 pos3d = Vec3.atLowerCornerOf(pos); + final CommandSourceStack source = isCommand + ? player.createCommandSourceStack().withPosition(pos3d).withPermission(2) + : player.createCommandSourceStack().withPosition(pos3d).withSuppressedOutput().withMaximumPermission(2); for (String command : trigger.executes) { - server.getCommandManager().handleCommand(source, command); + server.getCommands().performCommand(source, command); } } return true; } else { - player.sendStatusMessage(new StringTextComponent("You seemed to click the void just now..."), true); + player.displayClientMessage(new TextComponent("You seemed to click the void just now..."), true); return false; } } diff --git a/src/main/java/org/teacon/signin/client/ClientGuideMapManager.java b/src/main/java/org/teacon/signin/client/ClientGuideMapManager.java index 5726e22..9974f08 100644 --- a/src/main/java/org/teacon/signin/client/ClientGuideMapManager.java +++ b/src/main/java/org/teacon/signin/client/ClientGuideMapManager.java @@ -1,10 +1,9 @@ package org.teacon.signin.client; import net.minecraft.client.Minecraft; -import net.minecraft.client.entity.player.ClientPlayerEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.math.vector.Vector3i; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; + import org.teacon.signin.data.GuideMap; import org.teacon.signin.data.Trigger; import org.teacon.signin.data.Waypoint; @@ -18,17 +17,17 @@ public final class ClientGuideMapManager { private final Map availableWaypoints = new HashMap<>(); private final Map availableTriggers = new HashMap<>(); - public void openMapByPacket(MapScreenPacket.Action action, ResourceLocation mapId, Vector3d position) { + public void openMapByPacket(MapScreenPacket.Action action, ResourceLocation mapId, Vec3 position) { Minecraft mc = Minecraft.getInstance(); - mc.runAsync(() -> { + mc.submitAsync(() -> { if (action == MapScreenPacket.Action.OPEN_SPECIFIC) { Objects.requireNonNull(mapId); GuideMap map = SignMeUpClient.MANAGER.findMap(mapId); - mc.displayGuiScreen(new GuideMapScreen(mapId, map, position)); - } else if (mc.currentScreen instanceof GuideMapScreen) { - final GuideMapScreen screen = (GuideMapScreen) mc.currentScreen; + mc.setScreen(new GuideMapScreen(mapId, map, position)); + } else if (mc.screen instanceof GuideMapScreen) { + final GuideMapScreen screen = (GuideMapScreen) mc.screen; if (action != MapScreenPacket.Action.CLOSE_SPECIFIC || screen.mapId.equals(mapId)) { - mc.displayGuiScreen(null); + mc.setScreen(null); } } }); @@ -38,15 +37,15 @@ public synchronized void acceptUpdateFromServer(SortedMap nearestTo(Vector3d pos) { + public Map.Entry nearestTo(Vec3 pos) { double minDistanceSq = Double.MAX_VALUE; Map.Entry result = null; for (Map.Entry entry : this.availableMaps.entrySet()) { // Skip the dimension check because the client manager only knows // guide maps that are for the current dimension. final GuideMap guideMap = entry.getValue(); - final double dx = pos.getX() - guideMap.center.getX(); - final double dz = pos.getZ() - guideMap.center.getZ(); + final double dx = pos.x() - guideMap.center.getX(); + final double dz = pos.z() - guideMap.center.getZ(); if (Math.min(Math.abs(dx), Math.abs(dz)) <= guideMap.radius) { final double distanceSq = dx * dx + dz * dz; if (distanceSq < minDistanceSq) { diff --git a/src/main/java/org/teacon/signin/client/GuideMapScreen.java b/src/main/java/org/teacon/signin/client/GuideMapScreen.java index e1f8e68..692e190 100644 --- a/src/main/java/org/teacon/signin/client/GuideMapScreen.java +++ b/src/main/java/org/teacon/signin/client/GuideMapScreen.java @@ -4,20 +4,20 @@ import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Queues; -import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; -import mcp.MethodsReturnNonnullByDefault; +import com.mojang.blaze3d.vertex.*; +import net.minecraft.MethodsReturnNonnullByDefault; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.FontRenderer; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.client.gui.widget.button.Button; -import net.minecraft.client.gui.widget.button.ImageButton; -import net.minecraft.util.IReorderingProcessor; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.client.gui.components.Button; +import net.minecraft.client.gui.components.ImageButton; +import net.minecraft.client.gui.screens.Screen; +import net.minecraft.core.Vec3i; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.util.FormattedCharSequence; +import net.minecraft.world.phys.Vec3; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -34,7 +34,8 @@ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault -public final class GuideMapScreen extends Screen { +public final class GuideMapScreen extends Screen +{ private static final Logger LOGGER = LogManager.getLogger("SignMeUp"); private static final Marker MARKER = MarkerManager.getMarker("GuideMapScreen"); @@ -58,7 +59,7 @@ public final class GuideMapScreen extends Screen { private boolean hasWaypointTrigger = false; private final GuideMap map; - private final Vector3d playerLocation; + private final Vec3 playerLocation; private final List waypointIds; private PolynomialMapping mapping; @@ -71,7 +72,7 @@ public final class GuideMapScreen extends Screen { private boolean needRefresh = false; - public GuideMapScreen(ResourceLocation mapId, GuideMap map, Vector3d location) { + public GuideMapScreen(ResourceLocation mapId, GuideMap map, Vec3 location) { super(map.getTitle()); this.map = map; this.mapId = mapId; @@ -90,12 +91,12 @@ protected void init() { int x0 = (this.width - X_SIZE) / 2, y0 = (this.height - Y_SIZE) / 2, x1 = x0 + 206; // Left and Right Image Flip Button - this.leftFlip = this.addButton(new ImageButton(x1 + 7, y0 + 20, 10, 54, 155, 163, 0, GUIDE_MAP_RIGHT, new FlipHandler(1))); - this.rightFlip = this.addButton(new ImageButton(x1 + 93, y0 + 20, 10, 54, 167, 163, 0, GUIDE_MAP_RIGHT, new FlipHandler(-1))); + this.leftFlip = this.addRenderableWidget(new ImageButton(x1 + 7, y0 + 20, 10, 54, 155, 163, 0, GUIDE_MAP_RIGHT, new FlipHandler(1))); + this.rightFlip = this.addRenderableWidget(new ImageButton(x1 + 93, y0 + 20, 10, 54, 167, 163, 0, GUIDE_MAP_RIGHT, new FlipHandler(-1))); // Prev and next page for map triggers - this.mapTriggerPrev = this.addButton(new ImageButton(x0 + 6, y0 + 138, 33, 17, 66, 163, 19, GUIDE_MAP_LEFT, (btn) -> --this.mapTriggerPage)); - this.mapTriggerNext = this.addButton(new ImageButton(x0 + 39, y0 + 138, 33, 17, 99, 163, 19, GUIDE_MAP_LEFT, (btn) -> ++this.mapTriggerPage)); + this.mapTriggerPrev = this.addRenderableWidget(new ImageButton(x0 + 6, y0 + 138, 33, 17, 66, 163, 19, GUIDE_MAP_LEFT, (btn) -> --this.mapTriggerPage)); + this.mapTriggerNext = this.addRenderableWidget(new ImageButton(x0 + 39, y0 + 138, 33, 17, 99, 163, 19, GUIDE_MAP_LEFT, (btn) -> ++this.mapTriggerPage)); // Setup trigger buttons from GuideMap this.mapTriggers.clear(); @@ -107,7 +108,7 @@ protected void init() { continue; } this.mapTriggerPageSize = Math.max(this.mapTriggerPageSize, 1 + j / 6); - final TriggerButton btn = this.addButton(new TriggerButton(x0 + 8, y0 + 21 + (j % 6) * 19, 62, 18, + final TriggerButton btn = this.addRenderableWidget(new TriggerButton(x0 + 8, y0 + 21 + (j % 6) * 19, 62, 18, 2, trigger.disabled ? 203 : 163, trigger.disabled ? 0 : 20, GUIDE_MAP_LEFT, trigger, (b) -> SignMeUp.channel.sendToServer(new TriggerFromMapPacket(this.mapId, triggerId)))); this.mapTriggers.add(btn); @@ -132,11 +133,11 @@ protected void init() { final int waypointSize = waypoints.size(); final double[] inputX = new double[waypointSize], inputY = new double[waypointSize]; final double[] outputX = new double[waypointSize], outputY = new double[waypointSize]; - final Vector3i center = this.map.center; + final Vec3i center = this.map.center; for (int i = 0; i < waypointSize; ++i) { final Waypoint wp = waypoints.get(i); - final Vector3i actualLocation = wp.getActualLocation(); - final Vector3i renderLocation = wp.getRenderLocation(); + final Vec3i actualLocation = wp.getActualLocation(); + final Vec3i renderLocation = wp.getRenderLocation(); inputX[i] = actualLocation.getX() - center.getX(); inputY[i] = actualLocation.getZ() - center.getZ(); outputX[i] = renderLocation.getX() - center.getX(); @@ -158,13 +159,13 @@ protected void init() { final int wpY = Math.round((float) outputY[i] / this.map.radius * 64) + 64; if (wpX >= 1 && wpX <= 127 && wpY >= 1 && wpY <= 127) { // Setup Waypoints as ImageButtons - this.addButton(new ImageButton(mapCanvasX + wpX - 2, mapCanvasY + wpY - 2, 4, 4, 58, 2, 0, MAP_ICONS, + this.addRenderableWidget(new ImageButton(mapCanvasX + wpX - 2, mapCanvasY + wpY - 2, 4, 4, 58, 2, 0, MAP_ICONS, 128, 128, (btn) -> this.selectedWaypoint = wpId, (btn, transform, mouseX, mouseY) -> { - double distance = Math.sqrt(wp.getActualLocation().distanceSq(this.playerLocation, true)); - this.renderTooltip(transform, Arrays.asList( - wp.getTitle().func_241878_f(), - new TranslationTextComponent("sign_up.waypoint.distance", - Math.round(distance * 10.0) / 10.0).func_241878_f() + double distance = Math.sqrt(wp.getActualLocation().distSqr(this.playerLocation, true)); + this.renderComponentTooltip(transform, Arrays.asList( + wp.getTitle(), + new TranslatableComponent("sign_up.waypoint.distance", + Math.round(distance * 10.0) / 10.0) ), mouseX, mouseY); }, wp.getTitle())); // Setup trigger buttons from Waypoints @@ -175,7 +176,7 @@ protected void init() { if (trigger == null) { continue; } - TriggerButton btn = this.addButton(new TriggerButton(x1 + 109, y0 + 21 + j * 19, 62, 18, + TriggerButton btn = this.addRenderableWidget(new TriggerButton(x1 + 109, y0 + 21 + j * 19, 62, 18, 2, trigger.disabled ? 203 : 163, trigger.disabled ? 0 : 20, GUIDE_MAP_RIGHT, trigger, (b) -> SignMeUp.channel.sendToServer(new TriggerFromWaypointPacket(wpId, triggerId)))); this.waypointTriggers.put(wpId, btn); @@ -214,7 +215,7 @@ public void tick() { } @Override - public void render(MatrixStack transforms, int mouseX, int mouseY, float partialTicks) { + public void render(PoseStack transforms, int mouseX, int mouseY, float partialTicks) { final Minecraft mc = Objects.requireNonNull(this.minecraft); int x0 = (this.width - X_SIZE) / 2, y0 = (this.height - Y_SIZE) / 2, x1 = x0 + 206; @@ -226,12 +227,12 @@ public void render(MatrixStack transforms, int mouseX, int mouseY, float partial super.render(transforms, mouseX, mouseY, partialTicks); - this.renderTextCollection(this.font, transforms, x0, y0, x1); + this.renderTextCollection(transforms, x0, y0, x1); } - private void renderTextCollection(FontRenderer font, MatrixStack transforms, int x0, int y0, int x1) { + private void renderTextCollection(PoseStack transforms, int x0, int y0, int x1) { // Display the subtitle/desc of the map if no waypoint is selected - ITextComponent title = this.map.getTitle(), subtitle = this.map.getSubtitle(), desc = this.map.getDesc(); + Component title = this.map.getTitle(), subtitle = this.map.getSubtitle(), desc = this.map.getDesc(); if (this.selectedWaypoint != null) { Waypoint wp = SignMeUpClient.MANAGER.findWaypoint(this.selectedWaypoint); if (wp != null) { @@ -240,37 +241,37 @@ private void renderTextCollection(FontRenderer font, MatrixStack transforms, int } } // Draw title and subtitle depending on whether a waypoint is selected - final int xTitle = x0 + 142 - font.getStringPropertyWidth(title) / 2; - font.drawText(transforms, title, xTitle, y0 + 7F, 0x404040); - final int xSubtitle = x1 + 56 - font.getStringPropertyWidth(subtitle) / 2; - font.drawText(transforms, subtitle, xSubtitle, y0 + 7F, 0x404040); + final int xTitle = x0 + 142 - font.width(title) / 2; + font.draw(transforms, title, xTitle, y0 + 7F, 0x404040); + final int xSubtitle = x1 + 56 - font.width(subtitle) / 2; + font.draw(transforms, subtitle, xSubtitle, y0 + 7F, 0x404040); // I DISLIKE THIS METHOD BECAUSE IT FAILS TO HANDLE LINE BREAKING // A proper line breaking algorithm should comply with UAX #14, link below: // http://www.unicode.org/reports/tr14/ // However it at least get things work for now. So it is the status quo. - List displayedDescList = font.trimStringToWidth(desc, 90); + List displayedDescList = font.split(desc, 90); // Draw desc text for (int i = 0, size = Math.min(8, displayedDescList.size()); i < size; ++i) { - font.func_238422_b_(transforms, displayedDescList.get(i), x1 + 10F, y0 + 81F + 9 * i, 0x404040); + font.draw(transforms, displayedDescList.get(i), x1 + 10F, y0 + 81F + 9 * i, 0x404040); } } @SuppressWarnings("deprecation") - private void renderMapTexture(Minecraft mc, MatrixStack transforms, int x0, int y0, int x1) { + private void renderMapTexture(Minecraft mc, PoseStack transforms, int x0, int y0, int x1) { RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); - RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); // corner of the in-game window - mc.textureManager.bindTexture(this.map.texture); + RenderSystem.setShaderTexture(0, this.map.texture); // Who said we have to use 128 * 128 texture? blit(transforms, x0 + 78, y0 + 23, 0, 0, 128, 128, 128, 128); } @SuppressWarnings("deprecation") - private void renderWaypointTexture(Minecraft mc, MatrixStack transforms, int x0, int y0, int x1, float partialTicks) { + private void renderWaypointTexture(Minecraft mc, PoseStack transforms, int x0, int y0, int x1, float partialTicks) { RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); - RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); ResourceLocation image = this.map.getDisplayingImageId(); if (this.selectedWaypoint != null) { Waypoint wp = SignMeUpClient.MANAGER.findWaypoint(this.selectedWaypoint); @@ -295,25 +296,25 @@ private void renderWaypointTexture(Minecraft mc, MatrixStack transforms, int x0, if (this.lastWaypointTextures.isEmpty()) { this.ticksAfterWaypointTextureChanged = 0; } else { - mc.textureManager.bindTexture(head); + RenderSystem.setShaderTexture(0, head); blit(transforms, x1 + 7, y0 + 20, 0, 0, 96, 54, 96, 54); - RenderSystem.color4f(1.0F, 1.0F, 1.0F, alpha); - mc.textureManager.bindTexture(GUIDE_MAP_RIGHT); + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, alpha); + RenderSystem.setShaderTexture(0, GUIDE_MAP_RIGHT); blit(transforms, x1 + 7, y0 + 20, 7, 20, 96, 54); image = this.lastWaypointTextures.getFirst(); } this.lastWaypointTextures.addFirst(head); - mc.textureManager.bindTexture(image); + RenderSystem.setShaderTexture(0, image); blit(transforms, x1 + 7, y0 + 20, 0, 0, 96, 54, 96, 54); } @SuppressWarnings("deprecation") - private void renderBackgroundTexture(Minecraft mc, MatrixStack transforms, int x0, int y0, int x1) { - RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); - mc.textureManager.bindTexture(GUIDE_MAP_LEFT); + private void renderBackgroundTexture(Minecraft mc, PoseStack transforms, int x0, int y0, int x1) { + RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); + RenderSystem.setShaderTexture(0, GUIDE_MAP_LEFT); blit(transforms, x0, y0, 0, 0, 211, 161); blit(transforms, x0 + 6, y0 + 138, 66, 201, 66, 17); - mc.textureManager.bindTexture(GUIDE_MAP_RIGHT); + RenderSystem.setShaderTexture(0, GUIDE_MAP_RIGHT); blit(transforms, x1 + 5, y0, 5, 0, 174, 161); if (!this.hasWaypointTrigger) { blit(transforms, x1 + 108, y0 + 20, 181, 20, 64, 134); @@ -341,7 +342,8 @@ public boolean isPauseScreen() { return false; } - private final class FlipHandler implements Button.IPressable { + private final class FlipHandler implements Button.OnPress + { private final int diff; private FlipHandler(int diff) { @@ -365,19 +367,19 @@ private final class TriggerButton extends ImageButton { private final Trigger trigger; private TriggerButton(int x, int y, int width, int height, int uOffset, int vOffset, int vDiff, - ResourceLocation image, Trigger trigger, IPressable pressable) { + ResourceLocation image, Trigger trigger, OnPress pressable) { super(x, y, width, height, uOffset, vOffset, vDiff, image, pressable); this.trigger = trigger; } @Override - public void renderWidget(MatrixStack transforms, int mouseX, int mouseY, float partialTicks) { - super.renderWidget(transforms, mouseX, mouseY, partialTicks); - final FontRenderer font = Minecraft.getInstance().fontRenderer; - final int stringWidth = font.getStringPropertyWidth(this.trigger.getTitle()); + public void renderButton(PoseStack transforms, int mouseX, int mouseY, float partialTicks) { + super.renderButton(transforms, mouseX, mouseY, partialTicks); + //final Font font = Minecraft.getInstance().font; + final int stringWidth = font.width(this.trigger.getTitle()); final int x0 = this.x + this.width / 2 - stringWidth / 2, y0 = this.y + (this.height - 8) / 2; - font.drawText(transforms, this.trigger.getTitle(), x0, y0, this.trigger.disabled ? 0xFFFFFF : 0x404040); - if (this.isHovered()) { + font.draw(transforms, this.trigger.getTitle(), x0, y0, this.trigger.disabled ? 0xFFFFFF : 0x404040); + if (this.isHovered) { GuideMapScreen.this.renderTooltip(transforms, this.trigger.getDesc(), mouseX, mouseY); } } diff --git a/src/main/java/org/teacon/signin/client/Hotkey.java b/src/main/java/org/teacon/signin/client/Hotkey.java index 442e781..8aede6f 100644 --- a/src/main/java/org/teacon/signin/client/Hotkey.java +++ b/src/main/java/org/teacon/signin/client/Hotkey.java @@ -1,9 +1,9 @@ package org.teacon.signin.client; import net.minecraft.client.Minecraft; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -17,15 +17,15 @@ public final class Hotkey { @SubscribeEvent public static void keyTyped(InputEvent.KeyInputEvent event) { - if (SignMeUpClient.keyOpenMap != null && SignMeUpClient.keyOpenMap.isPressed()) { + if (SignMeUpClient.keyOpenMap != null && SignMeUpClient.keyOpenMap.isDown()) { Minecraft mc = Minecraft.getInstance(); if (mc.player != null) { - final Vector3d position = mc.player.getPositionVec(); + final Vec3 position = mc.player.position(); final Map.Entry entry = SignMeUpClient.MANAGER.nearestTo(position); if (entry != null) { - mc.displayGuiScreen(new GuideMapScreen(entry.getKey(), entry.getValue(), position)); + mc.setScreen(new GuideMapScreen(entry.getKey(), entry.getValue(), position)); } else { - mc.player.sendStatusMessage(new TranslationTextComponent("sign_up.status.no_map_available"), true); + mc.player.displayClientMessage(new TranslatableComponent("sign_up.status.no_map_available"), true); } } } diff --git a/src/main/java/org/teacon/signin/client/SignMeUpClient.java b/src/main/java/org/teacon/signin/client/SignMeUpClient.java index cf318e4..cbebea8 100644 --- a/src/main/java/org/teacon/signin/client/SignMeUpClient.java +++ b/src/main/java/org/teacon/signin/client/SignMeUpClient.java @@ -1,27 +1,28 @@ package org.teacon.signin.client; -import net.minecraft.client.settings.KeyBinding; -import net.minecraft.client.util.InputMappings; +import com.mojang.blaze3d.platform.InputConstants; +import net.minecraft.client.KeyMapping; import net.minecraftforge.api.distmarker.Dist; +import net.minecraftforge.client.ClientRegistry; import net.minecraftforge.client.settings.KeyConflictContext; import net.minecraftforge.client.settings.KeyModifier; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import org.lwjgl.glfw.GLFW; + @Mod.EventBusSubscriber(modid = "sign_up", bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public final class SignMeUpClient { public static final ClientGuideMapManager MANAGER = new ClientGuideMapManager(); - static KeyBinding keyOpenMap; + static KeyMapping keyOpenMap; @SubscribeEvent public static void setup(FMLClientSetupEvent event) { - ClientRegistry.registerKeyBinding(keyOpenMap = new KeyBinding("sign_up.keybinding.open_map", + ClientRegistry.registerKeyBinding(keyOpenMap = new KeyMapping("sign_up.keybinding.open_map", KeyConflictContext.IN_GAME, KeyModifier.NONE, - InputMappings.Type.KEYSYM, GLFW.GLFW_KEY_M, "sign_up.keybinding")); + InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_M, "sign_up.keybinding")); } } diff --git a/src/main/java/org/teacon/signin/command/CommandImpl.java b/src/main/java/org/teacon/signin/command/CommandImpl.java index 304eac0..1ac10a0 100644 --- a/src/main/java/org/teacon/signin/command/CommandImpl.java +++ b/src/main/java/org/teacon/signin/command/CommandImpl.java @@ -4,22 +4,22 @@ import com.mojang.brigadier.context.CommandContext; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.datafixers.util.Function4; -import net.minecraft.command.CommandSource; -import net.minecraft.command.arguments.ResourceLocationArgument; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.util.RegistryKey; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.StringTextComponent; -import net.minecraft.util.text.TranslationTextComponent; -import net.minecraft.world.World; -import net.minecraftforge.fml.network.NetworkDirection; + +import net.minecraft.commands.CommandSourceStack; +import net.minecraft.commands.arguments.ResourceLocationArgument; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceKey; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.level.Level; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.network.NetworkDirection; + import org.teacon.signin.SignMeUp; import org.teacon.signin.data.DynamicLocationStorage; import org.teacon.signin.data.GuideMap; -import org.teacon.signin.data.Trigger; import org.teacon.signin.data.Waypoint; import org.teacon.signin.network.MapScreenPacket; @@ -30,99 +30,99 @@ * This class contains command execution implementations */ public final class CommandImpl { - public static final TranslationTextComponent ERROR = new TranslationTextComponent("sign_up.text.error"); + public static final TranslatableComponent ERROR = new TranslatableComponent("sign_up.text.error"); - public static int trigger(CommandContext context) throws CommandSyntaxException { - final ResourceLocation triggerId = ResourceLocationArgument.getResourceLocation(context, "id"); - final BlockPos pos = new BlockPos(context.getSource().getPos()); - final ServerPlayerEntity src = context.getSource().asPlayer(); + public static int trigger(CommandContext context) throws CommandSyntaxException { + final ResourceLocation triggerId = ResourceLocationArgument.getId(context, "id"); + final BlockPos pos = new BlockPos(context.getSource().getPosition()); + final ServerPlayer src = context.getSource().getPlayerOrException(); return SignMeUp.trigger(src, pos, triggerId, true) ? 1 : 0; } - public static int listMaps(CommandContext context) { - CommandSource src = context.getSource(); + public static int listMaps(CommandContext context) { + CommandSourceStack src = context.getSource(); if (SignMeUp.MANAGER.getAllMaps().size() != 0) { - src.sendFeedback(new TranslationTextComponent("sign_up.text.list_maps") - .appendString(": ") + src.sendSuccess(new TranslatableComponent("sign_up.text.list_maps") + .append(": ") , false); for (GuideMap map : SignMeUp.MANAGER.getAllMaps()) { - src.sendFeedback(map.getTitle(), false); + src.sendSuccess(map.getTitle(), false); } return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR - .appendString(": ") - .appendSibling(new TranslationTextComponent("sign_up.text.no_map_exists")) + src.sendFailure(ERROR + .append(": ") + .append(new TranslatableComponent("sign_up.text.no_map_exists")) ); return -1; } } - public static int closeSpecificMap(CommandContext context) throws CommandSyntaxException { - CommandSource src = context.getSource(); - ServerPlayerEntity player = context.getSource().asPlayer(); + public static int closeSpecificMap(CommandContext context) throws CommandSyntaxException { + CommandSourceStack src = context.getSource(); + ServerPlayer player = context.getSource().getPlayerOrException(); final ResourceLocation id = context.getArgument("id", ResourceLocation.class); GuideMap map = SignMeUp.MANAGER.findMap(id); if (map != null) { // Here we have to send a packet to client side // for rendering the map GUI - MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.CLOSE_SPECIFIC, src.getPos(), id); - SignMeUp.channel.sendTo(packet, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.CLOSE_SPECIFIC, src.getPosition(), id); + SignMeUp.channel.sendTo(packet, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR - .appendString(": ") - .appendSibling(new TranslationTextComponent("sign_up.text.map")) - .appendString(" " + id.toString() + " ") - .appendSibling(new TranslationTextComponent("sign_up.text.does_not_exist")) + src.sendFailure(ERROR + .append(": ") + .append(new TranslatableComponent("sign_up.text.map")) + .append(" " + id.toString() + " ") + .append(new TranslatableComponent("sign_up.text.does_not_exist")) ); return -1; } } - public static int closeAnyMap(CommandContext context) throws CommandSyntaxException { - ServerPlayerEntity player = context.getSource().asPlayer(); - MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.CLOSE_ANY, Vector3d.ZERO, null); - SignMeUp.channel.sendTo(packet, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + public static int closeAnyMap(CommandContext context) throws CommandSyntaxException { + ServerPlayer player = context.getSource().getPlayerOrException(); + MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.CLOSE_ANY, Vec3.ZERO, null); + SignMeUp.channel.sendTo(packet, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); return Command.SINGLE_SUCCESS; } - public static int openSpecificMap(CommandContext context) throws CommandSyntaxException { - CommandSource src = context.getSource(); - ServerPlayerEntity player = context.getSource().asPlayer(); + public static int openSpecificMap(CommandContext context) throws CommandSyntaxException { + CommandSourceStack src = context.getSource(); + ServerPlayer player = context.getSource().getPlayerOrException(); final ResourceLocation id = context.getArgument("id", ResourceLocation.class); GuideMap map = SignMeUp.MANAGER.findMap(id); if (map != null) { // Here we have to send a packet to client side // for rendering the map GUI - final MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.OPEN_SPECIFIC, src.getPos(), id); - SignMeUp.channel.sendTo(packet, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + final MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.OPEN_SPECIFIC, src.getPosition(), id); + SignMeUp.channel.sendTo(packet, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR - .appendString(": ") - .appendSibling(new TranslationTextComponent("sign_up.text.map")) - .appendString(" " + id.toString() + " ") - .appendSibling(new TranslationTextComponent("sign_up.text.does_not_exist")) + src.sendFailure(ERROR + .append(": ") + .append(new TranslatableComponent("sign_up.text.map")) + .append(" " + id.toString() + " ") + .append(new TranslatableComponent("sign_up.text.does_not_exist")) ); return -1; } } - public static int openNearestMap(CommandContext context) throws CommandSyntaxException { - CommandSource src = context.getSource(); - ServerPlayerEntity player = src.asPlayer(); - RegistryKey worldKey = src.getWorld().getDimensionKey(); + public static int openNearestMap(CommandContext context) throws CommandSyntaxException { + CommandSourceStack src = context.getSource(); + ServerPlayer player = src.getPlayerOrException(); + ResourceKey worldKey = src.getLevel().dimension(); GuideMap map = null; double minDistanceSq = Double.MAX_VALUE; // We first check the dimension - if (src.asPlayer().world.getDimensionKey() == worldKey) { + if (src.getPlayerOrException().getLevel().dimension() == worldKey) { // Then we look for the nearest in-range map for (GuideMap guideMap : SignMeUp.MANAGER.getAllMaps()) { - final double dx = src.getPos().getX() - guideMap.center.getX(); - final double dz = src.getPos().getZ() - guideMap.center.getZ(); + final double dx = src.getPosition().x() - guideMap.center.getX(); + final double dz = src.getPosition().z() - guideMap.center.getZ(); if (Math.min(Math.abs(dx), Math.abs(dz)) <= guideMap.radius) { final double distanceSq = dx * dx + dz * dz; if (distanceSq < minDistanceSq) { @@ -135,128 +135,128 @@ public static int openNearestMap(CommandContext context) throws C if (map != null) { // Same packet as above - final MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.OPEN_SPECIFIC, src.getPos(), SignMeUp.MANAGER.findMapId(map)); - SignMeUp.channel.sendTo(packet, player.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + final MapScreenPacket packet = new MapScreenPacket(MapScreenPacket.Action.OPEN_SPECIFIC, src.getPosition(), SignMeUp.MANAGER.findMapId(map)); + SignMeUp.channel.sendTo(packet, player.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR - .appendString(": ") - .appendSibling(new TranslationTextComponent("sign_up.status.no_map_available")) + src.sendFailure(ERROR + .append(": ") + .append(new TranslatableComponent("sign_up.status.no_map_available")) ); return -1; } } - public static int listWaypoints(CommandContext context) throws CommandSyntaxException { - CommandSource src = context.getSource(); - ServerPlayerEntity player = src.asPlayer(); + public static int listWaypoints(CommandContext context) throws CommandSyntaxException { + CommandSourceStack src = context.getSource(); + ServerPlayer player = src.getPlayerOrException(); if (SignMeUp.MANAGER.getAllWaypoints().size() != 0) { - src.sendFeedback(new TranslationTextComponent("sign_up.text.list_points") - .appendString(": ") + src.sendSuccess(new TranslatableComponent("sign_up.text.list_points") + .append(": ") , false); for (Waypoint waypoint : SignMeUp.MANAGER.getAllWaypoints()) { DecimalFormat df = new DecimalFormat("0.00"); df.setRoundingMode(RoundingMode.HALF_UP); - src.sendFeedback(new StringTextComponent(" - ") - .appendSibling(waypoint.getTitle()).appendString("\n ") - .appendSibling(new TranslationTextComponent("sign_up.text.distance")) - .appendString(": " + df.format(Vector3d.copy(waypoint.getActualLocation()).distanceTo(src.getPos())) + " ") - .appendSibling(new TranslationTextComponent("sign_up.text.blocks_away")) + src.sendSuccess(new TextComponent(" - ") + .append(waypoint.getTitle()).append("\n ") + .append(new TranslatableComponent("sign_up.text.distance")) + .append(": " + df.format(Vec3.atLowerCornerOf(waypoint.getActualLocation()).distanceTo(src.getPosition())) + " ") + .append(new TranslatableComponent("sign_up.text.blocks_away")) , false ); } return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR.appendString(": ").appendSibling(new TranslationTextComponent("sign_up.text.no_waypoint_exists"))); + src.sendFailure(ERROR.append(": ").append(new TranslatableComponent("sign_up.text.no_waypoint_exists"))); return -1; } } - public static int listWaypointPos(CommandContext context) { - CommandSource src = context.getSource(); + public static int listWaypointPos(CommandContext context) { + CommandSourceStack src = context.getSource(); if (SignMeUp.MANAGER.getAllWaypoints().size() != 0) { - src.sendFeedback(new TranslationTextComponent("sign_up.text.list_points"), false); + src.sendSuccess(new TranslatableComponent("sign_up.text.list_points"), false); for (Waypoint waypoint : SignMeUp.MANAGER.getAllWaypoints()) { - src.sendFeedback(new StringTextComponent(" - ") - .appendSibling(waypoint.getTitle()) - .appendString("\n ") - .appendSibling(new TranslationTextComponent("sign_up.text.render_location")) - .appendString(": ") - .appendString(waypoint.getRenderLocation().getCoordinatesAsString()) - .appendString("\n ") - .appendSibling(new TranslationTextComponent("sign_up.text.actual_location")) - .appendString(": ") - .appendString(waypoint.getActualLocation().getCoordinatesAsString()) + src.sendSuccess(new TextComponent(" - ") + .append(waypoint.getTitle()) + .append("\n ") + .append(new TranslatableComponent("sign_up.text.render_location")) + .append(": ") + .append(waypoint.getRenderLocation().toShortString()) + .append("\n ") + .append(new TranslatableComponent("sign_up.text.actual_location")) + .append(": ") + .append(waypoint.getActualLocation().toShortString()) , false ); } return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(ERROR.appendString(": ").appendSibling(new TranslationTextComponent("sign_up.text.no_waypoint_exists"))); + src.sendFailure(ERROR.append(": ").append(new TranslatableComponent("sign_up.text.no_waypoint_exists"))); return -1; } } - public static int getWaypointPos(CommandContext context) { - CommandSource src = context.getSource(); + public static int getWaypointPos(CommandContext context) { + CommandSourceStack src = context.getSource(); final ResourceLocation id = context.getArgument("id", ResourceLocation.class); Waypoint waypoint = SignMeUp.MANAGER.findWaypoint(id); if (waypoint != null) { - src.sendFeedback(new StringTextComponent(" - ") - .appendSibling(waypoint.getTitle()) - .appendString("\n ") - .appendSibling(new TranslationTextComponent("sign_up.text.render_location")) - .appendString(": ") - .appendString(waypoint.getRenderLocation().getCoordinatesAsString()) - .appendString("\n ") - .appendSibling(new TranslationTextComponent("sign_up.text.actual_location")) - .appendString(": ") - .appendString(waypoint.getActualLocation().getCoordinatesAsString()) + src.sendSuccess(new TextComponent(" - ") + .append(waypoint.getTitle()) + .append("\n ") + .append(new TranslatableComponent("sign_up.text.render_location")) + .append(": ") + .append(waypoint.getRenderLocation().toShortString()) + .append("\n ") + .append(new TranslatableComponent("sign_up.text.actual_location")) + .append(": ") + .append(waypoint.getActualLocation().toShortString()) , false ); return Command.SINGLE_SUCCESS; } else { - src.sendErrorMessage(new StringTextComponent("Error: waypoint " + id + " does not exist")); - src.sendErrorMessage(ERROR - .appendString(": ") - .appendSibling(new TranslationTextComponent("sign_up.text.waypoint") - .appendString(" " + id.toString() + " ") - .appendSibling(new TranslationTextComponent("sign_up.text.does_not_exist"))) + src.sendFailure(new TextComponent("Error: waypoint " + id + " does not exist")); + src.sendFailure(ERROR + .append(": ") + .append(new TranslatableComponent("sign_up.text.waypoint") + .append(" " + id.toString() + " ") + .append(new TranslatableComponent("sign_up.text.does_not_exist"))) ); return -1; } } - public static int setWaypointActualPos(CommandContext context) { - return setDynamicWaypointPosImpl(context, (store, id, world, pos) -> { - store.setActual(id, world, pos); + public static int setWaypointActualPos(CommandContext context) { + return setDynamicWaypointPosImpl(context, (store, id, level, pos) -> { + store.setActual(id, level, pos); return Command.SINGLE_SUCCESS; }); } - public static int setWaypointRenderPos(CommandContext context) { - return setDynamicWaypointPosImpl(context, (store, id, world, pos) -> { - store.setRendering(id, world, pos); + public static int setWaypointRenderPos(CommandContext context) { + return setDynamicWaypointPosImpl(context, (store, id, level, pos) -> { + store.setRendering(id, level, pos); return Command.SINGLE_SUCCESS; }); } - public static int setDynamicWaypointPosImpl(CommandContext context, Function4 handler) { - final CommandSource src = context.getSource(); - final World world = src.getWorld(); + public static int setDynamicWaypointPosImpl(CommandContext context, Function4 handler) { + final CommandSourceStack src = context.getSource(); + final Level level = src.getLevel(); final BlockPos pos = context.getArgument("pos", BlockPos.class); final ResourceLocation id = context.getArgument("id", ResourceLocation.class); final Waypoint wp = SignMeUp.MANAGER.findWaypoint(id); if (wp != null) { if (wp.hasDynamicLocation()) { - return world.getCapability(DynamicLocationStorage.CAP).map(store -> handler.apply(store, id, world, pos)).orElse(-1); + return level.getCapability(DynamicLocationStorage.CAP).map(store -> handler.apply(store, id, level, pos)).orElse(-1); } else { - src.sendErrorMessage(new StringTextComponent("Error: waypoint " + id + " is static")); + src.sendFailure(new TextComponent("Error: waypoint " + id + " is static")); return -1; } } else { - src.sendErrorMessage(new StringTextComponent("Error: waypoint " + id + " does not exist")); + src.sendFailure(new TextComponent("Error: waypoint " + id + " does not exist")); return -1; } } diff --git a/src/main/java/org/teacon/signin/data/DynamicLocationStorage.java b/src/main/java/org/teacon/signin/data/DynamicLocationStorage.java index 3959b8a..e69b3d9 100644 --- a/src/main/java/org/teacon/signin/data/DynamicLocationStorage.java +++ b/src/main/java/org/teacon/signin/data/DynamicLocationStorage.java @@ -1,15 +1,14 @@ package org.teacon.signin.data; -import net.minecraft.nbt.CompoundNBT; -import net.minecraft.nbt.INBT; -import net.minecraft.nbt.NBTDynamicOps; -import net.minecraft.util.Direction; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.GlobalPos; -import net.minecraft.world.World; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; +import net.minecraft.core.GlobalPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtOps; +import net.minecraft.nbt.Tag; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.Level; import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.CapabilityInject; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.LazyOptional; @@ -25,7 +24,6 @@ public final class DynamicLocationStorage { private static final Logger LOGGER = LogManager.getLogger("SignMeUp"); - @CapabilityInject(DynamicLocationStorage.class) public static Capability CAP; final Map pos = new HashMap<>(); @@ -39,30 +37,27 @@ public GlobalPos getRendering(ResourceLocation id) { return renderPos.get(id); } - public void setActual(ResourceLocation id, World world, BlockPos pos) { - this.pos.put(id, GlobalPos.getPosition(world.getDimensionKey(), pos)); + public void setActual(ResourceLocation id, Level level, BlockPos pos) { + this.pos.put(id, GlobalPos.of(level.dimension(), pos)); } - public void setRendering(ResourceLocation id, World world, BlockPos pos) { - this.renderPos.put(id, GlobalPos.getPosition(world.getDimensionKey(), pos)); + public void setRendering(ResourceLocation id, Level level, BlockPos pos) { + this.renderPos.put(id, GlobalPos.of(level.dimension(), pos)); } - public static final class Serializer implements Capability.IStorage { - - @Override - public INBT writeNBT(Capability capability, DynamicLocationStorage instance, Direction side) { + public static final class Serializer { + public Tag writeNBT(Capability capability, DynamicLocationStorage instance, Direction side) { return writeNBTImpl(instance); } - @Override - public void readNBT(Capability capability, DynamicLocationStorage instance, Direction side, INBT nbt) { + public void readNBT(Capability capability, DynamicLocationStorage instance, Direction side, Tag nbt) { readNBTImpl(instance, nbt); } - public static CompoundNBT writeNBTImpl(DynamicLocationStorage instance) { - final CompoundNBT data = new CompoundNBT(); - final CompoundNBT actualPoses = new CompoundNBT(); - final CompoundNBT renderPoses = new CompoundNBT(); + public static CompoundTag writeNBTImpl(DynamicLocationStorage instance) { + final CompoundTag data = new CompoundTag(); + final CompoundTag actualPoses = new CompoundTag(); + final CompoundTag renderPoses = new CompoundTag(); instance.pos.forEach((id, pos) -> collect(id, pos, actualPoses)); instance.renderPos.forEach((id, pos) -> collect(id, pos, renderPoses)); data.put("actual", actualPoses); @@ -70,26 +65,26 @@ public static CompoundNBT writeNBTImpl(DynamicLocationStorage instance) { return data; } - public static void readNBTImpl(DynamicLocationStorage instance, INBT nbt) { - if (nbt instanceof CompoundNBT) { - final CompoundNBT data = (CompoundNBT) nbt; - final CompoundNBT actualPoses = data.getCompound("actual"); - final CompoundNBT renderPoses = data.getCompound("render"); - actualPoses.keySet().forEach(id -> parse(actualPoses, id, instance.pos)); - renderPoses.keySet().forEach(id -> parse(renderPoses, id, instance.renderPos)); + public static void readNBTImpl(DynamicLocationStorage instance, Tag nbt) { + if (nbt instanceof CompoundTag) { + final CompoundTag data = (CompoundTag) nbt; + final CompoundTag actualPoses = data.getCompound("actual"); + final CompoundTag renderPoses = data.getCompound("render"); + actualPoses.getAllKeys().forEach(id -> parse(actualPoses, id, instance.pos)); + renderPoses.getAllKeys().forEach(id -> parse(renderPoses, id, instance.renderPos)); } } - private static void collect(ResourceLocation id, GlobalPos pos, CompoundNBT dst) { - dst.put(id.toString(), GlobalPos.CODEC.encodeStart(NBTDynamicOps.INSTANCE, pos).getOrThrow(false, LOGGER::warn)); + private static void collect(ResourceLocation id, GlobalPos pos, CompoundTag dst) { + dst.put(id.toString(), GlobalPos.CODEC.encodeStart(NbtOps.INSTANCE, pos).getOrThrow(false, LOGGER::warn)); } - private static void parse(CompoundNBT src, String id, Map dst) { - dst.put(new ResourceLocation(id), GlobalPos.CODEC.parse(NBTDynamicOps.INSTANCE, src.get(id)).getOrThrow(false, LOGGER::warn)); + private static void parse(CompoundTag src, String id, Map dst) { + dst.put(new ResourceLocation(id), GlobalPos.CODEC.parse(NbtOps.INSTANCE, src.get(id)).getOrThrow(false, LOGGER::warn)); } } - public static final class Holder implements ICapabilityProvider, INBTSerializable { + public static final class Holder implements ICapabilityProvider, INBTSerializable { private final DynamicLocationStorage storage = new DynamicLocationStorage(); private final LazyOptional wrapped = LazyOptional.of(() -> this.storage); @@ -101,12 +96,12 @@ public LazyOptional getCapability(@Nonnull Capability cap, @Nullable D } @Override - public CompoundNBT serializeNBT() { + public CompoundTag serializeNBT() { return Serializer.writeNBTImpl(this.storage); } @Override - public void deserializeNBT(CompoundNBT nbt) { + public void deserializeNBT(CompoundTag nbt) { Serializer.readNBTImpl(this.storage, nbt); } } diff --git a/src/main/java/org/teacon/signin/data/GuideMap.java b/src/main/java/org/teacon/signin/data/GuideMap.java index 70b55e9..e4971b1 100644 --- a/src/main/java/org/teacon/signin/data/GuideMap.java +++ b/src/main/java/org/teacon/signin/data/GuideMap.java @@ -10,11 +10,11 @@ import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.JsonSyntaxException; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.StringTextComponent; -import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.core.Vec3i; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -29,11 +29,11 @@ public final class GuideMap { public static final ResourceLocation DEFAULT_IMAGE = new ResourceLocation("sign_up:textures/map_default.png"); - ITextComponent title; - ITextComponent subtitle; - ITextComponent desc; + Component title; + Component subtitle; + Component desc; - public Vector3i center; + public Vec3i center; public float radius = 128F; public ResourceLocation dim = null; @@ -47,16 +47,16 @@ public final class GuideMap { List waypointIds = Collections.emptyList(); List triggerIds = Collections.emptyList(); - public ITextComponent getTitle() { - return this.title != null ? this.title : new TranslationTextComponent("sign_up.map.unnamed"); + public Component getTitle() { + return this.title != null ? this.title : new TranslatableComponent("sign_up.map.unnamed"); } - public ITextComponent getSubtitle() { + public Component getSubtitle() { return this.subtitle != null ? this.subtitle : this.getTitle(); } - public ITextComponent getDesc() { - return this.desc != null ? this.desc : StringTextComponent.EMPTY; + public Component getDesc() { + return this.desc != null ? this.desc : TextComponent.EMPTY; } public boolean hasMoreThanOneImage() { @@ -94,16 +94,16 @@ public GuideMap deserialize(JsonElement src, Type type, JsonDeserializationConte } final JsonObject json = src.getAsJsonObject(); if (json.has("title")) { - map.title = context.deserialize(json.get("title"), ITextComponent.class); + map.title = context.deserialize(json.get("title"), Component.class); } if (json.has("subtitle")) { - map.subtitle = context.deserialize(json.get("subtitle"), ITextComponent.class); + map.subtitle = context.deserialize(json.get("subtitle"), Component.class); } if (json.has("description")) { - map.desc = context.deserialize(json.get("description"), ITextComponent.class); + map.desc = context.deserialize(json.get("description"), Component.class); } if (json.has("center")) { - map.center = context.deserialize(json.get("center"), Vector3i.class); + map.center = context.deserialize(json.get("center"), Vec3i.class); } else { LOGGER.warn(MARKER, "Center coordinate missing, falling back to [0, 0]."); } diff --git a/src/main/java/org/teacon/signin/data/GuideMapManager.java b/src/main/java/org/teacon/signin/data/GuideMapManager.java index a1cee7a..ecc644d 100644 --- a/src/main/java/org/teacon/signin/data/GuideMapManager.java +++ b/src/main/java/org/teacon/signin/data/GuideMapManager.java @@ -5,19 +5,19 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.client.resources.JsonReloadListener; // To anyone who are shocked: yes this class exists on both side! -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.profiler.IProfiler; -import net.minecraft.resources.IResourceManager; +import net.minecraft.core.Vec3i; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.ITextComponent; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.server.packs.resources.SimpleJsonResourceReloadListener; +import net.minecraft.util.profiling.ProfilerFiller; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; -import net.minecraftforge.fml.network.NetworkDirection; -import net.minecraftforge.fml.server.ServerLifecycleHooks; +import net.minecraftforge.network.NetworkDirection; +import net.minecraftforge.server.ServerLifecycleHooks; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Marker; @@ -35,18 +35,18 @@ import java.util.TreeMap; import java.util.WeakHashMap; -public final class GuideMapManager extends JsonReloadListener { +public final class GuideMapManager extends SimpleJsonResourceReloadListener { private static final Logger LOGGER = LogManager.getLogger("SignMeUp"); private static final Marker MARKER = MarkerManager.getMarker("GuideMapManager"); private static final Gson GSON = new GsonBuilder().setLenient() - .registerTypeHierarchyAdapter(ITextComponent.class, new ITextComponent.Serializer()) + .registerTypeHierarchyAdapter(Component.class, new Component.Serializer()) .registerTypeAdapter(GuideMap.class, new GuideMap.Serializer()) .registerTypeAdapter(Waypoint.class, new Waypoint.Serializer()) .registerTypeAdapter(Waypoint.Location.class, new Waypoint.Location.Serializer()) .registerTypeAdapter(Trigger.class, new Trigger.Serializer()) - .registerTypeAdapter(Vector3i.class, new Vector3iAdapter()) + .registerTypeAdapter(Vec3i.class, new Vector3iAdapter()) .create(); private static void setDiff(Set a, Set b, Set aMinusB, Set bMinusA) { @@ -74,15 +74,15 @@ public GuideMapManager() { @SubscribeEvent public void sync(EntityJoinWorldEvent event) { // Being a ServerPlayerEntity implies a logical server, thus no isRemote check. - if (event.getEntity() instanceof ServerPlayerEntity) { - final ServerPlayerEntity p = (ServerPlayerEntity) event.getEntity(); + if (event.getEntity() instanceof ServerPlayer) { + final ServerPlayer p = (ServerPlayer) event.getEntity(); final SortedMap mapsToSend = new TreeMap<>(); this.maps.forEach((id, map) -> { - if (p.world.getDimensionKey().getLocation().equals(map.dim)) { + if (p.level.dimension().location().equals(map.dim)) { mapsToSend.put(id, map); } }); - SignMeUp.channel.sendTo(new SyncGuideMapPacket(mapsToSend), p.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + SignMeUp.channel.sendTo(new SyncGuideMapPacket(mapsToSend), p.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); } } @@ -110,32 +110,32 @@ private static void tickOne(ResourceLocation id, PlayerTracker trackingComponent * packet so the client manager will receive that waypoint. * These players form the set diff 2 - 1. */ - final Set matched = Collections.newSetFromMap(new WeakHashMap<>()); + final Set matched = Collections.newSetFromMap(new WeakHashMap<>()); try { - matched.addAll(trackingComponent.getSelector().selectPlayers(server.getCommandSource())); + matched.addAll(trackingComponent.getSelector().findPlayers(server.createCommandSourceStack())); } catch (CommandSyntaxException e) { return; } - final Set update = Collections.newSetFromMap(new IdentityHashMap<>()); - final Set removal = Collections.newSetFromMap(new IdentityHashMap<>()); + final Set update = Collections.newSetFromMap(new IdentityHashMap<>()); + final Set removal = Collections.newSetFromMap(new IdentityHashMap<>()); setDiff(trackingComponent.getTracking(), matched, removal, update); - for (ServerPlayerEntity p : update) { - SignMeUp.channel.sendTo(trackingComponent.getNotifyPacket(false, id), p.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + for (ServerPlayer p : update) { + SignMeUp.channel.sendTo(trackingComponent.getNotifyPacket(false, id), p.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); } - for (ServerPlayerEntity p : removal) { - SignMeUp.channel.sendTo(trackingComponent.getNotifyPacket(true, id), p.connection.netManager, NetworkDirection.PLAY_TO_CLIENT); + for (ServerPlayer p : removal) { + SignMeUp.channel.sendTo(trackingComponent.getNotifyPacket(true, id), p.connection.getConnection(), NetworkDirection.PLAY_TO_CLIENT); } trackingComponent.setTracking(matched); } @Override - protected void apply(Map objects, IResourceManager manager, IProfiler profiler) { + protected void apply(Map objects, ResourceManager manager, ProfilerFiller profiler) { this.maps.clear(); this.points.clear(); this.triggers.clear(); - profiler.startSection("SignInGuides"); + profiler.push("SignInGuides"); objects.forEach(this::process); - profiler.endSection(); + profiler.pop(); } private void process(ResourceLocation id, JsonElement json) { diff --git a/src/main/java/org/teacon/signin/data/PlayerTracker.java b/src/main/java/org/teacon/signin/data/PlayerTracker.java index 03e8840..d03fa38 100644 --- a/src/main/java/org/teacon/signin/data/PlayerTracker.java +++ b/src/main/java/org/teacon/signin/data/PlayerTracker.java @@ -1,8 +1,9 @@ package org.teacon.signin.data; -import net.minecraft.command.arguments.EntitySelector; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.util.ResourceLocation; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; + import org.teacon.signin.network.PartialUpdatePacket; import java.util.Set; @@ -11,9 +12,9 @@ public interface PlayerTracker { EntitySelector getSelector(); - Set getTracking(); + Set getTracking(); - void setTracking(Set players); + void setTracking(Set players); PartialUpdatePacket getNotifyPacket(boolean remove, ResourceLocation id); } diff --git a/src/main/java/org/teacon/signin/data/Trigger.java b/src/main/java/org/teacon/signin/data/Trigger.java index f0d4d12..ed7f4ad 100644 --- a/src/main/java/org/teacon/signin/data/Trigger.java +++ b/src/main/java/org/teacon/signin/data/Trigger.java @@ -4,13 +4,13 @@ import com.google.gson.*; import com.mojang.brigadier.StringReader; import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.command.arguments.EntitySelector; -import net.minecraft.command.arguments.EntitySelectorParser; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.Util; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.Util; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.commands.arguments.selector.EntitySelectorParser; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; import org.teacon.signin.network.PartialUpdatePacket; import java.lang.reflect.Type; @@ -20,8 +20,8 @@ public final class Trigger implements PlayerTracker { - ITextComponent title; - ITextComponent desc; + Component title; + Component desc; public volatile boolean disabled = false; @@ -30,13 +30,13 @@ public final class Trigger implements PlayerTracker { public ImmutableList executes = ImmutableList.of(); - transient Set visiblePlayers = Collections.newSetFromMap(new WeakHashMap<>()); + transient Set visiblePlayers = Collections.newSetFromMap(new WeakHashMap<>()); - public ITextComponent getTitle() { - return this.title == null ? new TranslationTextComponent("sign_up.trigger.unnamed") : this.title; + public Component getTitle() { + return this.title == null ? new TranslatableComponent("sign_up.trigger.unnamed") : this.title; } - public ITextComponent getDesc() { + public Component getDesc() { return this.desc == null ? this.getTitle() : this.desc; } @@ -52,17 +52,17 @@ public EntitySelector getSelector() { return parsedSelector; } - public boolean isVisibleTo(ServerPlayerEntity p) { + public boolean isVisibleTo(ServerPlayer p) { return this.visiblePlayers.contains(p); } @Override - public Set getTracking() { + public Set getTracking() { return this.visiblePlayers; } @Override - public void setTracking(Set players) { + public void setTracking(Set players) { this.visiblePlayers = players; } @@ -79,10 +79,10 @@ public Trigger deserialize(JsonElement json, Type typeOfT, JsonDeserializationCo final JsonObject obj = json.getAsJsonObject(); final Trigger t = new Trigger(); if (obj.has("title")) { - t.title = context.deserialize(obj.get("title"), ITextComponent.class); + t.title = context.deserialize(obj.get("title"), Component.class); } if (obj.has("description")) { - t.desc = context.deserialize(obj.get("description"), ITextComponent.class); + t.desc = context.deserialize(obj.get("description"), Component.class); } if (obj.has("disabled")) { t.disabled = obj.get("disabled").getAsBoolean(); diff --git a/src/main/java/org/teacon/signin/data/Vector3iAdapter.java b/src/main/java/org/teacon/signin/data/Vector3iAdapter.java index 92ca6ae..94cd2aa 100644 --- a/src/main/java/org/teacon/signin/data/Vector3iAdapter.java +++ b/src/main/java/org/teacon/signin/data/Vector3iAdapter.java @@ -1,28 +1,28 @@ package org.teacon.signin.data; import com.google.gson.*; -import net.minecraft.util.math.vector.Vector3i; +import net.minecraft.core.Vec3i; import java.lang.reflect.Type; public final class Vector3iAdapter - implements JsonSerializer, JsonDeserializer { + implements JsonSerializer, JsonDeserializer { @Override - public Vector3i deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + public Vec3i deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonArray()) { JsonArray arr = json.getAsJsonArray(); if (arr.size() == 3) { - return new Vector3i(arr.get(0).getAsInt(), arr.get(1).getAsInt(), arr.get(2).getAsInt()); + return new Vec3i(arr.get(0).getAsInt(), arr.get(1).getAsInt(), arr.get(2).getAsInt()); } else if (arr.size() == 2) { - return new Vector3i(arr.get(0).getAsInt(), 0, arr.get(1).getAsInt()); + return new Vec3i(arr.get(0).getAsInt(), 0, arr.get(1).getAsInt()); } } throw new JsonSyntaxException("Coordinates must be array of 2 or 3 integers"); } @Override - public JsonElement serialize(Vector3i src, Type typeOfSrc, JsonSerializationContext context) { + public JsonElement serialize(Vec3i src, Type typeOfSrc, JsonSerializationContext context) { JsonArray arr = new JsonArray(); arr.add(src.getX()); arr.add(src.getY()); diff --git a/src/main/java/org/teacon/signin/data/Waypoint.java b/src/main/java/org/teacon/signin/data/Waypoint.java index 38d0453..72c5ce7 100644 --- a/src/main/java/org/teacon/signin/data/Waypoint.java +++ b/src/main/java/org/teacon/signin/data/Waypoint.java @@ -10,14 +10,14 @@ import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.mojang.brigadier.StringReader; -import net.minecraft.command.arguments.EntitySelector; -import net.minecraft.command.arguments.EntitySelectorParser; -import net.minecraft.entity.player.ServerPlayerEntity; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.ITextComponent; -import net.minecraft.util.text.StringTextComponent; -import net.minecraft.util.text.TranslationTextComponent; +import net.minecraft.commands.arguments.selector.EntitySelector; +import net.minecraft.commands.arguments.selector.EntitySelectorParser; +import net.minecraft.core.Vec3i; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.TextComponent; +import net.minecraft.network.chat.TranslatableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerPlayer; import org.teacon.signin.network.PartialUpdatePacket; import java.lang.reflect.Type; @@ -31,11 +31,11 @@ public final class Waypoint implements PlayerTracker { public static final class Location { - Vector3i actualLocation; - private Vector3i renderLocation; + Vec3i actualLocation; + private Vec3i renderLocation; boolean isDynamic = false; - public Vector3i getRenderLocation() { + public Vec3i getRenderLocation() { return this.renderLocation == null ? this.actualLocation : this.renderLocation; } @@ -50,9 +50,9 @@ public Location deserialize(JsonElement json, Type type, JsonDeserializationCont return loc; } else if (json.isJsonObject()) { final JsonObject locations = json.getAsJsonObject(); - loc.actualLocation = context.deserialize(locations.get("actual"), Vector3i.class); + loc.actualLocation = context.deserialize(locations.get("actual"), Vec3i.class); if (locations.has("render")) { - loc.renderLocation = context.deserialize(locations.get("render"), Vector3i.class); + loc.renderLocation = context.deserialize(locations.get("render"), Vec3i.class); } return loc; } else { @@ -76,8 +76,8 @@ public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationCont } } - private ITextComponent title; - private ITextComponent desc; + private Component title; + private Component desc; private String selector = "@e"; private transient EntitySelector parsedSelector; @@ -90,25 +90,25 @@ public JsonElement serialize(Location src, Type typeOfSrc, JsonSerializationCont private int displayingImageIndex; - transient Set visiblePlayers = Collections.newSetFromMap(new WeakHashMap<>()); + transient Set visiblePlayers = Collections.newSetFromMap(new WeakHashMap<>()); - public ITextComponent getTitle() { - return title == null ? new TranslationTextComponent("sign_up.waypoint.unnamed") : this.title; + public Component getTitle() { + return title == null ? new TranslatableComponent("sign_up.waypoint.unnamed") : this.title; } - public ITextComponent getDesc() { - return this.desc == null ? StringTextComponent.EMPTY : this.desc; + public Component getDesc() { + return this.desc == null ? TextComponent.EMPTY : this.desc; } public boolean hasDynamicLocation() { return location.isDynamic; } - public Vector3i getRenderLocation() { + public Vec3i getRenderLocation() { return location.getRenderLocation(); } - public Vector3i getActualLocation() { + public Vec3i getActualLocation() { return location.actualLocation; } @@ -143,12 +143,12 @@ public EntitySelector getSelector() { } @Override - public Set getTracking() { + public Set getTracking() { return this.visiblePlayers; } @Override - public void setTracking(Set players) { + public void setTracking(Set players) { this.visiblePlayers = players; } @@ -165,10 +165,10 @@ public Waypoint deserialize(JsonElement json, Type typeOfT, JsonDeserializationC final JsonObject obj = json.getAsJsonObject(); final Waypoint wp = new Waypoint(); if (obj.has("title")) { - wp.title = context.deserialize(obj.get("title"), ITextComponent.class); + wp.title = context.deserialize(obj.get("title"), Component.class); } if (obj.has("description")) { - wp.desc = context.deserialize(obj.get("description"), ITextComponent.class); + wp.desc = context.deserialize(obj.get("description"), Component.class); } if (obj.has("selector")) { wp.selector = obj.get("selector").getAsString(); diff --git a/src/main/java/org/teacon/signin/network/MapScreenPacket.java b/src/main/java/org/teacon/signin/network/MapScreenPacket.java index 317f9ad..7ae6853 100644 --- a/src/main/java/org/teacon/signin/network/MapScreenPacket.java +++ b/src/main/java/org/teacon/signin/network/MapScreenPacket.java @@ -1,41 +1,41 @@ package org.teacon.signin.network; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3d; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.phys.Vec3; +import net.minecraftforge.network.NetworkEvent; import org.teacon.signin.client.SignMeUpClient; import java.util.function.Supplier; public final class MapScreenPacket { private final Action action; - private final Vector3d position; + private final Vec3 position; private final ResourceLocation mapId; - public MapScreenPacket(Action action, Vector3d position, ResourceLocation id) { + public MapScreenPacket(Action action, Vec3 position, ResourceLocation id) { this.position = position; this.action = action; this.mapId = id; } - public MapScreenPacket(PacketBuffer buf) { - this.action = buf.readEnumValue(Action.class); + public MapScreenPacket(FriendlyByteBuf buf) { + this.action = buf.readEnum(Action.class); if (this.action != Action.CLOSE_ANY) { - this.position = new Vector3d(buf.readDouble(), buf.readDouble(), buf.readDouble()); + this.position = new Vec3(buf.readDouble(), buf.readDouble(), buf.readDouble()); this.mapId = buf.readResourceLocation(); } else { - this.position = Vector3d.ZERO; + this.position = Vec3.ZERO; this.mapId = null; } } - public void write(PacketBuffer buf) { - buf.writeEnumValue(this.action); + public void write(FriendlyByteBuf buf) { + buf.writeEnum(this.action); if (this.action != Action.CLOSE_ANY) { - buf.writeDouble(this.position.getX()); - buf.writeDouble(this.position.getY()); - buf.writeDouble(this.position.getZ()); + buf.writeDouble(this.position.x()); + buf.writeDouble(this.position.y()); + buf.writeDouble(this.position.z()); buf.writeResourceLocation(this.mapId); } } diff --git a/src/main/java/org/teacon/signin/network/PartialUpdatePacket.java b/src/main/java/org/teacon/signin/network/PartialUpdatePacket.java index 0461ae5..d9d78ce 100644 --- a/src/main/java/org/teacon/signin/network/PartialUpdatePacket.java +++ b/src/main/java/org/teacon/signin/network/PartialUpdatePacket.java @@ -3,12 +3,11 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screen.Screen; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.math.vector.Vector3i; -import net.minecraft.util.text.ITextComponent; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraft.core.Vec3i; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkEvent; import org.teacon.signin.client.GuideMapScreen; import org.teacon.signin.client.SignMeUpClient; import org.teacon.signin.data.*; @@ -24,9 +23,9 @@ public enum Mode { private static final Gson GSON = new GsonBuilder().setLenient() .registerTypeAdapter(Waypoint.class, new Waypoint.Serializer()) .registerTypeAdapter(Waypoint.Location.class, new Waypoint.Location.Serializer()) - .registerTypeAdapter(Vector3i.class, new Vector3iAdapter()) + .registerTypeAdapter(Vec3i.class, new Vector3iAdapter()) .registerTypeAdapter(Trigger.class, new Trigger.Serializer()) - .registerTypeHierarchyAdapter(ITextComponent.class, new ITextComponent.Serializer()) + .registerTypeHierarchyAdapter(Component.class, new Component.Serializer()) .create(); private Mode mode; @@ -35,18 +34,18 @@ public enum Mode { private ResourceLocation triggerId; private Trigger trigger; - public PartialUpdatePacket(PacketBuffer buf) { - switch (this.mode = buf.readEnumValue(Mode.class)) { + public PartialUpdatePacket(FriendlyByteBuf buf) { + switch (this.mode = buf.readEnum(Mode.class)) { case ADD_WAYPOINT: this.waypointId = buf.readResourceLocation(); - this.waypoint = GSON.fromJson(buf.readString(Short.MAX_VALUE), Waypoint.class); + this.waypoint = GSON.fromJson(buf.readUtf(Short.MAX_VALUE), Waypoint.class); break; case REMOVE_WAYPOINT: this.waypointId = buf.readResourceLocation(); break; case ADD_TRIGGER: this.triggerId = buf.readResourceLocation(); - this.trigger = GSON.fromJson(buf.readString(Short.MAX_VALUE), Trigger.class); + this.trigger = GSON.fromJson(buf.readUtf(Short.MAX_VALUE), Trigger.class); break; case REMOVE_TRIGGER: this.triggerId = buf.readResourceLocation(); @@ -65,22 +64,22 @@ public PartialUpdatePacket(Mode mode, ResourceLocation id, Trigger trigger) { this.trigger = trigger; } - public void write(PacketBuffer buf) { - buf.writeEnumValue(this.mode); + public void write(FriendlyByteBuf buf) { + buf.writeEnum(this.mode); switch (this.mode) { case REMOVE_WAYPOINT: buf.writeResourceLocation(this.waypointId); break; case ADD_WAYPOINT: buf.writeResourceLocation(this.waypointId); - buf.writeString(GSON.toJson(this.waypoint)); + buf.writeUtf(GSON.toJson(this.waypoint)); break; case REMOVE_TRIGGER: buf.writeResourceLocation(this.triggerId); break; case ADD_TRIGGER: buf.writeResourceLocation(this.triggerId); - buf.writeString(GSON.toJson(this.trigger)); + buf.writeUtf(GSON.toJson(this.trigger)); break; } } @@ -102,8 +101,8 @@ public void handle(Supplier contextGetter) { break; } final Minecraft mc = Minecraft.getInstance(); - if (mc.currentScreen instanceof GuideMapScreen) { - ((GuideMapScreen) mc.currentScreen).refresh(); + if (mc.screen instanceof GuideMapScreen) { + ((GuideMapScreen) mc.screen).refresh(); } }); contextGetter.get().setPacketHandled(true); diff --git a/src/main/java/org/teacon/signin/network/SyncGuideMapPacket.java b/src/main/java/org/teacon/signin/network/SyncGuideMapPacket.java index 9ec7ffc..4887334 100644 --- a/src/main/java/org/teacon/signin/network/SyncGuideMapPacket.java +++ b/src/main/java/org/teacon/signin/network/SyncGuideMapPacket.java @@ -4,10 +4,11 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; -import net.minecraft.util.text.ITextComponent; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraft.network.FriendlyByteBuf; + +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkEvent; import org.teacon.signin.client.SignMeUpClient; import org.teacon.signin.data.GuideMap; @@ -21,7 +22,7 @@ public final class SyncGuideMapPacket { private static final Gson GSON = new GsonBuilder().setLenient() .registerTypeAdapter(GuideMap.class, new GuideMap.Serializer()) - .registerTypeHierarchyAdapter(ITextComponent.class, new ITextComponent.Serializer()) + .registerTypeHierarchyAdapter(Component.class, new Component.Serializer()) .create(); private final SortedMap maps; @@ -30,7 +31,7 @@ public SyncGuideMapPacket(SortedMap mapsToSend) { this.maps = mapsToSend; } - public SyncGuideMapPacket(PacketBuffer buf) { + public SyncGuideMapPacket(FriendlyByteBuf buf) { this.maps = new TreeMap<>(); // We want all guide maps to be sorted by key. try { final String src = new String(buf.readByteArray(), StandardCharsets.UTF_8); @@ -45,7 +46,7 @@ private static void accept(Map.Entry entry, Class ty dst.put(new ResourceLocation(entry.getKey()), GSON.fromJson(entry.getValue(), type)); } - public void write(PacketBuffer buf) { + public void write(FriendlyByteBuf buf) { buf.writeByteArray(GSON.toJson(this.maps).getBytes(StandardCharsets.UTF_8)); } diff --git a/src/main/java/org/teacon/signin/network/TriggerFromMapPacket.java b/src/main/java/org/teacon/signin/network/TriggerFromMapPacket.java index 4c3e47d..8f35976 100644 --- a/src/main/java/org/teacon/signin/network/TriggerFromMapPacket.java +++ b/src/main/java/org/teacon/signin/network/TriggerFromMapPacket.java @@ -1,8 +1,8 @@ package org.teacon.signin.network; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkEvent; import org.teacon.signin.SignMeUp; import org.teacon.signin.data.GuideMap; @@ -14,7 +14,7 @@ public final class TriggerFromMapPacket { private final ResourceLocation trigger; // Used for deserialization - public TriggerFromMapPacket(PacketBuffer buf) { + public TriggerFromMapPacket(FriendlyByteBuf buf) { this.map = buf.readResourceLocation(); this.trigger = buf.readResourceLocation(); } @@ -24,7 +24,7 @@ public TriggerFromMapPacket(ResourceLocation map, ResourceLocation trigger) { this.trigger = trigger; } - public void write(PacketBuffer buf) { + public void write(FriendlyByteBuf buf) { buf.writeResourceLocation(this.map); buf.writeResourceLocation(this.trigger); } diff --git a/src/main/java/org/teacon/signin/network/TriggerFromWaypointPacket.java b/src/main/java/org/teacon/signin/network/TriggerFromWaypointPacket.java index c0ac124..b357479 100644 --- a/src/main/java/org/teacon/signin/network/TriggerFromWaypointPacket.java +++ b/src/main/java/org/teacon/signin/network/TriggerFromWaypointPacket.java @@ -1,8 +1,8 @@ package org.teacon.signin.network; -import net.minecraft.network.PacketBuffer; -import net.minecraft.util.ResourceLocation; -import net.minecraftforge.fml.network.NetworkEvent; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.network.NetworkEvent; import org.teacon.signin.SignMeUp; import org.teacon.signin.data.Waypoint; @@ -14,7 +14,7 @@ public final class TriggerFromWaypointPacket { private final ResourceLocation trigger; // Used for deserialization - public TriggerFromWaypointPacket(PacketBuffer buf) { + public TriggerFromWaypointPacket(FriendlyByteBuf buf) { this.waypoint = buf.readResourceLocation(); this.trigger = buf.readResourceLocation(); } @@ -24,7 +24,7 @@ public TriggerFromWaypointPacket(ResourceLocation waypoint, ResourceLocation tri this.trigger = trigger; } - public void write(PacketBuffer buf) { + public void write(FriendlyByteBuf buf) { buf.writeResourceLocation(this.waypoint); buf.writeResourceLocation(this.trigger); }