diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..ae2282e --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,39 @@ +# Automatically build the project and run any configured tests for every push +# and submitted pull request. This can help catch issues that only occur on +# certain platforms or Java versions, and provides a first line of defence +# against bad commits. + +name: build +on: [pull_request, push] + +jobs: + build: + strategy: + matrix: + # Use these Java versions + java: [ + 17, # Current Java LTS & minimum supported by Minecraft + ] + # and run on both Linux and Windows + os: [ubuntu-20.04, windows-2022] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v1 + - name: Setup JDK ${{ matrix.java }} + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + - name: Make Wrapper Executable + if: ${{ runner.os != 'Windows' }} + run: chmod +x ./gradlew + - name: Build Project + run: ./gradlew build + - name: Capture Build Artifacts + if: ${{ runner.os == 'Linux' && matrix.java == '17' }} + uses: actions/upload-artifact@v2 + with: + name: Artifacts + path: build/libs/ diff --git a/.gitignore b/.gitignore index 5b89b33..c611735 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # User-specific stuff .idea/ +/.vscode *.iml *.ipr diff --git a/README.md b/README.md index 0c87024..700fa8b 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ It works on both the **client and server**, and **does not** require the mod to ### Downloads -You can find downloads for DimThread on the [GitHub releases page](https://github.com/WearBlackAllDay/DimensionalThreading/releases). +You can find downloads for DimThread on the [GitHub releases page](https://github.com/MCTown/DimensionalThreading/releases). The Fabric API can be found on [Curseforge](https://www.curseforge.com/minecraft/mc-mods/fabric-api). ### Installing @@ -41,8 +41,6 @@ The mod will not crash if you do not have enough threads available, but it will ##### How is the compatibility with other mods? Compatibility with [JellySquids](https://github.com/jellysquid3) performance mods and [Carpet](https://github.com/gnembon/fabric-carpet) will be ensured and issues concerning them are accepted. If you plan on using a different mod compatibility cannot be guaranteed, since not every author writes their mod threadsafe. -##### What about older versions of Minecraft? -DimThread is written with 1.16 compatibility in mind, older versions are currently not considered. If you play on 1.12 you can use a similar project maintained by [2No2Name](https://github.com/2No2Name). --- diff --git a/build.gradle b/build.gradle index ada4b33..54dca12 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'fabric-loom' version '0.10-SNAPSHOT' + id 'fabric-loom' version '0.12-SNAPSHOT' id 'maven-publish' } @@ -11,35 +11,26 @@ version = project.mod_version group = project.maven_group repositories { - maven { - url "https://jitpack.io" - } // Add repositories to retrieve artifacts from in here. // You should only use this when depending on other mods because // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. // See https://docs.gradle.org/current/userguide/declaring_repositories.html // for more information about repositories. + maven { url "https://masa.dy.fi/maven" } } dependencies { - implementation "com.github.wearblackallday:JavaUtils:bd58640372" - include"com.github.wearblackallday:JavaUtils:bd58640372" - // To change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - - // Fabric API. This is technically optional, but you probably want it anyway. -// modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - modImplementation"net.fabricmc.fabric-api:fabric-game-rule-api-v1:${project.fabric_game_rule_v1_version}" - // PSA: Some older mods, compiled on Loom 0.2.1, might have outdated Maven POMs. - // You may need to force-disable transitiveness on them. + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + modRuntimeOnly "carpet:fabric-carpet:${project.minecraft_version}-${project.carpet_version}" } -minecraft { - accessWidener = file("src/main/resources/dimthread.accesswidener") - refmapName = "dimthread.refmap.json" +loom { + accessWidenerPath = file("src/main/resources/dimthread.accesswidener") + mixin.defaultRefmapName = "dimthread.refmap.json" } processResources { @@ -58,7 +49,7 @@ tasks.withType(JavaCompile).configureEach { it.options.encoding = "UTF-8" // Minecraft 1.17 (21w19a) upwards uses Java 16. - it.options.release = 16 + it.options.release = 17 } java { diff --git a/gradle.properties b/gradle.properties index 63a458c..25fab1f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,15 +2,16 @@ org.gradle.jvmargs=-Xmx1G # Fabric Properties # check these on https://modmuss50.me/fabric.html -minecraft_version=1.18 -yarn_mappings=1.18+build.1 -loader_version=0.12.8 +minecraft_version=1.18.2 +yarn_mappings=1.18.2+build.3 +loader_version=0.13.3 # Mod Properties -mod_version=1.2.6 +mod_version=1.2.6-1.18.2-sand-duper-fix.3 maven_group=wearblackallday archives_base_name=DimThread # Dependencies # check this on https://modmuss50.me/fabric.html -#fabric_version=0.44.0+1.18 -fabric_game_rule_v1_version=1.0.9+e77d3ea6cb +fabric_version=0.51.1+1.18.2 +carpet_version=1.4.69+v220331 +#fabric_game_rule_v1_version=1.0.9+e77d3ea6cb diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 62d4c05..41d9927 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 84d1f85..aa991fc 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-7.3.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index fbd7c51..1b6c787 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# 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. @@ -17,67 +17,101 @@ # ############################################################################## -## -## 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='"-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 @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 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 @@ -98,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 @@ -106,80 +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" = "true" -o "$msys" = "true" ] ; 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 +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # 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=`expr $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; +# * $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. +# -# 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" +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 a9f778a..ac1b06f 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -40,7 +40,7 @@ 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. @@ -54,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% @@ -64,21 +64,6 @@ 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 @@ -86,7 +71,7 @@ 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/wearblackallday/dimthread/DimThread.java b/src/main/java/wearblackallday/dimthread/DimThread.java index 5d79bb2..8aa0bd1 100644 --- a/src/main/java/wearblackallday/dimthread/DimThread.java +++ b/src/main/java/wearblackallday/dimthread/DimThread.java @@ -6,7 +6,7 @@ import wearblackallday.dimthread.init.ModGameRules; import wearblackallday.dimthread.thread.IMutableMainThread; import wearblackallday.dimthread.util.ServerManager; -import wearblackallday.util.ThreadPool; +import wearblackallday.dimthread.util.ThreadPool; public class DimThread implements ModInitializer { diff --git a/src/main/java/wearblackallday/dimthread/mixin/EntityMixin.java b/src/main/java/wearblackallday/dimthread/mixin/EntityMixin.java index 1203f8f..4138b49 100644 --- a/src/main/java/wearblackallday/dimthread/mixin/EntityMixin.java +++ b/src/main/java/wearblackallday/dimthread/mixin/EntityMixin.java @@ -1,34 +1,210 @@ package wearblackallday.dimthread.mixin; -import wearblackallday.dimthread.DimThread; +import net.minecraft.block.BlockState; import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityDimensions; +import net.minecraft.entity.EntityPose; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.server.MinecraftServer; import net.minecraft.server.world.ServerWorld; +import net.minecraft.state.property.Properties; +import net.minecraft.util.math.BlockPos; +import net.minecraft.util.math.Direction; +import net.minecraft.util.math.Vec3d; +import net.minecraft.world.BlockLocating; +import net.minecraft.world.Heightmap; +import net.minecraft.world.TeleportTarget; +import net.minecraft.world.World; +import net.minecraft.world.border.WorldBorder; +import net.minecraft.world.dimension.AreaHelper; +import net.minecraft.world.dimension.DimensionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.Redirect; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; +import wearblackallday.dimthread.DimThread; +import wearblackallday.dimthread.util.UncompletedTeleportTarget; + +import java.util.Optional; @Mixin(Entity.class) public abstract class EntityMixin { - @Shadow public abstract Entity moveToWorld(ServerWorld destination); + private NbtCompound nbtCachedForMoveToWorld; + + private UncompletedTeleportTarget uncompletedTeleportTargetForMoveToWorld; + @Shadow + protected abstract void removeFromDimension(); + + + @Shadow public abstract World getWorld(); + + @Shadow public abstract NbtCompound writeNbt(NbtCompound nbt); + + @Shadow public abstract @Nullable Entity moveToWorld(ServerWorld destination); + + @Shadow private int netherPortalCooldown; + + @Shadow protected BlockPos lastNetherPortalPosition; + + @Shadow public abstract boolean isRemoved(); + + @Shadow @Nullable public abstract MinecraftServer getServer(); + + @Shadow public World world; + + @Shadow public abstract double getX(); + + @Shadow public abstract double getY(); + + @Shadow public abstract double getZ(); + + @Shadow protected abstract Optional getPortalRect(ServerWorld destWorld, BlockPos destPos, boolean destIsNether, WorldBorder worldBorder); + + @Shadow protected abstract Vec3d positionInPortal(Direction.Axis portalAxis, BlockLocating.Rectangle portalRect); + + @Shadow public abstract EntityDimensions getDimensions(EntityPose pose); + + @Shadow public abstract EntityPose getPose(); + + @Shadow public abstract Vec3d getVelocity(); + + @Shadow public abstract float getYaw(); + + @Shadow public abstract float getPitch(); + + @Shadow protected abstract @Nullable TeleportTarget getTeleportTarget(ServerWorld destination); + + @Shadow protected abstract void unsetRemoved(); + + @Shadow public abstract void readNbt(NbtCompound nbt); + + @Shadow @Final private static Logger LOGGER; /** - * Schedules moving entities between dimensions to the server thread. Once all the world finish ticking, - * {@code moveToWorld()} is processed in a safe manner avoiding concurrent modification exceptions. + * Schedules moving entities between dimensions to the server thread. Once all + * the world finish ticking, {@code moveToWorld()} is processed in a safe manner + * avoiding concurrent modification exceptions. * - * For example, the entity list is not thread-safe and modifying it from multiple threads will cause - * a crash. Additionally, loading chunks from another thread will cause a deadlock in the server chunk manager. - * */ + * For example, the entity list is not thread-safe and modifying it from + * multiple threads will cause a crash. Additionally, loading chunks from + * another thread will cause a deadlock in the server chunk manager. + */ @Inject(method = "moveToWorld", at = @At("HEAD"), cancellable = true) - public void moveToWorld(ServerWorld destination, CallbackInfoReturnable ci) { - if(!DimThread.MANAGER.isActive(destination.getServer()))return; + public void onMoveToWorld(ServerWorld destination, CallbackInfoReturnable ci) { + if (!DimThread.MANAGER.isActive(destination.getServer())) + return; - if(DimThread.owns(Thread.currentThread())) { - destination.getServer().execute(() -> this.moveToWorld(destination)); + if (DimThread.owns(Thread.currentThread())) { + nbtCachedForMoveToWorld = writeNbt(new NbtCompound()); + uncompletedTeleportTargetForMoveToWorld = createTeleportTargetUncompleted(destination); + destination.getServer().execute( + () -> { + Entity entity = this.moveToWorld(destination); + if(entity == null) { + this.unsetRemoved(); + nbtCachedForMoveToWorld.putInt("PortalCooldown", this.netherPortalCooldown); + this.readNbt(nbtCachedForMoveToWorld); + this.uncompletedTeleportTargetForMoveToWorld = null; + this.nbtCachedForMoveToWorld = null; + this.world.spawnEntity((Entity) (Object) this);// if the teleporting failed, we need to add it back to the world + LOGGER.debug("Failed to teleport {}, return it to its previous world", this); + } + } + ); + this.removeFromDimension(); ci.setReturnValue(null); } } + /** + * Perform deep copy instead of clone() to fix the bug that handed item disappear while teleporting + */ + @Redirect(method = "moveToWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;copyFrom(Lnet/minecraft/entity/Entity;)V")) + private void onMoveToWorldCopyFrom(Entity instance, Entity original) { + if(DimThread.MANAGER.isActive(getServer())) { + NbtCompound nbtCompound = ((EntityMixin) (Object) original).nbtCachedForMoveToWorld; + nbtCompound.remove("Dimension"); + instance.readNbt(nbtCompound); + ((EntityMixin) (Object) instance).netherPortalCooldown = ((EntityMixin) (Object) original).netherPortalCooldown; + ((EntityMixin) (Object) instance).lastNetherPortalPosition = ((EntityMixin) (Object) original).lastNetherPortalPosition; + } else { + instance.copyFrom(original); + } + } + + /** + * We have to use the data we cached when moveToWorld is called + * It's getting modified later + */ + @Redirect(method = "moveToWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;getTeleportTarget(Lnet/minecraft/server/world/ServerWorld;)Lnet/minecraft/world/TeleportTarget;")) + private TeleportTarget onMoveToWorldGetTeleportTarget(@NotNull Entity instance, ServerWorld destination) { + EntityMixin ins = ((EntityMixin) (Object) instance); + if(DimThread.MANAGER.isActive(getServer())) { + return ins.uncompletedTeleportTargetForMoveToWorld == null ? null : ins.uncompletedTeleportTargetForMoveToWorld.complete(destination); + } else { + return ins.getTeleportTarget(destination); + } + } + + @Inject(method = "removeFromDimension", at = @At("HEAD"), cancellable = true) + private void onRemoveFromDimension(CallbackInfo ci) { + if(isRemoved()) { + ci.cancel(); + } + } + + /** + * We check this because when we call this method in getServer().execute(), the entity has already been removed + */ + @Redirect(method = "moveToWorld", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;isRemoved()Z")) + private boolean onMoveToWorldIsRemoved(Entity instance) { + return instance.isRemoved() && ((EntityMixin) (Object) instance).nbtCachedForMoveToWorld == null; + } + + /** + * take a snapshot of some values so that codes modified it later doesn't affect teleporting + */ + private UncompletedTeleportTarget createTeleportTargetUncompleted(ServerWorld dest) { + boolean isEndReturnPortal = world.getRegistryKey() == World.END && dest.getRegistryKey() == World.OVERWORLD; + boolean isEndPortal = dest.getRegistryKey() == World.END; + Vec3d velocity = getVelocity(); + float yaw = getYaw(), pitch = getPitch(); + if(!isEndPortal && !isEndReturnPortal) { + boolean isNetherPortal = dest.getRegistryKey() == World.NETHER; + boolean isNetherReturnPortal = world.getRegistryKey() == World.NETHER; + if(!isNetherPortal && !isNetherReturnPortal) { + return dest1 -> null; + } else { + WorldBorder border = dest.getWorldBorder(); + double scale = DimensionType.getCoordinateScaleFactor(world.getDimension(), dest.getDimension()); + BlockPos target = border.clamp(getX() * scale, getY(), getZ() * scale); + BlockState portalState = world.getBlockState(lastNetherPortalPosition); + Direction.Axis axis; + Vec3d vec3d; + EntityDimensions dimensions = getDimensions(getPose()); + if (portalState.contains(Properties.HORIZONTAL_AXIS)) { + axis = portalState.get(Properties.HORIZONTAL_AXIS); + BlockLocating.Rectangle rectangle = BlockLocating.getLargestRectangle(this.lastNetherPortalPosition, axis, 21, Direction.Axis.Y, 21, (blockPos) -> this.world.getBlockState(blockPos) == portalState); + vec3d = this.positionInPortal(axis, rectangle); + } else { + axis = Direction.Axis.X; + vec3d = new Vec3d(0.5, 0.0, 0.0); + } + return dest1 -> getPortalRect(dest1, target, isNetherPortal, border).map((rect) -> AreaHelper.getNetherTeleportTarget(dest1, rect, axis, vec3d, dimensions, velocity, yaw, pitch)).orElse(null); + } + } else { + return dest1 -> { + BlockPos target = isEndPortal ? ServerWorld.END_SPAWN_POS : dest1.getTopPosition(Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, dest1.getSpawnPos()); + return new TeleportTarget(new Vec3d(target.getX() + 0.5, target.getY(), target.getZ() + 0.5), velocity, yaw, pitch); + }; + } + } } diff --git a/src/main/java/wearblackallday/dimthread/mixin/MinecraftServerMixin.java b/src/main/java/wearblackallday/dimthread/mixin/MinecraftServerMixin.java index 7faeb4f..96c7fdb 100644 --- a/src/main/java/wearblackallday/dimthread/mixin/MinecraftServerMixin.java +++ b/src/main/java/wearblackallday/dimthread/mixin/MinecraftServerMixin.java @@ -13,7 +13,8 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import wearblackallday.dimthread.DimThread; import wearblackallday.dimthread.util.CrashInfo; -import wearblackallday.util.ThreadPool; +import wearblackallday.dimthread.util.ServerWorldAccessor; +import wearblackallday.dimthread.util.ThreadPool; import java.util.Collections; import java.util.Iterator; @@ -72,6 +73,7 @@ public void tickWorlds(BooleanSupplier shouldKeepTicking, CallbackInfo ci) { }); pool.awaitCompletion(); + getWorlds().forEach(world -> ((ServerWorldAccessor) world).dimthread_tickTime()); // Time ticking is not thread-safe, fix https://github.com/WearBlackAllDay/DimensionalThreading/issues/72 if(crash.get() != null) { crash.get().crash("Exception ticking world"); diff --git a/src/main/java/wearblackallday/dimthread/mixin/RedstoneWireBlockMixin.java b/src/main/java/wearblackallday/dimthread/mixin/RedstoneWireBlockMixin.java index 919c878..4965042 100644 --- a/src/main/java/wearblackallday/dimthread/mixin/RedstoneWireBlockMixin.java +++ b/src/main/java/wearblackallday/dimthread/mixin/RedstoneWireBlockMixin.java @@ -25,7 +25,7 @@ public abstract class RedstoneWireBlockMixin { @Shadow @Final public static IntProperty POWER; @Shadow @Final public static Map> DIRECTION_TO_WIRE_CONNECTION_PROPERTY; - @Shadow protected abstract BlockState method_27840(BlockView world, BlockState state, BlockPos pos); + @Shadow protected abstract BlockState getPlacementState(BlockView world, BlockState state, BlockPos pos); /** * {@code RedstoneWireBlock#wiresGivePower} is not thread-safe since it's a global flag. To ensure @@ -79,7 +79,7 @@ public int getWeakRedstonePower(BlockState state, BlockView world, BlockPos pos, int i = state.get(POWER); if(i == 0)return 0; - return direction != Direction.UP && !this.method_27840(world, state, pos) + return direction != Direction.UP && !this.getPlacementState(world, state, pos) .get(DIRECTION_TO_WIRE_CONNECTION_PROPERTY.get(direction.getOpposite())).isConnected() ? 0 : i; } diff --git a/src/main/java/wearblackallday/dimthread/mixin/ServerWorldMixin.java b/src/main/java/wearblackallday/dimthread/mixin/ServerWorldMixin.java new file mode 100644 index 0000000..34c2fa0 --- /dev/null +++ b/src/main/java/wearblackallday/dimthread/mixin/ServerWorldMixin.java @@ -0,0 +1,51 @@ +package wearblackallday.dimthread.mixin; + +import net.minecraft.server.world.ServerWorld; +import net.minecraft.util.profiler.Profiler; +import net.minecraft.util.registry.RegistryEntry; +import net.minecraft.util.registry.RegistryKey; +import net.minecraft.world.MutableWorldProperties; +import net.minecraft.world.World; +import net.minecraft.world.dimension.DimensionType; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; +import wearblackallday.dimthread.DimThread; +import wearblackallday.dimthread.util.ServerWorldAccessor; + +import java.util.function.Supplier; + +@Mixin(ServerWorld.class) +public abstract class ServerWorldMixin extends World implements ServerWorldAccessor { + protected ServerWorldMixin(MutableWorldProperties properties, RegistryKey registryRef, RegistryEntry registryEntry, Supplier profiler, boolean isClient, boolean debugWorld, long seed) { + super(properties, registryRef, registryEntry, profiler, isClient, debugWorld, seed); + } + + @Shadow protected abstract void tickTime(); + + boolean onMainThread = false; + boolean timeTickedOnWorldThread = false; + + /** + * Time ticking is not thread-safe. We cancel time ticking from the world thread. However, DimThread will tick time on the main thread + */ + @Inject(method = "tickTime", at = @At("HEAD"), cancellable = true) + private void preventTimeTicking(CallbackInfo ci) { + if (DimThread.MANAGER.isActive(getServer()) && !onMainThread) { + timeTickedOnWorldThread = true; + ci.cancel(); + } + } + + @Override + public void dimthread_tickTime() { + if (timeTickedOnWorldThread) { + onMainThread = true; + tickTime(); + onMainThread = false; + timeTickedOnWorldThread = false; + } + } +} diff --git a/src/main/java/wearblackallday/dimthread/util/ServerManager.java b/src/main/java/wearblackallday/dimthread/util/ServerManager.java index af399bd..2da7f2a 100644 --- a/src/main/java/wearblackallday/dimthread/util/ServerManager.java +++ b/src/main/java/wearblackallday/dimthread/util/ServerManager.java @@ -3,7 +3,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.GameRules; import wearblackallday.dimthread.init.ModGameRules; -import wearblackallday.util.ThreadPool; +import wearblackallday.dimthread.util.ThreadPool; import java.util.Collections; import java.util.ConcurrentModificationException; diff --git a/src/main/java/wearblackallday/dimthread/util/ServerWorldAccessor.java b/src/main/java/wearblackallday/dimthread/util/ServerWorldAccessor.java new file mode 100644 index 0000000..50fedfc --- /dev/null +++ b/src/main/java/wearblackallday/dimthread/util/ServerWorldAccessor.java @@ -0,0 +1,8 @@ +package wearblackallday.dimthread.util; + +/** + * Create this calass wo that we can call tickTime from ServerWorldMixin + */ +public interface ServerWorldAccessor { + void dimthread_tickTime(); +} diff --git a/src/main/java/wearblackallday/dimthread/util/ThreadPool.java b/src/main/java/wearblackallday/dimthread/util/ThreadPool.java new file mode 100644 index 0000000..97fb3c1 --- /dev/null +++ b/src/main/java/wearblackallday/dimthread/util/ThreadPool.java @@ -0,0 +1,169 @@ +package wearblackallday.dimthread.util; + +import java.util.Iterator; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.function.*; +import java.util.stream.DoubleStream; +import java.util.stream.IntStream; +import java.util.stream.LongStream; +import java.util.stream.Stream; + +public class ThreadPool { + private ThreadPoolExecutor executor; + private final int threadCount; + private final IntLatch activeCount = new IntLatch(); + + public ThreadPool() { + this(Runtime.getRuntime().availableProcessors()); + } + + public ThreadPool(int threadCount) { + this.threadCount = threadCount; + this.restart(); + } + + public int getThreadCount() { + return this.threadCount; + } + + public int getActiveCount() { + return this.activeCount.getCount(); + } + + public ThreadPoolExecutor getExecutor() { + return this.executor; + } + + public void execute(Runnable action) { + this.activeCount.increment(); + + this.executor.execute(() -> { + action.run(); + this.activeCount.decrement(); + }); + } + + public void execute(Iterator iterator, Consumer action) { + iterator.forEachRemaining(t -> this.execute(() -> action.accept(t))); + } + + public void execute(Iterable iterable, Consumer action) { + iterable.forEach(t -> this.execute(() -> action.accept(t))); + } + + public void execute(Stream stream, Consumer action) { + stream.forEach(t -> this.execute(() -> action.accept(t))); + } + + public void execute(IntStream stream, IntConsumer action) { + stream.forEach(t -> this.execute(() -> action.accept(t))); + } + + public void execute(LongStream stream, LongConsumer action) { + stream.forEach(t -> this.execute(() -> action.accept(t))); + } + + public void execute(DoubleStream stream, DoubleConsumer action) { + stream.forEach(t -> this.execute(() -> action.accept(t))); + } + + public void execute(T[] array, Consumer action) { + for(T t : array) this.execute(() -> action.accept(t)); + } + + public void execute(boolean[] array, Consumer action) { + for(boolean t : array) this.execute(() -> action.accept(t)); + } + + public void execute(byte[] array, Consumer action) { + for(byte t : array) this.execute(() -> action.accept(t)); + } + + public void execute(short[] array, Consumer action) { + for(short t : array) this.execute(() -> action.accept(t)); + } + + public void execute(int[] array, IntConsumer action) { + for(int t : array) this.execute(() -> action.accept(t)); + } + + public void execute(float[] array, Consumer action) { + for(float t : array) this.execute(() -> action.accept(t)); + } + + public void execute(long[] array, LongConsumer action) { + for(long t : array) this.execute(() -> action.accept(t)); + } + + public void execute(double[] array, DoubleConsumer action) { + for(double t : array) this.execute(() -> action.accept(t)); + } + + public void execute(char[] array, Consumer action) { + for(char t : array) this.execute(() -> action.accept(t)); + } + + public void awaitFreeThread() { + this.waitFor(value -> value < this.getThreadCount()); + } + + public void awaitCompletion() { + this.waitFor(value -> value == 0); + } + + public void waitFor(IntPredicate condition) { + try { + this.activeCount.waitUntil(condition); + } catch(InterruptedException e) { + e.printStackTrace(); + } + } + + public void restart() { + if(this.executor == null || this.executor.isShutdown()) { + this.executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(this.threadCount); + } + } + + public void shutdown() { + this.executor.shutdown(); + } + + public boolean isShutdown() { + return this.executor.isShutdown(); + } + + private static class IntLatch { + private CountDownLatch latch; + + private IntLatch() { + this(0); + } + + private IntLatch(int count) { + this.latch = new CountDownLatch(count); + } + + private synchronized int getCount() { + return (int)this.latch.getCount(); + } + + private synchronized void decrement() { + this.latch.countDown(); + this.notifyAll(); + } + + private synchronized void increment() { + this.latch = new CountDownLatch((int)this.latch.getCount() + 1); + this.notifyAll(); + } + + private synchronized void waitUntil(IntPredicate predicate) throws InterruptedException { + while(!predicate.test(this.getCount())) { + this.wait(); + } + } + } +} diff --git a/src/main/java/wearblackallday/dimthread/util/UncompletedTeleportTarget.java b/src/main/java/wearblackallday/dimthread/util/UncompletedTeleportTarget.java new file mode 100644 index 0000000..a8a50e7 --- /dev/null +++ b/src/main/java/wearblackallday/dimthread/util/UncompletedTeleportTarget.java @@ -0,0 +1,13 @@ +package wearblackallday.dimthread.util; + +import net.minecraft.server.world.ServerWorld; +import net.minecraft.world.TeleportTarget; +import org.jetbrains.annotations.Nullable; + +/** + * This is used for teleport target which is not completed right now, we are going to complete it in another thread + * For thread-unsafe operations + */ +public interface UncompletedTeleportTarget { + @Nullable TeleportTarget complete(ServerWorld dest); +} diff --git a/src/main/resources/dimthread.accesswidener b/src/main/resources/dimthread.accesswidener index 46ccd35..027fe2d 100644 --- a/src/main/resources/dimthread.accesswidener +++ b/src/main/resources/dimthread.accesswidener @@ -1,2 +1,2 @@ accessWidener v1 named -accessible class net/minecraft/server/world/ServerChunkManager$MainThreadExecutor \ No newline at end of file +accessible class net/minecraft/server/world/ServerChunkManager$MainThreadExecutor diff --git a/src/main/resources/dimthread.mixins.json b/src/main/resources/dimthread.mixins.json index dae46c2..8ec27e2 100644 --- a/src/main/resources/dimthread.mixins.json +++ b/src/main/resources/dimthread.mixins.json @@ -2,12 +2,13 @@ "required": true, "minVersion": "0.8", "package": "wearblackallday.dimthread.mixin", - "compatibilityLevel": "JAVA_16", + "compatibilityLevel": "JAVA_17", "mixins": [ "EntityMixin", "MinecraftServerMixin", "RedstoneWireBlockMixin", "ServerChunkManagerMixin", + "ServerWorldMixin", "WorldMixin" ], "client": [ diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index 2a2aae5..cb2f68e 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -17,7 +17,7 @@ ], "accessWidener": "dimthread.accesswidener", "depends": { - "fabricloader": ">=0.12.8", + "fabricloader": ">=0.13.3", "minecraft": ">=1.18" } }