diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index d0ad80af9..8291f089a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,11 +13,11 @@ jobs: with: fetch-depth: 0 - - name: Set up JDK 17 + - name: Set up JDK 21 uses: actions/setup-java@v3 with: distribution: 'temurin' - java-version: 17 + java-version: 21 - name: Grant execute permission for Gradlew run: chmod +x gradlew diff --git a/build.gradle b/build.gradle index 6c615ab72..ebdbeef0c 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ import net.fabricmc.loom.task.RemapJarTask plugins { - id 'dev.architectury.loom' version '1.4.380' + id 'dev.architectury.loom' version '1.6.395' // This dependency is only used to determine the state of the Git working tree so that build artifacts can be // more easily identified. TODO: Lazily load GrGit via a service only when builds are performed. @@ -63,7 +63,7 @@ jar { loom { runs { - client { + configureEach { mods { radium { sourceSet sourceSets.main @@ -88,7 +88,10 @@ repositories { dependencies { //to change the versions see the gradle.properties file minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" + mappings loom.layered { + it.mappings("net.fabricmc:yarn:${project.yarn_mappings}:v2") + it.mappings("dev.architectury:yarn-mappings-patch-neoforge:${project.yarn_patch}") + } neoForge "net.neoforged:neoforge:${project.loader_version}" //modCompileOnly "dev.su5ed.sinytra.fabric-api:fabric-transfer-api-v1:${project.fabric_version}" // Ye diff --git a/components/mixin-config-plugin/gradle/wrapper/gradle-wrapper.properties b/components/mixin-config-plugin/gradle/wrapper/gradle-wrapper.properties index e750102e0..17655d0ef 100644 --- a/components/mixin-config-plugin/gradle/wrapper/gradle-wrapper.properties +++ b/components/mixin-config-plugin/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-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradle.properties b/gradle.properties index 64ad39dc0..ae72d7712 100644 --- a/gradle.properties +++ b/gradle.properties @@ -3,13 +3,14 @@ org.gradle.jvmargs=-Xmx3G # Fabric Properties # check these on https://modmuss50.me/fabric.html -minecraft_version=1.20.4 -yarn_mappings=1.20.4+build.1 -loader_version=20.4.182 +minecraft_version=1.20.5 +yarn_mappings=1.20.5+build.1 +yarn_patch=1.20.5+build.3 +loader_version=20.5.16-beta #Fabric api fabric_version=3.3.0+d55c00c777 # Mod Properties -mod_version=0.12.2 +mod_version=0.12.5 maven_group=me.jellysquid.mods loom.platform=neoforge diff --git a/gradle/fabric.gradle b/gradle/fabric.gradle index 4e81ba577..ce3a93fd5 100644 --- a/gradle/fabric.gradle +++ b/gradle/fabric.gradle @@ -3,14 +3,7 @@ apply plugin: "dev.architectury.loom" processResources { inputs.property "version", project.version - filesMatching("META-INF/mods.toml") { + filesMatching("META-INF/neoforge.mods.toml") { expand "version": project.version } } - -dependencies { - //to change the versions see the gradle.properties file - minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" - neoForge "net.neoforged:neoforge:${project.loader_version}" -} \ No newline at end of file diff --git a/gradle/java.gradle b/gradle/java.gradle index 26e31af1b..3a0d9d1ba 100644 --- a/gradle/java.gradle +++ b/gradle/java.gradle @@ -1,5 +1,5 @@ -sourceCompatibility = JavaVersion.VERSION_17 -targetCompatibility = JavaVersion.VERSION_17 +sourceCompatibility = JavaVersion.VERSION_21 +targetCompatibility = JavaVersion.VERSION_21 // ensure that the encoding is set to UTF-8, no matter what the system default is // this fixes some edge cases with special characters not displaying correctly @@ -10,4 +10,4 @@ tasks.withType(JavaCompile) { jar { from "${rootProject.projectDir}/LICENSE.txt" -} \ No newline at end of file +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180f2..d64cd4917 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 db9a6b825..a80b22ce5 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c78733..1aa94a426 100755 --- a/gradlew +++ b/gradlew @@ -55,7 +55,7 @@ # 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 +# https://github.com/gradle/gradle/blob/HEAD/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/. @@ -80,13 +80,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 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"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -133,22 +131,29 @@ location of your Java installation." fi else 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. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then done 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. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ @@ -205,6 +214,12 @@ set -- \ org.gradle.wrapper.GradleWrapperMain \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32c..25da30dbd 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +41,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -56,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 goto fail @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/lithium-mixin-config.md b/lithium-mixin-config.md index 8802882ca..42ff14899 100644 --- a/lithium-mixin-config.md +++ b/lithium-mixin-config.md @@ -20,22 +20,6 @@ mixin.gen.biome_noise_cache=false (default: `true`) Mob AI optimizations -### `mixin.ai.nearby_entity_tracking` -(default: `false`) -Event-based system for tracking nearby entities. - -Requirements: -- `mixin.util.entity_section_position=true` -- `mixin.util.accessors=true` - -### `mixin.ai.nearby_entity_tracking.goals` -(default: `true`) -A number of AI goals which query for nearby entities in the world every tick will use the event-based -system for tracking nearby entities. In other words, instead of entities constantly polling to see if -other entities are nearby, they will instead be notified only occasionally when such an entity enters -their range. - - ### `mixin.ai.pathing` (default: `true`) A faster code path is used for determining what kind of path-finding node type is associated with a @@ -254,8 +238,7 @@ Various entity collision optimizations (default: `true`) Skips being pushed by fluids when the nearby chunk sections do not contain this fluid Requirements: -- `mixin.util.block_tracking=true` -- `mixin.experimental.entity.block_caching.fluid_pushing=false` +- `mixin.util.block_tracking=true` ### `mixin.entity.collisions.intersection` (default: `true`) @@ -276,18 +259,6 @@ In chunks with many mobs in ladders a separate list of pushable entities for cra Requirements: - `mixin.chunk.entity_class_groups=true` -### `mixin.entity.data_tracker` -(default: `true`) -Various entity data tracker optimizations - -### `mixin.entity.data_tracker.no_locks` -(default: `true`) -Remove unnecessary locking when accessing the data tracker - -### `mixin.entity.data_tracker.use_arrays` -(default: `true`) -Data trackers use a custom optimized entry map - ### `mixin.entity.fast_elytra_check` (default: `true`) Skip repeatedly writing to the data tracker that an entity is not flying @@ -304,10 +275,6 @@ Skip checking whether an entity is inside powder snow for movement speed slowdow (default: `true`) Access entities faster when accessing a relatively small number of entity sections -### `mixin.entity.hopper_minecart` -(default: `true`) -Hopper minecarts search for item entities faster by combining multiple item entity searches. Also eliminates duplicated item entity pickup attempts - ### `mixin.entity.inactive_navigations` (default: `true`) Block updates skip notifying mobs that won't react to the block update anyways @@ -354,12 +321,6 @@ Requirements: (default: `true`) Skip searching for fire or lava in the burn time countdown logic when they are not on fire and the result does not make a difference. Also use the block listening system to cache whether the entity is touching fire or lava. -### `mixin.experimental.entity.block_caching.fluid_pushing` -(default: `true`) -Use the block listening system to cache entity fluid interaction when not touching fluid currents. -Requirements: -- `mixin.util.block_tracking.block_listening=true` - ### `mixin.experimental.entity.block_caching.suffocation` (default: `true`) Use the block listening system to cache the entity suffocation check. diff --git a/src/main/java/me/jellysquid/mods/lithium/common/ai/MemoryModificationCounter.java b/src/main/java/me/jellysquid/mods/lithium/common/ai/MemoryModificationCounter.java index 2521d4696..3d797616f 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/ai/MemoryModificationCounter.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/ai/MemoryModificationCounter.java @@ -2,5 +2,5 @@ public interface MemoryModificationCounter { - long getModCount(); + long lithium$getModCount(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/BlockStatePathingCache.java b/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/BlockStatePathingCache.java index c11bbfe8b..81b88b98c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/BlockStatePathingCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/BlockStatePathingCache.java @@ -3,9 +3,9 @@ import net.minecraft.entity.ai.pathing.PathNodeType; public interface BlockStatePathingCache { - PathNodeType getPathNodeType(); + PathNodeType lithium$getPathNodeType(); - PathNodeType getNeighborPathNodeType(); + PathNodeType lithium$getNeighborPathNodeType(); void lithium$initPathCache(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/PathNodeCache.java b/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/PathNodeCache.java index 1c915999f..e1d56bfd6 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/PathNodeCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/ai/pathing/PathNodeCache.java @@ -5,9 +5,11 @@ import me.jellysquid.mods.lithium.common.util.Pos; import me.jellysquid.mods.lithium.common.world.ChunkView; import me.jellysquid.mods.lithium.common.world.WorldHelper; +import me.jellysquid.mods.lithium.mixin.ai.pathing.PathContextAccessor; import net.minecraft.block.AbstractBlock; import net.minecraft.block.BlockState; import net.minecraft.entity.ai.pathing.LandPathNodeMaker; +import net.minecraft.entity.ai.pathing.PathContext; import net.minecraft.entity.ai.pathing.PathNodeType; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; @@ -21,15 +23,15 @@ private static boolean isChunkSectionDangerousNeighbor(ChunkSection section) { } public static PathNodeType getPathNodeType(BlockState state) { - return ((BlockStatePathingCache) state).getPathNodeType(); + return ((BlockStatePathingCache) state).lithium$getPathNodeType(); } public static PathNodeType getNeighborPathNodeType(AbstractBlock.AbstractBlockState state) { - return ((BlockStatePathingCache) state).getNeighborPathNodeType(); + return ((BlockStatePathingCache) state).lithium$getNeighborPathNodeType(); } /** - * Returns whether or not a chunk section is free of dangers. This makes use of a caching layer to greatly + * Returns whether a chunk section is free of dangers. This makes use of a caching layer to greatly * accelerate neighbor danger checks when path-finding. * * @param section The chunk section to test for dangers @@ -43,28 +45,26 @@ public static boolean isSectionSafeAsNeighbor(ChunkSection section) { } if (BlockStateFlags.ENABLED) { - return !((BlockCountingSection) section).mayContainAny(BlockStateFlags.PATH_NOT_OPEN); + return !((BlockCountingSection) section).lithium$mayContainAny(BlockStateFlags.PATH_NOT_OPEN); } return !isChunkSectionDangerousNeighbor(section); } - public static PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mutable pos, PathNodeType type) { - int x = pos.getX(); - int y = pos.getY(); - int z = pos.getZ(); + public static PathNodeType getNodeTypeFromNeighbors(PathContext context, int x, int y, int z, PathNodeType fallback) { + BlockView world = context.getWorld(); ChunkSection section = null; // Check that all the block's neighbors are within the same chunk column. If so, we can isolate all our block // reads to just one chunk and avoid hits against the server chunk manager. - if (world instanceof ChunkView chunkView && WorldHelper.areNeighborsWithinSameChunkSection(pos)) { + if (world instanceof ChunkView chunkView && WorldHelper.areNeighborsWithinSameChunkSection(x, y, z)) { // If the y-coordinate is within bounds, we can cache the chunk section. Otherwise, the if statement to check // if the cached chunk section was initialized will early-exit. if (!world.isOutOfHeightLimit(y)) { - Chunk chunk = chunkView.getLoadedChunk(Pos.ChunkCoord.fromBlockCoord(x), Pos.ChunkCoord.fromBlockCoord(z)); + Chunk chunk = chunkView.lithium$getLoadedChunk(Pos.ChunkCoord.fromBlockCoord(x), Pos.ChunkCoord.fromBlockCoord(z)); - // If the chunk is absent, the cached section above will remain null, as there is no chunk section anyways. + // If the chunk is absent, the cached section above will remain null, as there is no chunk section anyway. // An empty chunk or section will never pose any danger sources, which will be caught later. if (chunk != null) { section = chunk.getSectionArray()[Pos.SectionYIndex.fromBlockCoord(world, y)]; @@ -75,7 +75,7 @@ public static PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mu // section is empty or contains any dangerous blocks within the palette. If not, we can assume any checks // against this chunk section will always fail, allowing us to fast-exit. if (section == null || PathNodeCache.isSectionSafeAsNeighbor(section)) { - return type; + return fallback; //TODO side effects of vanilla's path node caching } } @@ -103,19 +103,19 @@ public static PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mu if (section != null) { state = section.getBlockState(adjX & 15, adjY & 15, adjZ & 15); } else { - state = world.getBlockState(pos.set(adjX, adjY, adjZ)); + BlockPos.Mutable pos = ((PathContextAccessor) context).getLastNodePos().set(adjX, adjY, adjZ); + state = world.getBlockState(pos); } - // Ensure that the block isn't air first to avoid expensive hash table accesses if (state.isAir()) { continue; } PathNodeType neighborType = PathNodeCache.getNeighborPathNodeType(state); - if (neighborType == null) { //Here null means that no path node type is cached (uninitalized or dynamic) + if (neighborType == null) { //Here null means that no path node type is cached (uninitialized or dynamic) //Passing null as previous node type to the method signals to other lithium mixins that we only want the neighbor behavior of this block and not its neighbors - neighborType = LandPathNodeMaker.getNodeTypeFromNeighbors(world, pos, null); + neighborType = LandPathNodeMaker.getNodeTypeFromNeighbors(context, adjX + 1, adjY + 1, adjZ + 1, null); //Here null means that the path node type is not changed by the block! if (neighborType == null) { neighborType = PathNodeType.OPEN; @@ -128,7 +128,7 @@ public static PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mu } } - return type; + return fallback; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/ai/raid/OminousBannerCache.java b/src/main/java/me/jellysquid/mods/lithium/common/ai/raid/OminousBannerCache.java new file mode 100644 index 000000000..ed9fadcf0 --- /dev/null +++ b/src/main/java/me/jellysquid/mods/lithium/common/ai/raid/OminousBannerCache.java @@ -0,0 +1,7 @@ +package me.jellysquid.mods.lithium.common.ai.raid; + +import net.minecraft.item.ItemStack; + +public interface OminousBannerCache { + ItemStack lithium$getCachedOminousBanner(); +} diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/BlockCountingSection.java b/src/main/java/me/jellysquid/mods/lithium/common/block/BlockCountingSection.java index c4fb71e88..fdb63fbbb 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/BlockCountingSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/BlockCountingSection.java @@ -1,5 +1,9 @@ package me.jellysquid.mods.lithium.common.block; +import net.minecraft.block.BlockState; + public interface BlockCountingSection { - boolean mayContainAny(TrackedBlockStatePredicate trackedBlockStatePredicate); + boolean lithium$mayContainAny(TrackedBlockStatePredicate trackedBlockStatePredicate); + + void lithium$trackBlockStateChange(BlockState newState, BlockState oldState); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/BlockListeningSection.java b/src/main/java/me/jellysquid/mods/lithium/common/block/BlockListeningSection.java index 8bc5aaa33..5fc29f3c0 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/BlockListeningSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/BlockListeningSection.java @@ -1,9 +1,13 @@ package me.jellysquid.mods.lithium.common.block; import me.jellysquid.mods.lithium.common.entity.block_tracking.SectionedBlockChangeTracker; +import net.minecraft.util.math.ChunkSectionPos; public interface BlockListeningSection { - void addToCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker); - void removeFromCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker); + void lithium$addToCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker); + + void lithium$removeFromCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker); + + void lithium$invalidateListeningSection(ChunkSectionPos sectionPos); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/SleepingBlockEntity.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/SleepingBlockEntity.java index b167971e4..431e9ce08 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/SleepingBlockEntity.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/SleepingBlockEntity.java @@ -24,50 +24,50 @@ public String getName() { } }; - WrappedBlockEntityTickInvokerAccessor getTickWrapper(); + WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper(); - void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper); + void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper); - BlockEntityTickInvoker getSleepingTicker(); + BlockEntityTickInvoker lithium$getSleepingTicker(); - void setSleepingTicker(BlockEntityTickInvoker sleepingTicker); + void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker); - default boolean startSleeping() { + default boolean lithium$startSleeping() { if (this.isSleeping()) { return false; } - WrappedBlockEntityTickInvokerAccessor tickWrapper = this.getTickWrapper(); + WrappedBlockEntityTickInvokerAccessor tickWrapper = this.lithium$getTickWrapper(); if (tickWrapper == null) { return false; } - this.setSleepingTicker(tickWrapper.getWrapped()); + this.lithium$setSleepingTicker(tickWrapper.getWrapped()); tickWrapper.callSetWrapped(SleepingBlockEntity.SLEEPING_BLOCK_ENTITY_TICKER); return true; } default void sleepOnlyCurrentTick() { - BlockEntityTickInvoker sleepingTicker = this.getSleepingTicker(); - WrappedBlockEntityTickInvokerAccessor tickWrapper = this.getTickWrapper(); + BlockEntityTickInvoker sleepingTicker = this.lithium$getSleepingTicker(); + WrappedBlockEntityTickInvokerAccessor tickWrapper = this.lithium$getTickWrapper(); if (sleepingTicker == null) { sleepingTicker = tickWrapper.getWrapped(); } World world = ((BlockEntity) this).getWorld(); tickWrapper.callSetWrapped(new SleepUntilTimeBlockEntityTickInvoker((BlockEntity) this, world.getTime() + 1, sleepingTicker)); - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } default void wakeUpNow() { - BlockEntityTickInvoker sleepingTicker = this.getSleepingTicker(); + BlockEntityTickInvoker sleepingTicker = this.lithium$getSleepingTicker(); if (sleepingTicker == null) { return; } this.setTicker(sleepingTicker); - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } default void setTicker(BlockEntityTickInvoker delegate) { - WrappedBlockEntityTickInvokerAccessor tickWrapper = this.getTickWrapper(); + WrappedBlockEntityTickInvokerAccessor tickWrapper = this.lithium$getTickWrapper(); if (tickWrapper == null) { return; } @@ -75,6 +75,6 @@ default void setTicker(BlockEntityTickInvoker delegate) { } default boolean isSleeping() { - return this.getSleepingTicker() != null; + return this.lithium$getSleepingTicker() != null; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeEmitter.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeEmitter.java index d10b48ed3..e0e35c747 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeEmitter.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeEmitter.java @@ -10,21 +10,21 @@ * The forwarding methods below are helpers, it is not recommended to call them from outside InventoryChangeTracker.java */ public interface InventoryChangeEmitter { - void emitStackListReplaced(); + void lithium$emitStackListReplaced(); - void emitRemoved(); + void lithium$emitRemoved(); - void emitContentModified(); + void lithium$emitContentModified(); - void emitFirstComparatorAdded(); + void lithium$emitFirstComparatorAdded(); - void forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker); + void lithium$forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker); - void forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener); + void lithium$forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener); - void stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener); + void lithium$stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener); default void emitCallbackReplaced() { - this.emitRemoved(); + this.lithium$emitRemoved(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeListener.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeListener.java index 5b89b0602..2b3400c2a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeListener.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeListener.java @@ -4,12 +4,12 @@ public interface InventoryChangeListener { default void handleStackListReplaced(Inventory inventory) { - this.handleInventoryRemoved(inventory); + this.lithium$handleInventoryRemoved(inventory); } - void handleInventoryContentModified(Inventory inventory); + void lithium$handleInventoryContentModified(Inventory inventory); - void handleInventoryRemoved(Inventory inventory); + void lithium$handleInventoryRemoved(Inventory inventory); - boolean handleComparatorAdded(Inventory inventory); + boolean lithium$handleComparatorAdded(Inventory inventory); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeTracker.java index e438335a2..ce6d1476d 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_change_tracking/InventoryChangeTracker.java @@ -4,14 +4,14 @@ public interface InventoryChangeTracker extends InventoryChangeEmitter { default void listenForContentChangesOnce(LithiumStackList stackList, InventoryChangeListener inventoryChangeListener) { - this.forwardContentChangeOnce(inventoryChangeListener, stackList, this); + this.lithium$forwardContentChangeOnce(inventoryChangeListener, stackList, this); } default void listenForMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { - this.forwardMajorInventoryChanges(inventoryChangeListener); + this.lithium$forwardMajorInventoryChanges(inventoryChangeListener); } default void stopListenForMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { - this.stopForwardingMajorInventoryChanges(inventoryChangeListener); + this.lithium$stopForwardingMajorInventoryChanges(inventoryChangeListener); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracker.java index b0e97df0d..d69dbcb59 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracker.java @@ -3,7 +3,7 @@ import net.minecraft.util.math.Direction; public interface ComparatorTracker { - void onComparatorAdded(Direction direction, int offset); + void lithium$onComparatorAdded(Direction direction, int offset); - boolean hasAnyComparatorNearby(); + boolean lithium$hasAnyComparatorNearby(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracking.java b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracking.java index 760bfd424..e4ca4bd6d 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracking.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/block/entity/inventory_comparator_tracking/ComparatorTracking.java @@ -21,9 +21,9 @@ public static void notifyNearbyBlockEntitiesAboutNewComparator(World world, Bloc searchPos.move(searchDirection, searchOffset); BlockState blockState = world.getBlockState(searchPos); if (blockState.getBlock() instanceof BlockEntityProvider) { - BlockEntity blockEntity = ((BlockEntityGetter) world).getLoadedExistingBlockEntity(searchPos); + BlockEntity blockEntity = ((BlockEntityGetter) world).lithium$getLoadedExistingBlockEntity(searchPos); if (blockEntity instanceof Inventory && blockEntity instanceof ComparatorTracker comparatorTracker) { - comparatorTracker.onComparatorAdded(searchDirection, searchOffset); + comparatorTracker.lithium$onComparatorAdded(searchDirection, searchOffset); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/client/ClientWorldAccessor.java b/src/main/java/me/jellysquid/mods/lithium/common/client/ClientWorldAccessor.java index 12cd1126b..1fde2fe97 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/client/ClientWorldAccessor.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/client/ClientWorldAccessor.java @@ -4,5 +4,5 @@ import net.minecraft.entity.Entity; public interface ClientWorldAccessor { - ClientEntityManager getEntityManager(); + ClientEntityManager lithium$getEntityManager(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/EquipmentEntity.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/EquipmentEntity.java index f46d59a44..8b4dd5d2a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/EquipmentEntity.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/EquipmentEntity.java @@ -1,7 +1,7 @@ package me.jellysquid.mods.lithium.common.entity; public interface EquipmentEntity { - default void lithiumOnEquipmentChanged() { + default void lithium$OnEquipmentChanged() { } interface EquipmentTrackingEntity { diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/NavigatingEntity.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/NavigatingEntity.java index b204826a9..649e733bf 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/NavigatingEntity.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/NavigatingEntity.java @@ -3,12 +3,12 @@ import net.minecraft.entity.ai.pathing.EntityNavigation; public interface NavigatingEntity { - boolean isRegisteredToWorld(); + boolean lithium$isRegisteredToWorld(); - void setRegisteredToWorld(EntityNavigation navigation); + void lithium$setRegisteredToWorld(EntityNavigation navigation); - EntityNavigation getRegisteredNavigation(); + EntityNavigation lithium$getRegisteredNavigation(); - void updateNavigationRegistration(); + void lithium$updateNavigationRegistration(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/PositionedEntityTrackingSection.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/PositionedEntityTrackingSection.java index b985b8144..615b748fc 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/PositionedEntityTrackingSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/PositionedEntityTrackingSection.java @@ -1,7 +1,7 @@ package me.jellysquid.mods.lithium.common.entity; public interface PositionedEntityTrackingSection { - void setPos(long chunkSectionPos); + void lithium$setPos(long chunkSectionPos); - long getPos(); + long lithium$getPos(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCache.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCache.java index a3e701e52..55487ca25 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCache.java @@ -1,11 +1,11 @@ package me.jellysquid.mods.lithium.common.entity.block_tracking; -import it.unimi.dsi.fastutil.objects.Reference2DoubleArrayMap; +import it.unimi.dsi.fastutil.objects.Object2DoubleArrayMap; +import it.unimi.dsi.fastutil.objects.Object2DoubleMap; import me.jellysquid.mods.lithium.common.block.BlockStateFlags; import net.minecraft.entity.Entity; -import net.minecraft.fluid.Fluid; -import net.minecraft.registry.tag.TagKey; import net.minecraft.util.math.Box; +import net.neoforged.neoforge.fluids.FluidType; public final class BlockCache { // To avoid slowing down setblock operations, only start caching after 3 Seconds = 60 gameticks with N accesses per tick @@ -24,7 +24,7 @@ public final class BlockCache { //0 if not suffocating. 1 if touching suffocating. -1 if not cached private byte cachedIsSuffocating; //Touched fluid's height IF fluid pushing is 0. Touched fluid height is 0 when not touching that fluid. Not in collection: No cached value (uninitialized OR fluid pushing is not 0) - private final Reference2DoubleArrayMap> fluidType2FluidHeightMap; + private final Object2DoubleArrayMap fluidType2FluidHeightMap; //Future: maybe cache last failed movement vector @@ -32,7 +32,7 @@ public BlockCache() { this.tracker = null; this.trackedPos = null; this.initDelay = 0; - this.fluidType2FluidHeightMap = new Reference2DoubleArrayMap<>(2); + this.fluidType2FluidHeightMap = new Object2DoubleArrayMap<>(2); } public boolean isTracking() { @@ -97,17 +97,25 @@ public void setCanSkipBlockTouching(boolean value) { this.canSkipBlockTouching = value; } - public double getStationaryFluidHeightOrDefault(TagKey fluid, double defaultValue) { + public double getStationaryFluidHeightOrDefault(FluidType fluid, double defaultValue) { if (this.isTracking()) { return this.fluidType2FluidHeightMap.getOrDefault(fluid, defaultValue); } return defaultValue; } - public void setCachedFluidHeight(TagKey fluid, double fluidHeight) { + public void setCachedFluidHeight(FluidType fluid, double fluidHeight) { this.fluidType2FluidHeightMap.put(fluid, fluidHeight); } + public Object2DoubleMap getCachedFluidHeightMap() { + if(this.isTracking()) { + return this.fluidType2FluidHeightMap; + } else { + return null; + } + } + public byte getIsTouchingFireLava() { if (this.isTracking()) { return this.cachedTouchingFireLava; diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCacheProvider.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCacheProvider.java index d36e609dd..b3f94f268 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCacheProvider.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/BlockCacheProvider.java @@ -3,10 +3,10 @@ import net.minecraft.entity.Entity; public interface BlockCacheProvider { - BlockCache getBlockCache(); + BlockCache lithium$getBlockCache(); default BlockCache getUpdatedBlockCache(Entity entity) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); bc.updateCache(entity); return bc; } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/ChunkSectionChangeCallback.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/ChunkSectionChangeCallback.java index 1d3773d85..7bc76d72b 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/ChunkSectionChangeCallback.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/ChunkSectionChangeCallback.java @@ -3,6 +3,7 @@ import me.jellysquid.mods.lithium.common.block.BlockListeningSection; import me.jellysquid.mods.lithium.common.block.BlockStateFlags; import me.jellysquid.mods.lithium.common.block.ListeningBlockStatePredicate; +import net.minecraft.util.math.ChunkSectionPos; import java.util.ArrayList; @@ -23,7 +24,7 @@ public short onBlockChange(int flagIndex, BlockListeningSection section) { for (int i = 0; i < sectionedBlockChangeTrackers.size(); i++) { sectionedBlockChangeTrackers.get(i).setChanged(section); } - this.listeningMask &= ~(1 << flagIndex); + this.listeningMask &= (short) ~(1 << flagIndex); return this.listeningMask; } @@ -36,7 +37,7 @@ public short addTracker(SectionedBlockChangeTracker tracker, ListeningBlockState } sectionedBlockChangeTrackers.add(tracker); - this.listeningMask |= (1 << blockGroupIndex); + this.listeningMask |= (short) (1 << blockGroupIndex); return this.listeningMask; } @@ -46,9 +47,23 @@ public short removeTracker(SectionedBlockChangeTracker tracker, ListeningBlockSt if (sectionedBlockChangeTrackers != null) { sectionedBlockChangeTrackers.remove(tracker); if (sectionedBlockChangeTrackers.isEmpty()) { - this.listeningMask &= ~(1 << blockGroup.getIndex()); + this.listeningMask &= (short) ~(1 << blockGroup.getIndex()); } } return this.listeningMask; } + + public void onChunkSectionInvalidated(ChunkSectionPos sectionPos) { + for (int flagIndex = 0; flagIndex < this.trackers.length; flagIndex++) { + ArrayList sectionedBlockChangeTrackers = this.trackers[flagIndex]; + this.trackers[flagIndex] = null; + if (sectionedBlockChangeTrackers != null) { + //noinspection ForLoopReplaceableByForEach + for (int i = 0; i < sectionedBlockChangeTrackers.size(); i++) { + sectionedBlockChangeTrackers.get(i).onChunkSectionInvalidated(sectionPos); + } + } + } + this.listeningMask = 0; + } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/SectionedBlockChangeTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/SectionedBlockChangeTracker.java index 89500c980..5115da0d4 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/SectionedBlockChangeTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/block_tracking/SectionedBlockChangeTracker.java @@ -42,7 +42,7 @@ public static SectionedBlockChangeTracker registerAt(World world, Box entityBoun WorldSectionBox worldSectionBox = WorldSectionBox.relevantExpandedBlocksBox(world, entityBoundingBox); SectionedBlockChangeTracker tracker = new SectionedBlockChangeTracker(worldSectionBox, blockGroup); //noinspection unchecked - tracker = ((LithiumInternerWrapper)world).getCanonical(tracker); + tracker = ((LithiumInternerWrapper) world).lithium$getCanonical(tracker); tracker.register(); return tracker; @@ -73,10 +73,12 @@ public void register() { ChunkSection section = sectionArray[Pos.SectionYIndex.fromSectionCoord(trackedSections.world(), y)]; BlockListeningSection blockListeningSection = (BlockListeningSection) section; - blockListeningSection.addToCallback(this.blockGroup, this); + blockListeningSection.lithium$addToCallback(this.blockGroup, this); } } } + this.isListeningToAll = (this.sectionsNotListeningTo == null || this.sectionsNotListeningTo.isEmpty()) + && (this.sectionsUnsubscribed == null || this.sectionsUnsubscribed.isEmpty()); this.setChanged(this.getWorldTime()); } this.timesRegistered++; @@ -103,13 +105,13 @@ public void unregister() { ChunkSection section = sectionArray[Pos.SectionYIndex.fromSectionCoord(world, y)]; BlockListeningSection blockListeningSection = (BlockListeningSection) section; - blockListeningSection.removeFromCallback(this.blockGroup, this); + blockListeningSection.lithium$removeFromCallback(this.blockGroup, this); } } } this.sectionsNotListeningTo = null; //noinspection unchecked - ((LithiumInternerWrapper)world).deleteCanonical(this); + ((LithiumInternerWrapper) world).lithium$deleteCanonical(this); } public void listenToAllSections() { @@ -128,7 +130,7 @@ public void listenToAllSections() { } ChunkSection section = chunk.getSectionArray()[Pos.SectionYIndex.fromSectionCoord(this.trackedWorldSections.world(), chunkSectionPos.getY())]; BlockListeningSection blockListeningSection = (BlockListeningSection) section; - blockListeningSection.addToCallback(this.blockGroup, this); + blockListeningSection.lithium$addToCallback(this.blockGroup, this); } } if (this.sectionsUnsubscribed != null) { @@ -136,7 +138,7 @@ public void listenToAllSections() { for (int i = unsubscribed.size() - 1; i >= 0; i--) { changed = true; BlockListeningSection blockListeningSection = unsubscribed.remove(i); - blockListeningSection.addToCallback(this.blockGroup, this); + blockListeningSection.lithium$addToCallback(this.blockGroup, this); } } this.isListeningToAll = true; @@ -192,4 +194,13 @@ public boolean equals(Object obj) { public int hashCode() { return this.getClass().hashCode() ^ this.trackedWorldSections.hashCode() ^ this.blockGroup.hashCode(); } + + public void onChunkSectionInvalidated(ChunkSectionPos sectionPos) { + if (this.sectionsNotListeningTo == null) { + this.sectionsNotListeningTo = new ArrayList<>(); + } + this.sectionsNotListeningTo.add(sectionPos); + this.setChanged(this.getWorldTime()); + this.isListeningToAll = false; + } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement/ChunkAwareBlockCollisionSweeper.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement/ChunkAwareBlockCollisionSweeper.java index a9a5d9971..a151cccb0 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement/ChunkAwareBlockCollisionSweeper.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement/ChunkAwareBlockCollisionSweeper.java @@ -129,7 +129,6 @@ private boolean nextSection() { return false; //no more sections to iterate } } - //Casting to Chunk is not checked, together with other mods this could cause a ClassCastException this.cachedChunk = this.world.getChunk(this.chunkX, this.chunkZ, ChunkStatus.FULL, false); if (this.cachedChunk != null) { this.cachedChunkSection = this.cachedChunk.getSectionArray()[this.chunkYIndex]; @@ -290,7 +289,7 @@ private static int expandMax(int coord) { private static boolean hasChunkSectionOversizedBlocks(Chunk chunk, int chunkY) { if (BlockStateFlags.ENABLED) { ChunkSection section = chunk.getSectionArray()[chunkY]; - return section != null && ((BlockCountingSection) section).mayContainAny(BlockStateFlags.OVERSIZED_SHAPE); + return section != null && ((BlockCountingSection) section).lithium$mayContainAny(BlockStateFlags.OVERSIZED_SHAPE); } return true; //like vanilla, assume that a chunk section has oversized blocks, when the section mixin isn't loaded } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/EntityMovementTrackerSection.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/EntityMovementTrackerSection.java index 90615afeb..1d09e2fd7 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/EntityMovementTrackerSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/EntityMovementTrackerSection.java @@ -4,15 +4,15 @@ import net.minecraft.world.entity.SectionedEntityCache; public interface EntityMovementTrackerSection { - void addListener(SectionedEntityMovementTracker listener); + void lithium$addListener(SectionedEntityMovementTracker listener); - void removeListener(SectionedEntityCache sectionedEntityCache, SectionedEntityMovementTracker listener); + void lithium$removeListener(SectionedEntityCache sectionedEntityCache, SectionedEntityMovementTracker listener); - void trackEntityMovement(int notificationMask, long time); + void lithium$trackEntityMovement(int notificationMask, long time); - long getChangeTime(int trackedClass); + long lithium$getChangeTime(int trackedClass); - void listenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass); + void lithium$listenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass); - void removeListenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass); + void lithium$removeListenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/MovementTrackerCache.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/MovementTrackerCache.java index c9b345628..bee6fb05f 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/MovementTrackerCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/MovementTrackerCache.java @@ -1,7 +1,7 @@ package me.jellysquid.mods.lithium.common.entity.movement_tracker; public interface MovementTrackerCache { - void remove(SectionedEntityMovementTracker tracker); + void lithium$remove(SectionedEntityMovementTracker tracker); - > S deduplicate(S tracker); + > S lithium$deduplicate(S tracker); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementListener.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementListener.java index 391cb3339..5ec613987 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementListener.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementListener.java @@ -2,6 +2,6 @@ public interface SectionedEntityMovementListener { - void handleEntityMovement(Class category); + void lithium$handleEntityMovement(Class category); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementTracker.java index 4fe56df40..8003a5692 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedEntityMovementTracker.java @@ -70,8 +70,8 @@ private long listenToAllSectionsAndGetMaxChangeTime() { ArrayList notListeningTo = this.sectionsNotListeningTo; for (int i = notListeningTo.size() - 1; i >= 0; i--) { EntityMovementTrackerSection entityMovementTrackerSection = notListeningTo.remove(i); - entityMovementTrackerSection.listenToMovementOnce(this, this.trackedClass); - maxChangeTime = Math.max(maxChangeTime, entityMovementTrackerSection.getChangeTime(this.trackedClass)); + entityMovementTrackerSection.lithium$listenToMovementOnce(this, this.trackedClass); + maxChangeTime = Math.max(maxChangeTime, entityMovementTrackerSection.lithium$getChangeTime(this.trackedClass)); } return maxChangeTime; } @@ -97,7 +97,7 @@ public void register(ServerWorld world) { EntityTrackingSection section = cache.getTrackingSection(ChunkSectionPos.asLong(x, y, z)); EntityMovementTrackerSection sectionAccess = (EntityMovementTrackerSection) section; this.sortedSections.add(section); - sectionAccess.addListener(this); + sectionAccess.lithium$addListener(this); } } } @@ -116,15 +116,15 @@ public void unRegister(ServerWorld world) { //noinspection unchecked SectionedEntityCache cache = ((ServerEntityManagerAccessor) ((ServerWorldAccessor) world).getEntityManager()).getCache(); MovementTrackerCache storage = (MovementTrackerCache) cache; - storage.remove(this); + storage.lithium$remove(this); ArrayList> sections = this.sortedSections; for (int i = sections.size() - 1; i >= 0; i--) { EntityTrackingSection section = sections.get(i); EntityMovementTrackerSection sectionAccess = (EntityMovementTrackerSection) section; - sectionAccess.removeListener(cache, this); + sectionAccess.lithium$removeListener(cache, this); if (!this.sectionsNotListeningTo.remove(section)) { - ((EntityMovementTrackerSection) section).removeListenToMovementOnce(this, this.trackedClass); + ((EntityMovementTrackerSection) section).lithium$removeListenToMovementOnce(this, this.trackedClass); } } this.setChanged(world.getTime()); @@ -151,7 +151,7 @@ public void onSectionLeftRange(EntityMovementTrackerSection section) { this.sectionVisible[sectionIndex] = false; if (!this.sectionsNotListeningTo.remove(section)) { - section.removeListenToMovementOnce(this, this.trackedClass); + section.lithium$removeListenToMovementOnce(this, this.trackedClass); this.notifyAllListeners(); } } @@ -188,7 +188,7 @@ private void notifyAllListeners() { ReferenceOpenHashSet listeners = this.sectionedEntityMovementListeners; if (listeners != null && !listeners.isEmpty()) { for (SectionedEntityMovementListener listener : listeners) { - listener.handleEntityMovement(this.clazz); + listener.lithium$handleEntityMovement(this.clazz); } listeners.clear(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedInventoryEntityMovementTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedInventoryEntityMovementTracker.java index 2bc79a49d..42648c508 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedInventoryEntityMovementTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedInventoryEntityMovementTracker.java @@ -23,7 +23,7 @@ public static SectionedInventoryEntityMovementTracker registerAt(ServerWo WorldSectionBox worldSectionBox = WorldSectionBox.entityAccessBox(world, interactionArea); SectionedInventoryEntityMovementTracker tracker = new SectionedInventoryEntityMovementTracker<>(worldSectionBox, clazz); - tracker = cache.deduplicate(tracker); + tracker = cache.lithium$deduplicate(tracker); tracker.register(world); return tracker; diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedItemEntityMovementTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedItemEntityMovementTracker.java index f1970cdad..02fae09e9 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedItemEntityMovementTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/SectionedItemEntityMovementTracker.java @@ -1,6 +1,5 @@ package me.jellysquid.mods.lithium.common.entity.movement_tracker; -import me.jellysquid.mods.lithium.common.util.collections.BucketedList; import me.jellysquid.mods.lithium.common.util.tuples.WorldSectionBox; import me.jellysquid.mods.lithium.mixin.block.hopper.EntityTrackingSectionAccessor; import me.jellysquid.mods.lithium.mixin.util.entity_movement_tracking.ServerEntityManagerAccessor; @@ -10,6 +9,7 @@ import net.minecraft.util.collection.TypeFilterableList; import net.minecraft.util.math.Box; +import java.util.ArrayList; import java.util.List; public class SectionedItemEntityMovementTracker extends SectionedEntityMovementTracker { @@ -18,21 +18,19 @@ public SectionedItemEntityMovementTracker(WorldSectionBox worldSectionBox, Class super(worldSectionBox, clazz); } - public static SectionedItemEntityMovementTracker registerAt(ServerWorld world, Box encompassingBox, Class clazz) { + public static SectionedItemEntityMovementTracker registerAt(ServerWorld world, Box interactionArea, Class clazz) { MovementTrackerCache cache = (MovementTrackerCache) ((ServerEntityManagerAccessor) ((ServerWorldAccessor) world).getEntityManager()).getCache(); - WorldSectionBox worldSectionBox = WorldSectionBox.entityAccessBox(world, encompassingBox); + WorldSectionBox worldSectionBox = WorldSectionBox.entityAccessBox(world, interactionArea); SectionedItemEntityMovementTracker tracker = new SectionedItemEntityMovementTracker<>(worldSectionBox, clazz); - tracker = cache.deduplicate(tracker); + tracker = cache.lithium$deduplicate(tracker); tracker.register(world); return tracker; } - public List getEntities(Box[] areas) { - int numBoxes = areas.length - 1; - BucketedList entities = new BucketedList<>(numBoxes); - Box encompassingBox = areas[numBoxes]; + public List getEntities(Box interactionArea) { + ArrayList entities = new ArrayList<>(); for (int sectionIndex = 0; sectionIndex < this.sortedSections.size(); sectionIndex++) { if (this.sectionVisible[sectionIndex]) { //noinspection unchecked @@ -41,16 +39,8 @@ public List getEntities(Box[] areas) { for (S entity : collection.getAllOfType(this.clazz)) { if (entity.isAlive()) { Box entityBoundingBox = entity.getBoundingBox(); - //even though there are usually only two boxes to check, checking the encompassing box only will be faster in most cases - //In vanilla the number of boxes checked is always 2. Here it is 1 (miss) and 2-3 (hit) - if (entityBoundingBox.intersects(encompassingBox)) { - for (int j = 0; j < numBoxes; j++) { - if (entityBoundingBox.intersects(areas[j])) { - entities.addToBucket(j, entity); - //Only add each entity once. A hopper cannot pick up from the entity twice anyways. - break; - } - } + if (entityBoundingBox.intersects(interactionArea)) { + entities.add(entity); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/ToggleableMovementTracker.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/ToggleableMovementTracker.java index a6730d4b3..fc1329226 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/ToggleableMovementTracker.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/movement_tracker/ToggleableMovementTracker.java @@ -2,5 +2,5 @@ public interface ToggleableMovementTracker { - int setNotificationMask(int notificationMask); + int lithium$setNotificationMask(int notificationMask); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListener.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListener.java index a064ded7f..d245905c1 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListener.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListener.java @@ -30,7 +30,7 @@ default void updateChunkRegistrations(SectionedEntityCache if (after == null || !after.contains(pos.set(x, y, z))) { long sectionPos = ChunkSectionPos.asLong(x, y, z); EntityTrackingSection trackingSection = entityCache.getTrackingSection(sectionPos); - ((NearbyEntityListenerSection) trackingSection).removeListener(entityCache, this); + ((NearbyEntityListenerSection) trackingSection).lithium$removeListener(entityCache, this); if (trackingSection.isEmpty()) { entityCache.removeSection(sectionPos); } @@ -44,7 +44,7 @@ default void updateChunkRegistrations(SectionedEntityCache for (int y = after.getMinY(); y <= after.getMaxY(); y++) { for (int z = after.getMinZ(); z <= after.getMaxZ(); z++) { if (before == null || !before.contains(pos.set(x, y, z))) { - ((NearbyEntityListenerSection) entityCache.getTrackingSection(ChunkSectionPos.asLong(x, y, z))).addListener(this); + ((NearbyEntityListenerSection) entityCache.getTrackingSection(ChunkSectionPos.asLong(x, y, z))).lithium$addListener(this); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerMulti.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerMulti.java index caaf44cb1..14191acd4 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerMulti.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerMulti.java @@ -39,7 +39,7 @@ private void updateRange(NearbyEn this.range = updatedRange; //noinspection unchecked - SectionedEntityCache entityCache = ((ServerEntityManagerAccessor)((ServerWorldAccessor)tracker.getEntity().getWorld()).getEntityManager()).getCache(); + SectionedEntityCache entityCache = ((ServerEntityManagerAccessor) ((ServerWorldAccessor) tracker.getEntity().getWorld()).getEntityManager()).getCache(); ChunkSectionPos chunkPos = ChunkSectionPos.from(tracker.getEntity().getBlockPos()); this.updateChunkRegistrations(entityCache, chunkPos, this.range, chunkPos, updatedRange); diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerProvider.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerProvider.java index 7b1e5b707..fef161be5 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerProvider.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerProvider.java @@ -4,7 +4,7 @@ public interface NearbyEntityListenerProvider { @Nullable - NearbyEntityListenerMulti getListener(); + NearbyEntityListenerMulti lithium$getListener(); - void addListener(NearbyEntityTracker listener); + void lithium$addListener(NearbyEntityTracker listener); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerSection.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerSection.java index ef74b5ac0..c097b07a1 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/nearby_tracker/NearbyEntityListenerSection.java @@ -3,7 +3,7 @@ import net.minecraft.world.entity.SectionedEntityCache; public interface NearbyEntityListenerSection { - void addListener(NearbyEntityListener listener); + void lithium$addListener(NearbyEntityListener listener); - void removeListener(SectionedEntityCache sectionedEntityCache, NearbyEntityListener listener); + void lithium$removeListener(SectionedEntityCache sectionedEntityCache, NearbyEntityListener listener); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/BlockCachingEntity.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/BlockCachingEntity.java index 1f0d4b870..66b946877 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/BlockCachingEntity.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/BlockCachingEntity.java @@ -4,17 +4,17 @@ public interface BlockCachingEntity { - default void lithiumOnBlockCacheDeleted() { + default void lithium$OnBlockCacheDeleted() { } - default void lithiumOnBlockCacheSet(BlockState newState) { + default void lithium$OnBlockCacheSet(BlockState newState) { } - default void lithiumSetClimbingMobCachingSectionUpdateBehavior(boolean listening) { + default void lithium$SetClimbingMobCachingSectionUpdateBehavior(boolean listening) { throw new UnsupportedOperationException(); } - BlockState getCachedFeetBlockState(); + BlockState lithium$getCachedFeetBlockState(); } \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/PushableEntityClassGroup.java b/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/PushableEntityClassGroup.java index 6dd3c7b0f..72d3460b3 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/PushableEntityClassGroup.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/entity/pushable/PushableEntityClassGroup.java @@ -2,7 +2,6 @@ import me.jellysquid.mods.lithium.common.entity.EntityClassGroup; import me.jellysquid.mods.lithium.common.reflection.ReflectionUtil; -import cpw.mods.modlauncher.api.INameMappingService; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.boss.dragon.EnderDragonEntity; diff --git a/src/main/java/me/jellysquid/mods/lithium/common/hopper/HopperHelper.java b/src/main/java/me/jellysquid/mods/lithium/common/hopper/HopperHelper.java index 04d5a15f9..c2cedd1c5 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/hopper/HopperHelper.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/hopper/HopperHelper.java @@ -1,65 +1,17 @@ package me.jellysquid.mods.lithium.common.hopper; -import net.minecraft.block.Block; -import net.minecraft.block.BlockState; -import net.minecraft.block.ChestBlock; -import net.minecraft.block.InventoryProvider; -import net.minecraft.block.entity.*; +import net.minecraft.block.entity.HopperBlockEntity; +import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.inventory.DoubleInventory; import net.minecraft.inventory.Inventory; import net.minecraft.inventory.SidedInventory; import net.minecraft.item.ItemStack; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Box; import net.minecraft.util.math.Direction; import net.minecraft.util.math.MathHelper; -import net.minecraft.util.shape.VoxelShape; -import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; -import java.util.Objects; - public class HopperHelper { - private static final VoxelShape CACHED_INPUT_VOLUME = Hopper.INPUT_AREA_SHAPE; - private static final Box[] CACHED_INPUT_VOLUME_BOXES = CACHED_INPUT_VOLUME.getBoundingBoxes().toArray(new Box[0]); - - public static Box[] getHopperPickupVolumeBoxes(Hopper hopper) { - VoxelShape inputAreaShape = hopper.getInputAreaShape(); - if (inputAreaShape == CACHED_INPUT_VOLUME) { - return CACHED_INPUT_VOLUME_BOXES; - } - return inputAreaShape.getBoundingBoxes().toArray(new Box[0]); - } - - /** - * Gets the block inventory at the given position, exactly like vanilla gets it. - * Needed because we don't want to search for entity inventories like the vanilla method does. - * - * @param world world we are searching in - * @param blockPos position of the block inventory - * @return the block inventory at the given position - */ - @Nullable - public static Inventory vanillaGetBlockInventory(World world, BlockPos blockPos) { - //[VanillaCopy] - Inventory inventory = null; - BlockState blockState = world.getBlockState(blockPos); - Block block = blockState.getBlock(); - if (block instanceof InventoryProvider) { - inventory = ((InventoryProvider)block).getInventory(blockState, world, blockPos); - } else if (blockState.hasBlockEntity()) { - BlockEntity blockEntity = world.getBlockEntity(blockPos); - if (blockEntity instanceof Inventory) { - inventory = (Inventory)blockEntity; - if (inventory instanceof ChestBlockEntity && block instanceof ChestBlock) { - inventory = ChestBlock.getInventory((ChestBlock)block, blockState, world, blockPos, true); - } - } - } - return inventory; - } - public static boolean tryMoveSingleItem(Inventory to, ItemStack stack, @Nullable Direction fromDirection) { SidedInventory toSided = to instanceof SidedInventory ? ((SidedInventory) to) : null; if (toSided != null && fromDirection != null) { @@ -83,14 +35,14 @@ public static boolean tryMoveSingleItem(Inventory to, ItemStack stack, @Nullable public static boolean tryMoveSingleItem(Inventory to, @Nullable SidedInventory toSided, ItemStack transferStack, int targetSlot, @Nullable Direction fromDirection) { ItemStack toStack = to.getStack(targetSlot); - //Assumption: no mods depend on the the stack size of transferStack in isValid or canInsert, like vanilla doesn't + //Assumption: no mods depend on the stack size of transferStack in isValid or canInsert, like vanilla doesn't if (to.isValid(targetSlot, transferStack) && (toSided == null || toSided.canInsert(targetSlot, transferStack, fromDirection))) { int toCount; if (toStack.isEmpty()) { ItemStack singleItem = transferStack.split(1); to.setStack(targetSlot, singleItem); return true; //caller needs to call to.markDirty() - } else if (toStack.isOf(transferStack.getItem()) && toStack.getMaxCount() > (toCount = toStack.getCount()) && to.getMaxCountPerStack() > toCount && areNbtEqual(toStack, transferStack)) { + } else if (toStack.getMaxCount() > (toCount = toStack.getCount()) && to.getMaxCountPerStack() > toCount && ItemStack.areItemsAndComponentsEqual(toStack, transferStack)) { transferStack.decrement(1); toStack.increment(1); return true; //caller needs to call to.markDirty() @@ -99,12 +51,8 @@ public static boolean tryMoveSingleItem(Inventory to, @Nullable SidedInventory t return false; } - private static boolean areNbtEqual(ItemStack stack1, ItemStack stack2) { - return Objects.equals(stack1.getNbt(), stack2.getNbt()); - } - private static int calculateReducedSignalStrength(float contentWeight, int inventorySize, int inventoryMaxCountPerStack, int numOccupiedSlots, int itemStackCount, int itemStackMaxCount) { - //contentWeight adaption can include rounding error for non power of 2 max stack sizes, which do not exist in vanilla anyways + //contentWeight adaption can include rounding error for non-power of 2 max stack sizes, which do not exist in vanilla anyways int maxStackSize = Math.min(inventoryMaxCountPerStack, itemStackMaxCount); int newNumOccupiedSlots = numOccupiedSlots - (itemStackCount == 1 ? 1 : 0); float newContentWeight = contentWeight - (1f / (float) maxStackSize); diff --git a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleInventory.java b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleInventory.java index fb1a3a383..894a943d9 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleInventory.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleInventory.java @@ -25,7 +25,7 @@ public class LithiumDoubleInventory extends DoubleInventory implements LithiumIn /** * This method returns the same LithiumDoubleInventory instance for equal (same children in same order) - * doubleInventory parameters until {@link #emitRemoved()} is called. After that a new LithiumDoubleInventory object + * doubleInventory parameters until {@link #lithium$emitRemoved()} is called. After that a new LithiumDoubleInventory object * may be in use. * * @param doubleInventory A double inventory @@ -55,18 +55,18 @@ private LithiumDoubleInventory(LithiumInventory first, LithiumInventory second) } @Override - public void emitContentModified() { + public void lithium$emitContentModified() { ReferenceOpenHashSet inventoryChangeListeners = this.inventoryChangeListeners; if (inventoryChangeListeners != null) { for (InventoryChangeListener inventoryChangeListener : inventoryChangeListeners) { - inventoryChangeListener.handleInventoryContentModified(this); + inventoryChangeListener.lithium$handleInventoryContentModified(this); } inventoryChangeListeners.clear(); } } @Override - public void emitStackListReplaced() { + public void lithium$emitStackListReplaced() { ReferenceOpenHashSet listeners = this.inventoryHandlingTypeListeners; if (listeners != null && !listeners.isEmpty()) { listeners.forEach(inventoryChangeListener -> inventoryChangeListener.handleStackListReplaced(this)); @@ -76,10 +76,10 @@ public void emitStackListReplaced() { } @Override - public void emitRemoved() { + public void lithium$emitRemoved() { ReferenceOpenHashSet listeners = this.inventoryHandlingTypeListeners; if (listeners != null && !listeners.isEmpty()) { - listeners.forEach(listener -> listener.handleInventoryRemoved(this)); + listeners.forEach(listener -> listener.lithium$handleInventoryRemoved(this)); } this.invalidateChangeListening(); @@ -97,15 +97,15 @@ private void invalidateChangeListening() { } @Override - public void emitFirstComparatorAdded() { + public void lithium$emitFirstComparatorAdded() { ReferenceOpenHashSet inventoryChangeListeners = this.inventoryChangeListeners; if (inventoryChangeListeners != null && !inventoryChangeListeners.isEmpty()) { - inventoryChangeListeners.removeIf(inventoryChangeListener -> inventoryChangeListener.handleComparatorAdded(this)); + inventoryChangeListeners.removeIf(inventoryChangeListener -> inventoryChangeListener.lithium$handleComparatorAdded(this)); } } @Override - public void forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker) { + public void lithium$forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker) { if (this.inventoryChangeListeners == null) { this.inventoryChangeListeners = new ReferenceOpenHashSet<>(1); } @@ -115,7 +115,7 @@ public void forwardContentChangeOnce(InventoryChangeListener inventoryChangeList } @Override - public void forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { + public void lithium$forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { if (this.inventoryHandlingTypeListeners == null) { this.inventoryHandlingTypeListeners = new ReferenceOpenHashSet<>(1); @@ -126,7 +126,7 @@ public void forwardMajorInventoryChanges(InventoryChangeListener inventoryChange } @Override - public void stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { + public void lithium$stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { if (this.inventoryHandlingTypeListeners != null) { this.inventoryHandlingTypeListeners.remove(inventoryChangeListener); if (this.inventoryHandlingTypeListeners.isEmpty()) { @@ -147,28 +147,28 @@ public void setInventoryLithium(DefaultedList inventory) { } @Override - public void handleInventoryContentModified(Inventory inventory) { - this.emitContentModified(); + public void lithium$handleInventoryContentModified(Inventory inventory) { + this.lithium$emitContentModified(); } @Override - public void handleInventoryRemoved(Inventory inventory) { - this.emitRemoved(); + public void lithium$handleInventoryRemoved(Inventory inventory) { + this.lithium$emitRemoved(); } @Override - public boolean handleComparatorAdded(Inventory inventory) { - this.emitFirstComparatorAdded(); + public boolean lithium$handleComparatorAdded(Inventory inventory) { + this.lithium$emitFirstComparatorAdded(); return this.inventoryChangeListeners.isEmpty(); } @Override - public void onComparatorAdded(Direction direction, int offset) { + public void lithium$onComparatorAdded(Direction direction, int offset) { throw new UnsupportedOperationException("Call onComparatorAdded(Direction direction, int offset) on the inventory half only!"); } @Override - public boolean hasAnyComparatorNearby() { - return ((ComparatorTracker) this.first).hasAnyComparatorNearby() || ((ComparatorTracker) this.second).hasAnyComparatorNearby(); + public boolean lithium$hasAnyComparatorNearby() { + return ((ComparatorTracker) this.first).lithium$hasAnyComparatorNearby() || ((ComparatorTracker) this.second).lithium$hasAnyComparatorNearby(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleStackList.java b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleStackList.java index 3d12098fb..2aaf3868c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleStackList.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumDoubleStackList.java @@ -30,7 +30,7 @@ public static LithiumDoubleStackList getOrCreate(LithiumDoubleInventory doubleIn LithiumDoubleStackList parentStackList = first.parent; if (parentStackList == null || parentStackList != second.parent || parentStackList.first != first || parentStackList.second != second) { if (parentStackList != null) { - parentStackList.doubleInventory.emitRemoved(); + parentStackList.doubleInventory.lithium$emitRemoved(); } parentStackList = new LithiumDoubleStackList(doubleInventory, first, second, maxCountPerStack); first.parent = parentStackList; diff --git a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumStackList.java b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumStackList.java index fb2c6835d..a7197bf9c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumStackList.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/hopper/LithiumStackList.java @@ -121,7 +121,7 @@ public void changed() { InventoryChangeTracker inventoryModificationCallback = this.inventoryModificationCallback; if (inventoryModificationCallback != null) { this.inventoryModificationCallback = null; - inventoryModificationCallback.emitContentModified(); + inventoryModificationCallback.lithium$emitContentModified(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/hopper/UpdateReceiver.java b/src/main/java/me/jellysquid/mods/lithium/common/hopper/UpdateReceiver.java index 961ec357e..484686214 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/hopper/UpdateReceiver.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/hopper/UpdateReceiver.java @@ -3,6 +3,7 @@ import net.minecraft.util.math.Direction; public interface UpdateReceiver { - void invalidateCacheOnNeighborUpdate(boolean above); - void invalidateCacheOnNeighborUpdate(Direction fromDirection); + void lithium$invalidateCacheOnNeighborUpdate(boolean above); + + void lithium$invalidateCacheOnNeighborUpdate(Direction fromDirection); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/shapes/OffsetVoxelShapeCache.java b/src/main/java/me/jellysquid/mods/lithium/common/shapes/OffsetVoxelShapeCache.java index d17a0b2e4..77659e156 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/shapes/OffsetVoxelShapeCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/shapes/OffsetVoxelShapeCache.java @@ -4,7 +4,7 @@ import net.minecraft.util.shape.VoxelShape; public interface OffsetVoxelShapeCache { - VoxelShape getOffsetSimplifiedShape(float offset, Direction direction); + VoxelShape lithium$getOffsetSimplifiedShape(float offset, Direction direction); - void setShape(float offset, Direction direction, VoxelShape offsetShape); + void lithium$setShape(float offset, Direction direction, VoxelShape offsetShape); } \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboid.java b/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboid.java index f55ff1f56..9396f9bb2 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboid.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboid.java @@ -21,29 +21,26 @@ public class VoxelShapeAlignedCuboid extends VoxelShapeSimpleCube { //EPSILON for use in cases where it must be a lot smaller than 1/256 and larger than EPSILON static final double LARGE_EPSILON = 10 * EPSILON; - //In bit aligned shapes the bitset adds segments are between minX/Y/Z and maxX/Y/Z. + //In bit-aligned shapes the bitset adds segments are between minX/Y/Z and maxX/Y/Z. //Segments all have the same size. There is an additional collision box between two adjacent segments (if both are inside the shape) - protected final int xSegments; - protected final int ySegments; - protected final int zSegments; + protected final byte xyzResolution; public VoxelShapeAlignedCuboid(double minX, double minY, double minZ, double maxX, double maxY, double maxZ, int xRes, int yRes, int zRes) { super(new CuboidVoxelSet(1 << xRes, 1 << yRes, 1 << zRes, minX, minY, minZ, maxX, maxY, maxZ), minX, minY, minZ, maxX, maxY, maxZ); - this.xSegments = 1 << xRes; - this.ySegments = 1 << yRes; - this.zSegments = 1 << zRes; + if (xRes > 3 || yRes > 3 || zRes > 3 || xRes < 0 || yRes < 0 || zRes < 0) { + throw new IllegalArgumentException("Resolution must be between 0 and 3"); + } + + this.xyzResolution = (byte) (xRes << 4 | yRes << 2 | zRes); } /** * Constructor for use in offset() calls. */ - public VoxelShapeAlignedCuboid(VoxelSet voxels, int xSegments, int ySegments, int zSegments, double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { + public VoxelShapeAlignedCuboid(VoxelSet voxels, double minX, double minY, double minZ, double maxX, double maxY, double maxZ, byte xyzResolution) { super(voxels, minX, minY, minZ, maxX, maxY, maxZ); - - this.xSegments = xSegments; - this.ySegments = ySegments; - this.zSegments = zSegments; + this.xyzResolution = xyzResolution; } @Override @@ -70,11 +67,11 @@ public double calculateMaxDistance(AxisCycleDirection cycleDirection, Box box, d private double calculatePenetration(AxisCycleDirection dir, Box box, double maxDist) { switch (dir) { case NONE: - return VoxelShapeAlignedCuboid.calculatePenetration(this.minX, this.maxX, this.xSegments, box.minX, box.maxX, maxDist); + return VoxelShapeAlignedCuboid.calculatePenetration(this.minX, this.maxX, this.getXSegments(), box.minX, box.maxX, maxDist); case FORWARD: - return VoxelShapeAlignedCuboid.calculatePenetration(this.minZ, this.maxZ, this.zSegments, box.minZ, box.maxZ, maxDist); + return VoxelShapeAlignedCuboid.calculatePenetration(this.minZ, this.maxZ, this.getZSegments(), box.minZ, box.maxZ, maxDist); case BACKWARD: - return VoxelShapeAlignedCuboid.calculatePenetration(this.minY, this.maxY, this.ySegments, box.minY, box.maxY, maxDist); + return VoxelShapeAlignedCuboid.calculatePenetration(this.minY, this.maxY, this.getYSegments(), box.minY, box.maxY, maxDist); default: throw new IllegalArgumentException(); } @@ -134,17 +131,29 @@ private static double calculatePenetration(double aMin, double aMax, final int s @Override public DoubleList getPointPositions(Direction.Axis axis) { - return new FractionalDoubleList(axis.choose(this.xSegments, this.ySegments, this.zSegments)); + return new FractionalDoubleList(axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments())); } @Override protected double getPointPosition(Direction.Axis axis, int index) { - return (double) index / (double) axis.choose(this.xSegments, this.ySegments, this.zSegments); + return (double) index / (double) axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments()); } @Override protected int getCoordIndex(Direction.Axis axis, double coord) { - int i = axis.choose(this.xSegments, this.ySegments, this.zSegments); + int i = axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments()); return MathHelper.clamp(MathHelper.floor(coord * (double) i), -1, i); } + + protected int getXSegments() { + return 1 << (this.xyzResolution >>> 4); + } + + protected int getYSegments() { + return 1 << ((this.xyzResolution >>> 2) & 3); + } + + protected int getZSegments() { + return 1 << (this.xyzResolution & 3); + } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboidOffset.java b/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboidOffset.java index 1396a8a3d..b18a1b4e7 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboidOffset.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/shapes/VoxelShapeAlignedCuboidOffset.java @@ -17,14 +17,14 @@ public class VoxelShapeAlignedCuboidOffset extends VoxelShapeAlignedCuboid { //instead of keeping those variables, equivalent information can probably be recovered from minX, minY, minZ (which are 1/8th of a block aligned), but possibly with additional floating point error public VoxelShapeAlignedCuboidOffset(VoxelShapeAlignedCuboid originalShape, VoxelSet voxels, double xOffset, double yOffset, double zOffset) { - super(voxels, originalShape.xSegments, originalShape.ySegments, originalShape.zSegments, + super(voxels, originalShape.minX + xOffset, originalShape.minY + yOffset, originalShape.minZ + zOffset, - originalShape.maxX + xOffset, originalShape.maxY + yOffset, originalShape.maxZ + zOffset); + originalShape.maxX + xOffset, originalShape.maxY + yOffset, originalShape.maxZ + zOffset, originalShape.xyzResolution); if (originalShape instanceof VoxelShapeAlignedCuboidOffset) { - this.xOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).xOffset + xOffset; - this.yOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).yOffset + yOffset; - this.zOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).zOffset + zOffset; + this.xOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).xOffset + xOffset; //TODO the float addition here might cause non-vanilla floating point errors + this.yOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).yOffset + yOffset; // Float non-associativity technically causes an issue here + this.zOffset = ((VoxelShapeAlignedCuboidOffset) originalShape).zOffset + zOffset; // In practice, this is likely not a problem } else { this.xOffset = xOffset; this.yOffset = yOffset; @@ -55,11 +55,11 @@ public double calculateMaxDistance(AxisCycleDirection cycleDirection, Box box, d private double calculatePenetration(AxisCycleDirection dir, Box box, double maxDist) { switch (dir) { case NONE: - return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minX, this.maxX, this.xSegments, this.xOffset, box.minX, box.maxX, maxDist); + return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minX, this.maxX, this.getXSegments(), this.xOffset, box.minX, box.maxX, maxDist); case FORWARD: - return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minZ, this.maxZ, this.zSegments, this.zOffset, box.minZ, box.maxZ, maxDist); + return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minZ, this.maxZ, this.getZSegments(), this.zOffset, box.minZ, box.maxZ, maxDist); case BACKWARD: - return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minY, this.maxY, this.ySegments, this.yOffset, box.minY, box.maxY, maxDist); + return VoxelShapeAlignedCuboidOffset.calculatePenetration(this.minY, this.maxY, this.getYSegments(), this.yOffset, box.minY, box.maxY, maxDist); default: throw new IllegalArgumentException(); } @@ -134,20 +134,20 @@ private static double calculatePenetration(double aMin, double aMax, final int s @Override public DoubleList getPointPositions(Direction.Axis axis) { - return new OffsetFractionalDoubleList(axis.choose(this.xSegments, this.ySegments, this.zSegments), + return new OffsetFractionalDoubleList(axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments()), axis.choose(this.xOffset, this.yOffset, this.zOffset)); } @Override protected double getPointPosition(Direction.Axis axis, int index) { return axis.choose(this.xOffset, this.yOffset, this.zOffset) + - ((double) index / (double) axis.choose(this.xSegments, this.ySegments, this.zSegments)); + ((double) index / (double) axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments())); } @Override protected int getCoordIndex(Direction.Axis axis, double coord) { coord -= axis.choose(this.xOffset, this.yOffset, this.zOffset); - int numSegments = axis.choose(this.xSegments, this.ySegments, this.zSegments); + int numSegments = axis.choose(this.getXSegments(), this.getYSegments(), this.getZSegments()); return MathHelper.clamp(MathHelper.floor(coord * (double) numSegments), -1, numSegments); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/util/deduplication/LithiumInternerWrapper.java b/src/main/java/me/jellysquid/mods/lithium/common/util/deduplication/LithiumInternerWrapper.java index 27210fcef..6a32748b9 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/util/deduplication/LithiumInternerWrapper.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/util/deduplication/LithiumInternerWrapper.java @@ -2,7 +2,7 @@ public interface LithiumInternerWrapper { - T getCanonical(T value); + T lithium$getCanonical(T value); - void deleteCanonical(T value); + void lithium$deleteCanonical(T value); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkAwareEntityIterable.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkAwareEntityIterable.java index 9b550f186..793f2740f 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkAwareEntityIterable.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkAwareEntityIterable.java @@ -3,5 +3,5 @@ import net.minecraft.world.entity.EntityLike; public interface ChunkAwareEntityIterable { - Iterable lithiumIterateEntitiesInTrackedSections(); + Iterable lithium$IterateEntitiesInTrackedSections(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkRandomSource.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkRandomSource.java index 02eb1f1ed..27f95373c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkRandomSource.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkRandomSource.java @@ -8,5 +8,5 @@ public interface ChunkRandomSource { * Alternative implementation of {@link World#getRandomPosInChunk(int, int, int, int)} which does not allocate * a new {@link BlockPos}. */ - void getRandomPosInChunk(int x, int y, int z, int mask, BlockPos.Mutable out); + void lithium$getRandomPosInChunk(int x, int y, int z, int mask, BlockPos.Mutable out); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkView.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkView.java index 3d797f25f..a524ddb05 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkView.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ChunkView.java @@ -6,5 +6,5 @@ public interface ChunkView { @Nullable - Chunk getLoadedChunk(int chunkX, int chunkZ); + Chunk lithium$getLoadedChunk(int chunkX, int chunkZ); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ClimbingMobCachingSection.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ClimbingMobCachingSection.java index 733b9d678..269f4f643 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ClimbingMobCachingSection.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ClimbingMobCachingSection.java @@ -12,7 +12,7 @@ public interface ClimbingMobCachingSection { - LazyIterationConsumer.NextIteration collectPushableEntities(World world, Entity except, Box box, EntityPushablePredicate entityPushablePredicate, ArrayList entities); + LazyIterationConsumer.NextIteration lithium$collectPushableEntities(World world, Entity except, Box box, EntityPushablePredicate entityPushablePredicate, ArrayList entities); - void onEntityModifiedCachedBlock(BlockCachingEntity entity, BlockState newBlockState); + void lithium$onEntityModifiedCachedBlock(BlockCachingEntity entity, BlockState newBlockState); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ItemEntityHelper.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ItemEntityHelper.java index 486823646..f39add209 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ItemEntityHelper.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ItemEntityHelper.java @@ -2,47 +2,19 @@ import me.jellysquid.mods.lithium.common.entity.TypeFilterableListInternalAccess; import me.jellysquid.mods.lithium.common.entity.item.ItemEntityCategorizingList; -import me.jellysquid.mods.lithium.common.hopper.HopperHelper; -import me.jellysquid.mods.lithium.common.util.collections.BucketedList; import me.jellysquid.mods.lithium.mixin.util.accessors.EntityTrackingSectionAccessor; -import net.minecraft.block.entity.Hopper; import net.minecraft.entity.Entity; import net.minecraft.entity.ItemEntity; import net.minecraft.util.collection.TypeFilterableList; import net.minecraft.util.function.LazyIterationConsumer; import net.minecraft.util.math.Box; import net.minecraft.world.entity.SectionedEntityCache; -import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; public class ItemEntityHelper { - @NotNull - public static BucketedList getItemEntityBucketedList(Hopper hopper, double xOffset, double yOffset, double zOffset, List nearbyEntities) { - Box[] boundingBoxes = HopperHelper.getHopperPickupVolumeBoxes(hopper); - int numBoxes = boundingBoxes.length; - Box[] offsetBoundingBoxes = new Box[numBoxes]; - for (int i = 0; i < numBoxes; i++) { - offsetBoundingBoxes[i] = boundingBoxes[i].offset(xOffset, yOffset, zOffset); - } - - BucketedList entities = new BucketedList<>(numBoxes); - - for (ItemEntity itemEntity : nearbyEntities) { - Box entityBoundingBox = itemEntity.getBoundingBox(); - for (int j = 0; j < numBoxes; j++) { - if (entityBoundingBox.intersects(offsetBoundingBoxes[j])) { - entities.addToBucket(j, itemEntity); - //Only add each entity once. A hopper cannot pick up from the entity twice anyway. - break; - } - } - } - return entities; - } - public static void consumeItemEntitiesForMerge(SectionedEntityCache cache, ItemEntity searchingItemEntity, Box box, LazyIterationConsumer itemEntityConsumer) { cache.forEachInBox(box, section -> { //noinspection unchecked diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/ServerWorldExtended.java b/src/main/java/me/jellysquid/mods/lithium/common/world/ServerWorldExtended.java index d7b17c56f..e44b4a907 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/ServerWorldExtended.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/ServerWorldExtended.java @@ -3,7 +3,7 @@ import net.minecraft.entity.mob.MobEntity; public interface ServerWorldExtended { - void setNavigationActive(MobEntity mobEntity); + void lithium$setNavigationActive(MobEntity mobEntity); - void setNavigationInactive(MobEntity mobEntity); + void lithium$setNavigationInactive(MobEntity mobEntity); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/WorldHelper.java b/src/main/java/me/jellysquid/mods/lithium/common/world/WorldHelper.java index 12f0a6705..3b48b031c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/WorldHelper.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/WorldHelper.java @@ -55,7 +55,7 @@ public static List getEntitiesForCollision(EntityView entityView, Box bo public static SectionedEntityCache getEntityCacheOrNull(World world) { if (world instanceof ClientWorldAccessor) { //noinspection unchecked - return ((ClientEntityManagerAccessor) ((ClientWorldAccessor) world).getEntityManager()).getCache(); + return ((ClientEntityManagerAccessor) ((ClientWorldAccessor) world).lithium$getEntityManager()).getCache(); } else if (world instanceof ServerWorldAccessor) { //noinspection unchecked return ((ServerEntityManagerAccessor) ((ServerWorldAccessor) world).getEntityManager()).getCache(); @@ -69,7 +69,7 @@ public static List getEntitiesOfClassGroup(SectionedEntityCache //noinspection unchecked TypeFilterableList allEntities = ((EntityTrackingSectionAccessor) section).getCollection(); //noinspection unchecked - Collection entitiesOfType = ((ClassGroupFilterableList) allEntities).getAllOfGroupType(entityClassGroup); + Collection entitiesOfType = ((ClassGroupFilterableList) allEntities).lithium$getAllOfGroupType(entityClassGroup); if (!entitiesOfType.isEmpty()) { for (Entity entity : entitiesOfType) { if (entity.getBoundingBox().intersects(box) && !entity.isSpectator() && entity != collidingEntity) { @@ -85,7 +85,7 @@ public static List getEntitiesOfClassGroup(SectionedEntityCache public static List getPushableEntities(World world, SectionedEntityCache cache, Entity except, Box box, EntityPushablePredicate entityPushablePredicate) { ArrayList entities = new ArrayList<>(); - cache.forEachInBox(box, section -> ((ClimbingMobCachingSection) section).collectPushableEntities(world, except, box, entityPushablePredicate, entities)); + cache.forEachInBox(box, section -> ((ClimbingMobCachingSection) section).lithium$collectPushableEntities(world, except, box, entityPushablePredicate, entities)); return entities; } @@ -96,10 +96,10 @@ public static boolean areNeighborsWithinSameChunk(BlockPos pos) { return localX > 0 && localZ > 0 && localX < 15 && localZ < 15; } - public static boolean areNeighborsWithinSameChunkSection(BlockPos pos) { - int localX = pos.getX() & 15; - int localY = pos.getY() & 15; - int localZ = pos.getZ() & 15; + public static boolean areNeighborsWithinSameChunkSection(int x, int y, int z) { + int localX = x & 15; + int localY = y & 15; + int localZ = z & 15; return localX > 0 && localY > 0 && localZ > 0 && localX < 15 && localY < 15 && localZ < 15; } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/BlockEntityGetter.java b/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/BlockEntityGetter.java index e5c20888a..523210754 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/BlockEntityGetter.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/BlockEntityGetter.java @@ -4,5 +4,5 @@ import net.minecraft.util.math.BlockPos; public interface BlockEntityGetter { - BlockEntity getLoadedExistingBlockEntity(BlockPos pos); + BlockEntity lithium$getLoadedExistingBlockEntity(BlockPos pos); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/SupportCache.java b/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/SupportCache.java index 3d331ae15..1c2b4bb6c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/SupportCache.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/blockentity/SupportCache.java @@ -1,5 +1,5 @@ package me.jellysquid.mods.lithium.common.world.blockentity; public interface SupportCache { - boolean isSupported(); + boolean lithium$isSupported(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ChunkHolderExtended.java b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ChunkHolderExtended.java index ab879c98b..3fad8c3ef 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ChunkHolderExtended.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ChunkHolderExtended.java @@ -1,7 +1,6 @@ package me.jellysquid.mods.lithium.common.world.chunk; -import com.mojang.datafixers.util.Either; -import net.minecraft.server.world.ChunkHolder; +import net.minecraft.server.world.OptionalChunk; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.WorldChunk; @@ -11,12 +10,12 @@ public interface ChunkHolderExtended { /** * @return The existing future for the status at ordinal {@param index} or null if none exists */ - CompletableFuture> getFutureByStatus(int index); + CompletableFuture> lithium$getFutureByStatus(int index); /** * Updates the future for the status at ordinal {@param index}. */ - void setFutureForStatus(int index, CompletableFuture> future); + void lithium$setFutureForStatus(int index, CompletableFuture> future); /** * Updates the last accessed timestamp for this chunk. This is used to determine if a ticket was recently @@ -25,7 +24,7 @@ public interface ChunkHolderExtended { * @param time The current time * @return True if the chunk needs a new ticket to be created in order to retain it, otherwise false */ - boolean updateLastAccessTime(long time); + boolean lithium$updateLastAccessTime(long time); WorldChunk getCurrentlyLoading(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ClassGroupFilterableList.java b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ClassGroupFilterableList.java index 3f605f4e8..40a7f8020 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ClassGroupFilterableList.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/ClassGroupFilterableList.java @@ -5,6 +5,6 @@ import java.util.Collection; public interface ClassGroupFilterableList { - Collection getAllOfGroupType(EntityClassGroup type); + Collection lithium$getAllOfGroupType(EntityClassGroup type); } \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/CompactingPackedIntegerArray.java b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/CompactingPackedIntegerArray.java index 561b6aad7..30413784c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/CompactingPackedIntegerArray.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/CompactingPackedIntegerArray.java @@ -7,5 +7,5 @@ public interface CompactingPackedIntegerArray { * Copies the data out of this array into a new non-packed array. The returned array contains a copy of this array * re-mapped using {@param destPalette}. */ - void compact(Palette srcPalette, Palette dstPalette, short[] out); + void lithium$compact(Palette srcPalette, Palette dstPalette, short[] out); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/LithiumHashPalette.java b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/LithiumHashPalette.java index 72a1607d1..2e1aab539 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/LithiumHashPalette.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/chunk/LithiumHashPalette.java @@ -7,6 +7,7 @@ import net.minecraft.network.PacketByteBuf; import net.minecraft.network.encoding.VarInts; import net.minecraft.util.collection.IndexedIterable; +import net.minecraft.world.chunk.EntryMissingException; import net.minecraft.world.chunk.Palette; import net.minecraft.world.chunk.PaletteResizeListener; @@ -120,11 +121,16 @@ private void resize(int neededCapacity) { public T get(int id) { T[] entries = this.entries; + T entry = null; if (id >= 0 && id < entries.length) { - return entries[id]; + entry = entries[id]; } - return null; + if (entry != null) { + return entry; + } else { + throw new EntryMissingException(id); + } } @Override diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestSetExtended.java b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestSetExtended.java index 194d6df64..ab20e237c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestSetExtended.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestSetExtended.java @@ -9,6 +9,6 @@ import java.util.function.Predicate; public interface PointOfInterestSetExtended { - void collectMatchingPoints(Predicate> type, PointOfInterestStorage.OccupationStatus status, - Consumer consumer); + void lithium$collectMatchingPoints(Predicate> type, PointOfInterestStorage.OccupationStatus status, + Consumer consumer); } \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestStorageExtended.java b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestStorageExtended.java index d5e63b1d1..22294aaaf 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestStorageExtended.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/PointOfInterestStorageExtended.java @@ -30,6 +30,6 @@ public interface PointOfInterestStorageExtended { * @param worldBorder The world border the POI must be inside. * @return The first accepted position (respecting the described order) */ - Optional findNearestForPortalLogic(BlockPos pos, int radius, RegistryEntry type, PointOfInterestStorage.OccupationStatus status, - Predicate afterSortPredicate, WorldBorder worldBorder); + Optional lithium$findNearestForPortalLogic(BlockPos pos, int radius, RegistryEntry type, PointOfInterestStorage.OccupationStatus status, + Predicate afterSortPredicate, WorldBorder worldBorder); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/RegionBasedStorageSectionExtended.java b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/RegionBasedStorageSectionExtended.java index 844d7fe3f..50d4893ab 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/RegionBasedStorageSectionExtended.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/RegionBasedStorageSectionExtended.java @@ -10,7 +10,7 @@ public interface RegionBasedStorageSectionExtended { * @param chunkX The x-coordinate of the chunk column * @param chunkZ The z-coordinate of the chunk column */ - Stream getWithinChunkColumn(int chunkX, int chunkZ); + Stream lithium$getWithinChunkColumn(int chunkX, int chunkZ); /** * Fast-path for collecting all items in a chunk column. This avoids needing to retrieve items for each sub-chunk @@ -19,5 +19,5 @@ public interface RegionBasedStorageSectionExtended { * @param chunkX The x-coordinate of the chunk column * @param chunkZ The z-coordinate of the chunk column */ - Iterable getInChunkColumn(int chunkX, int chunkZ); + Iterable lithium$getInChunkColumn(int chunkX, int chunkZ); } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/NearbyPointOfInterestStream.java b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/NearbyPointOfInterestStream.java index de06cd109..9efb1e6fe 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/NearbyPointOfInterestStream.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/NearbyPointOfInterestStream.java @@ -188,8 +188,8 @@ public boolean tryAdvance(Consumer action) { int previousSize = this.points.size(); // Collect all points in the chunk into the active list of points - for (PointOfInterestSet set : this.storage.getInChunkColumn(chunkPosX, chunkPosZ)) { - ((PointOfInterestSetExtended) set).collectMatchingPoints(this.typeSelector, this.occupationStatus, this.collector); + for (PointOfInterestSet set : this.storage.lithium$getInChunkColumn(chunkPosX, chunkPosZ)) { + ((PointOfInterestSetExtended) set).lithium$collectMatchingPoints(this.typeSelector, this.occupationStatus, this.collector); } // If no points were found in this chunk, skip it early and move on diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/SphereChunkOrderedPoiSetSpliterator.java b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/SphereChunkOrderedPoiSetSpliterator.java index 55d55196d..4a6f3005e 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/SphereChunkOrderedPoiSetSpliterator.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/interests/iterator/SphereChunkOrderedPoiSetSpliterator.java @@ -48,7 +48,7 @@ public boolean tryAdvance(Consumer> action) { boolean progress = false; if (Distances.getMinChunkToBlockDistanceL2Sq(this.origin, this.chunkX, this.chunkZ) <= this.radiusSq) { //future work: filter sections with too high distance on the y axis as well - action.accept(this.storage.getWithinChunkColumn(this.chunkX, this.chunkZ)); + action.accept(this.storage.lithium$getWithinChunkColumn(this.chunkX, this.chunkZ)); progress = true; } diff --git a/src/main/java/me/jellysquid/mods/lithium/common/world/listeners/WorldBorderListenerOnce.java b/src/main/java/me/jellysquid/mods/lithium/common/world/listeners/WorldBorderListenerOnce.java index d13c4fe3f..7e8742c6e 100644 --- a/src/main/java/me/jellysquid/mods/lithium/common/world/listeners/WorldBorderListenerOnce.java +++ b/src/main/java/me/jellysquid/mods/lithium/common/world/listeners/WorldBorderListenerOnce.java @@ -5,25 +5,25 @@ public interface WorldBorderListenerOnce extends WorldBorderListener { - void onWorldBorderShapeChange(WorldBorder worldBorder); + void lithium$onWorldBorderShapeChange(WorldBorder worldBorder); default void onAreaReplaced(WorldBorder border) { - this.onWorldBorderShapeChange(border); + this.lithium$onWorldBorderShapeChange(border); } @Override default void onSizeChange(WorldBorder border, double size) { - this.onWorldBorderShapeChange(border); + this.lithium$onWorldBorderShapeChange(border); } @Override default void onInterpolateSize(WorldBorder border, double fromSize, double toSize, long time) { - this.onWorldBorderShapeChange(border); + this.lithium$onWorldBorderShapeChange(border); } @Override default void onCenterChanged(WorldBorder border, double centerX, double centerZ) { - this.onWorldBorderShapeChange(border); + this.lithium$onWorldBorderShapeChange(border); } @Override diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityMixin.java deleted file mode 100644 index 10fe84f0b..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityMixin.java +++ /dev/null @@ -1,31 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking; - -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerMulti; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerProvider; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityTracker; -import net.minecraft.entity.Entity; -import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Mixin; - -/** - * Extends the base living entity class to provide a {@link NearbyEntityListenerMulti} which will handle the - * child {@link NearbyEntityListenerProvider}s of AI tasks attached to this entity. - */ -@Mixin(Entity.class) -public class EntityMixin implements NearbyEntityListenerProvider { - private NearbyEntityListenerMulti tracker = null; - - @Override - @Nullable - public NearbyEntityListenerMulti getListener() { - return this.tracker; - } - - @Override - public void addListener(NearbyEntityTracker listener) { - if (this.tracker == null) { - this.tracker = new NearbyEntityListenerMulti(); - } - this.tracker.addListener(listener); - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityTrackingSectionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityTrackingSectionMixin.java deleted file mode 100644 index a2e70f88d..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/EntityTrackingSectionMixin.java +++ /dev/null @@ -1,101 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking; - -import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; -import me.jellysquid.mods.lithium.common.entity.PositionedEntityTrackingSection; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListener; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerSection; -import net.minecraft.entity.Entity; -import net.minecraft.util.collection.TypeFilterableList; -import net.minecraft.world.entity.EntityLike; -import net.minecraft.world.entity.EntityTrackingSection; -import net.minecraft.world.entity.EntityTrackingStatus; -import net.minecraft.world.entity.SectionedEntityCache; -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.ModifyVariable; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(EntityTrackingSection.class) -public abstract class EntityTrackingSectionMixin implements NearbyEntityListenerSection, PositionedEntityTrackingSection { - @Shadow - private EntityTrackingStatus status; - @Shadow - @Final - private TypeFilterableList collection; - - @Shadow - public abstract boolean isEmpty(); - - private final ReferenceOpenHashSet nearbyEntityListeners = new ReferenceOpenHashSet<>(0); - - @Override - public void addListener(NearbyEntityListener listener) { - this.nearbyEntityListeners.add(listener); - if (this.status.shouldTrack()) { - listener.onSectionEnteredRange(this, this.collection); - } - } - - @Override - public void removeListener(SectionedEntityCache sectionedEntityCache, NearbyEntityListener listener) { - boolean removed = this.nearbyEntityListeners.remove(listener); - if (this.status.shouldTrack() && removed) { - listener.onSectionLeftRange(this, this.collection); - } - if (this.isEmpty()) { - sectionedEntityCache.removeSection(this.getPos()); - } - } - - @Inject(method = "isEmpty()Z", at = @At(value = "HEAD"), cancellable = true) - public void isEmpty(CallbackInfoReturnable cir) { - if (!this.nearbyEntityListeners.isEmpty()) { - cir.setReturnValue(false); - } - } - - @Inject(method = "add(Lnet/minecraft/world/entity/EntityLike;)V", at = @At("RETURN")) - private void onEntityAdded(T entityLike, CallbackInfo ci) { - if (!this.status.shouldTrack() || this.nearbyEntityListeners.isEmpty()) { - return; - } - if (entityLike instanceof Entity entity) { - for (NearbyEntityListener nearbyEntityListener : this.nearbyEntityListeners) { - nearbyEntityListener.onEntityEnteredRange(entity); - } - } - } - - @Inject(method = "remove(Lnet/minecraft/world/entity/EntityLike;)Z", at = @At("RETURN")) - private void onEntityRemoved(T entityLike, CallbackInfoReturnable cir) { - if (this.status.shouldTrack() && !this.nearbyEntityListeners.isEmpty() && entityLike instanceof Entity entity) { - for (NearbyEntityListener nearbyEntityListener : this.nearbyEntityListeners) { - nearbyEntityListener.onEntityLeftRange(entity); - } - } - } - - @ModifyVariable(method = "swapStatus(Lnet/minecraft/world/entity/EntityTrackingStatus;)Lnet/minecraft/world/entity/EntityTrackingStatus;", at = @At(value = "HEAD"), argsOnly = true) - public EntityTrackingStatus swapStatus(final EntityTrackingStatus newStatus) { - if (this.status.shouldTrack() != newStatus.shouldTrack()) { - if (!newStatus.shouldTrack()) { - if (!this.nearbyEntityListeners.isEmpty()) { - for (NearbyEntityListener nearbyEntityListener : this.nearbyEntityListeners) { - nearbyEntityListener.onSectionLeftRange(this, this.collection); - } - } - } else { - if (!this.nearbyEntityListeners.isEmpty()) { - for (NearbyEntityListener nearbyEntityListener : this.nearbyEntityListeners) { - nearbyEntityListener.onSectionEnteredRange(this, this.collection); - } - } - } - } - return newStatus; - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerListenerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerListenerMixin.java deleted file mode 100644 index a49fbfcd9..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerListenerMixin.java +++ /dev/null @@ -1,75 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking; - -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerMulti; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerProvider; -import me.jellysquid.mods.lithium.common.util.tuples.Range6Int; -import me.jellysquid.mods.lithium.mixin.util.accessors.ServerEntityManagerAccessor; -import net.minecraft.entity.Entity; -import net.minecraft.server.world.ServerEntityManager; -import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.world.entity.EntityLike; -import net.minecraft.world.entity.EntityTrackingSection; -import net.minecraft.world.entity.EntityTrackingStatus; -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.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -@Mixin(targets = "net/minecraft/server/world/ServerEntityManager$Listener") -public class ServerEntityManagerListenerMixin { - @Shadow - @Final - private T entity; - - @Final - @SuppressWarnings("ShadowTarget") - @Shadow - ServerEntityManager manager; - - @Shadow - private long sectionPos; - - @Inject( - method = "updateEntityPosition()V", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/entity/EntityTrackingSection;add(Lnet/minecraft/world/entity/EntityLike;)V", - shift = At.Shift.AFTER - ), - locals = LocalCapture.CAPTURE_FAILHARD - ) - private void onUpdateEntityPosition(CallbackInfo ci, BlockPos blockPos, long newPos, EntityTrackingStatus entityTrackingStatus, EntityTrackingSection entityTrackingSection) { - NearbyEntityListenerMulti listener = ((NearbyEntityListenerProvider) this.entity).getListener(); - if (listener != null) - { - Range6Int chunkRange = listener.getChunkRange(); - //noinspection unchecked - listener.updateChunkRegistrations( - ((ServerEntityManagerAccessor) this.manager).getCache(), - ChunkSectionPos.from(this.sectionPos), chunkRange, - ChunkSectionPos.from(newPos), chunkRange - ); - } - } - - @Inject( - method = "remove(Lnet/minecraft/entity/Entity$RemovalReason;)V", - at = @At( - value = "HEAD" - ) - ) - private void onRemoveEntity(Entity.RemovalReason reason, CallbackInfo ci) { - NearbyEntityListenerMulti listener = ((NearbyEntityListenerProvider) this.entity).getListener(); - if (listener != null) { - //noinspection unchecked - listener.removeFromAllChunksInRange( - ((ServerEntityManagerAccessor) this.manager).getCache(), - ChunkSectionPos.from(this.sectionPos) - ); - } - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerMixin.java deleted file mode 100644 index be6a9819c..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/ServerEntityManagerMixin.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking; - -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerMulti; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerProvider; -import net.minecraft.server.world.ServerEntityManager; -import net.minecraft.util.math.ChunkSectionPos; -import net.minecraft.world.entity.EntityLike; -import net.minecraft.world.entity.SectionedEntityCache; -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.callback.CallbackInfoReturnable; - -@Mixin(ServerEntityManager.class) -public abstract class ServerEntityManagerMixin { - @Shadow - @Final - SectionedEntityCache cache; - - @Inject( - method = "addEntity(Lnet/minecraft/world/entity/EntityLike;Z)Z", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/entity/EntityLike;setChangeListener(Lnet/minecraft/world/entity/EntityChangeListener;)V", - shift = At.Shift.AFTER - ) - ) - private void onAddEntity(T entity, boolean existing, CallbackInfoReturnable cir) { - NearbyEntityListenerMulti listener = ((NearbyEntityListenerProvider) entity).getListener(); - if (listener != null) { - listener.addToAllChunksInRange( - this.cache, - ChunkSectionPos.from(entity.getBlockPos()) - ); - } - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/FleeEntityGoalMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/FleeEntityGoalMixin.java deleted file mode 100644 index 0c97cc756..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/FleeEntityGoalMixin.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking.goals; - -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerProvider; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityTracker; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityDimensions; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.ai.TargetPredicate; -import net.minecraft.entity.ai.goal.FleeEntityGoal; -import net.minecraft.entity.mob.PathAwareEntity; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -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 java.util.List; -import java.util.function.Predicate; - -@Mixin(FleeEntityGoal.class) -public class FleeEntityGoalMixin { - @Shadow - @Final - protected PathAwareEntity mob; - @Shadow - @Final - protected float fleeDistance; - private NearbyEntityTracker tracker; - - @Inject(method = "(Lnet/minecraft/entity/mob/PathAwareEntity;Ljava/lang/Class;Ljava/util/function/Predicate;FDDLjava/util/function/Predicate;)V", at = @At("RETURN")) - private void init(PathAwareEntity mob, Class fleeFromType, Predicate predicate, float distance, double slowSpeed, double fastSpeed, Predicate predicate2, CallbackInfo ci) { - EntityDimensions dimensions = this.mob.getType().getDimensions(); - double adjustedRange = dimensions.width * 0.5D + this.fleeDistance + 2D; - int horizontalRange = MathHelper.ceil(adjustedRange); - this.tracker = new NearbyEntityTracker<>(fleeFromType, mob, new Vec3i(horizontalRange, MathHelper.ceil(dimensions.height + 3 + 2), horizontalRange)); - - ((NearbyEntityListenerProvider) mob).addListener(this.tracker); - } - - @Redirect( - method = "canStart()Z", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/World;getClosestEntity(Ljava/util/List;Lnet/minecraft/entity/ai/TargetPredicate;Lnet/minecraft/entity/LivingEntity;DDD)Lnet/minecraft/entity/LivingEntity;" - ) - ) - private T redirectGetNearestEntity(World world, List entityList, TargetPredicate targetPredicate, LivingEntity entity, double x, double y, double z) { - return this.tracker.getClosestEntity(this.mob.getBoundingBox().expand(this.fleeDistance, 3.0D, this.fleeDistance), targetPredicate, x, y, z); - } - - @Redirect(method = "canStart()Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getEntitiesByClass(Ljava/lang/Class;Lnet/minecraft/util/math/Box;Ljava/util/function/Predicate;)Ljava/util/List;")) - private List redirectGetEntities(World world, Class entityClass, Box box, Predicate predicate) { - return null; - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/LookAtEntityGoalMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/LookAtEntityGoalMixin.java deleted file mode 100644 index 683592ebc..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/LookAtEntityGoalMixin.java +++ /dev/null @@ -1,73 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking.goals; - -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityListenerProvider; -import me.jellysquid.mods.lithium.common.entity.nearby_tracker.NearbyEntityTracker; -import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityDimensions; -import net.minecraft.entity.LivingEntity; -import net.minecraft.entity.ai.TargetPredicate; -import net.minecraft.entity.ai.goal.LookAtEntityGoal; -import net.minecraft.entity.mob.MobEntity; -import net.minecraft.entity.player.PlayerEntity; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.MathHelper; -import net.minecraft.util.math.Vec3i; -import net.minecraft.world.World; -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 java.util.List; -import java.util.function.Predicate; - -@Mixin(LookAtEntityGoal.class) -public class LookAtEntityGoalMixin { - @Shadow - @Final - protected MobEntity mob; - @Shadow - @Final - protected float range; - private NearbyEntityTracker tracker; - - @Inject(method = "(Lnet/minecraft/entity/mob/MobEntity;Ljava/lang/Class;FFZ)V", at = @At("RETURN")) - private void init(MobEntity mob, Class targetType, float range, float chance, boolean b, CallbackInfo ci) { - EntityDimensions dimensions = this.mob.getType().getDimensions(); - double adjustedRange = dimensions.width * 0.5D + this.range + 2D; - int horizontalRange = MathHelper.ceil(adjustedRange); - this.tracker = new NearbyEntityTracker<>(targetType, mob, new Vec3i(horizontalRange, MathHelper.ceil(dimensions.height + 3 + 2), horizontalRange)); - - ((NearbyEntityListenerProvider) mob).addListener(this.tracker); - } - - @Redirect( - method = "canStart()Z", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/World;getClosestEntity(Ljava/util/List;Lnet/minecraft/entity/ai/TargetPredicate;Lnet/minecraft/entity/LivingEntity;DDD)Lnet/minecraft/entity/LivingEntity;" - ) - ) - private LivingEntity redirectGetNearestEntity(World world, List entityList, TargetPredicate targetPredicate, LivingEntity entity, double x, double y, double z) { - return this.tracker.getClosestEntity(this.mob.getBoundingBox().expand(this.range, 3.0D, this.range), targetPredicate, x, y, z); - } - - @Redirect(method = "canStart()Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/World;getEntitiesByClass(Ljava/lang/Class;Lnet/minecraft/util/math/Box;Ljava/util/function/Predicate;)Ljava/util/List;")) - private List redirectGetEntities(World world, Class entityClass, Box box, Predicate predicate) { - return null; - } - - @Redirect( - method = "canStart()Z", - at = @At( - value = "INVOKE", - target = "Lnet/minecraft/world/World;getClosestPlayer(Lnet/minecraft/entity/ai/TargetPredicate;Lnet/minecraft/entity/LivingEntity;DDD)Lnet/minecraft/entity/player/PlayerEntity;" - ) - ) - private PlayerEntity redirectGetClosestPlayer(World world, TargetPredicate targetPredicate, LivingEntity entity, double x, double y, double z) { - return (PlayerEntity) this.tracker.getClosestEntity(null, targetPredicate, x, y, z); - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/package-info.java deleted file mode 100644 index 52cf5a221..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/goals/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -@MixinConfigOption( - description = """ - A number of AI goals which query for nearby entities in the world every tick will use the event-based - system for tracking nearby entities. In other words, instead of entities constantly polling to see if - other entities are nearby, they will instead be notified only occasionally when such an entity enters - their range. - """ -) -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking.goals; - -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/package-info.java deleted file mode 100644 index 403f4d318..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/nearby_entity_tracking/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -@MixinConfigOption( - description = """ - Event-based system for tracking nearby entities. - """, - depends = { - @MixinConfigDependency(dependencyPath = "mixin.util.entity_section_position"), - @MixinConfigDependency(dependencyPath = "mixin.util.accessors") - }, - enabled = false //Disabled, because mspt increase in normal worlds has been measured consistently -) -package me.jellysquid.mods.lithium.mixin.ai.nearby_entity_tracking; - -import net.caffeinemc.gradle.MixinConfigDependency; -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/AbstractBlockStateMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/AbstractBlockStateMixin.java index dd4b5326a..4fce16db3 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/AbstractBlockStateMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/AbstractBlockStateMixin.java @@ -6,6 +6,7 @@ import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.ai.pathing.LandPathNodeMaker; +import net.minecraft.entity.ai.pathing.PathContext; import net.minecraft.entity.ai.pathing.PathNodeType; import net.minecraft.util.math.BlockPos; import org.apache.commons.lang3.Validate; @@ -28,9 +29,9 @@ public abstract class AbstractBlockStateMixin implements BlockStatePathingCache BlockState state = this.asBlockState(); - SingleBlockBlockView blockView = SingleBlockBlockView.of(state, BlockPos.ORIGIN); + SingleBlockBlockView singleBlockBlockView = SingleBlockBlockView.of(state, BlockPos.ORIGIN); try { - this.pathNodeType = Validate.notNull(LandPathNodeMaker.getCommonNodeType(blockView, BlockPos.ORIGIN)); + this.pathNodeType = Validate.notNull(LandPathNodeMaker.getCommonNodeType(singleBlockBlockView, BlockPos.ORIGIN), "Block has no common path node type!"); } catch (SingleBlockBlockView.SingleBlockViewException | ClassCastException e) { //This is usually hit by shulker boxes, as their hitbox depends on the block entity, and the node type depends on the hitbox //Also catch ClassCastException in case some modded code casts BlockView to ChunkCache @@ -38,22 +39,23 @@ public abstract class AbstractBlockStateMixin implements BlockStatePathingCache } try { //Passing null as previous node type to the method signals to other lithium mixins that we only want the neighbor behavior of this block and not its neighbors - this.pathNodeTypeNeighbor = (LandPathNodeMaker.getNodeTypeFromNeighbors(blockView, BlockPos.ORIGIN.mutableCopy(), null)); + //Using exceptions for control flow, but this way we do not need to copy the code for the cache initialization, reducing required maintenance and improving mod compatibility + this.pathNodeTypeNeighbor = (LandPathNodeMaker.getNodeTypeFromNeighbors(new PathContext(singleBlockBlockView, null), 1, 1, 1, null)); if (this.pathNodeTypeNeighbor == null) { this.pathNodeTypeNeighbor = PathNodeType.OPEN; } - } catch (SingleBlockBlockView.SingleBlockViewException | ClassCastException e) { + } catch (SingleBlockBlockView.SingleBlockViewException | NullPointerException | ClassCastException e) { this.pathNodeTypeNeighbor = null; } } @Override - public PathNodeType getPathNodeType() { + public PathNodeType lithium$getPathNodeType() { return this.pathNodeType; } @Override - public PathNodeType getNeighborPathNodeType() { + public PathNodeType lithium$getNeighborPathNodeType() { return this.pathNodeTypeNeighbor; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/BirdPathNodeMakerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/BirdPathNodeMakerMixin.java index 9215ccdda..86c6d271f 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/BirdPathNodeMakerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/BirdPathNodeMakerMixin.java @@ -2,9 +2,8 @@ import me.jellysquid.mods.lithium.common.ai.pathing.PathNodeCache; import net.minecraft.entity.ai.pathing.BirdPathNodeMaker; +import net.minecraft.entity.ai.pathing.PathContext; import net.minecraft.entity.ai.pathing.PathNodeType; -import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; @@ -16,8 +15,8 @@ public class BirdPathNodeMakerMixin { * @reason Use optimized implementation which avoids scanning blocks for dangers where possible * @author JellySquid, 2No2Name */ - @Redirect(method = "getDefaultNodeType", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/ai/pathing/BirdPathNodeMaker;getNodeTypeFromNeighbors(Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos$Mutable;Lnet/minecraft/entity/ai/pathing/PathNodeType;)Lnet/minecraft/entity/ai/pathing/PathNodeType;")) - private PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mutable pos, PathNodeType type) { - return PathNodeCache.getNodeTypeFromNeighbors(world, pos, type); + @Redirect(method = "getDefaultNodeType", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/ai/pathing/BirdPathNodeMaker;getNodeTypeFromNeighbors(Lnet/minecraft/entity/ai/pathing/PathContext;IIILnet/minecraft/entity/ai/pathing/PathNodeType;)Lnet/minecraft/entity/ai/pathing/PathNodeType;")) + private PathNodeType getNodeTypeFromNeighbors(PathContext pathContext, int x, int y, int z, PathNodeType pathNodeType) { + return PathNodeCache.getNodeTypeFromNeighbors(pathContext, x, y, z, pathNodeType); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/LandPathNodeMakerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/LandPathNodeMakerMixin.java index f5f1fd7ca..0b5a7b270 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/LandPathNodeMakerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/LandPathNodeMakerMixin.java @@ -4,6 +4,7 @@ import me.jellysquid.mods.lithium.common.ai.pathing.PathNodeCache; import net.minecraft.block.BlockState; import net.minecraft.entity.ai.pathing.LandPathNodeMaker; +import net.minecraft.entity.ai.pathing.PathContext; import net.minecraft.entity.ai.pathing.PathNodeType; import net.minecraft.util.math.BlockPos; import net.minecraft.world.BlockView; @@ -23,12 +24,11 @@ @Mixin(value = LandPathNodeMaker.class, priority = 990) public abstract class LandPathNodeMakerMixin { /** - * This mixin requires a priority < 1000 due to fabric api using 1000 and we need to inject before them. + * This mixin requires a priority < 1000 due to fabric api using 1000 and us needing to inject before them. * * @reason Use optimized implementation * @author JellySquid, 2No2Name */ - @SuppressWarnings("InvalidInjectorMethodSignature") @Inject(method = "getCommonNodeType", at = @At( value = "INVOKE_ASSIGN", @@ -72,16 +72,14 @@ private static void getLithiumCachedCommonNodeType(BlockView world, BlockPos pos @Inject( method = "getNodeTypeFromNeighbors", locals = LocalCapture.CAPTURE_FAILHARD, at = @At( - value = "INVOKE", shift = At.Shift.AFTER, - target = "Lnet/minecraft/util/math/BlockPos$Mutable;set(III)Lnet/minecraft/util/math/BlockPos$Mutable;" + value = "INVOKE", shift = At.Shift.BEFORE, + target = "Lnet/minecraft/entity/ai/pathing/PathContext;getNodeType(III)Lnet/minecraft/entity/ai/pathing/PathNodeType;" ), cancellable = true ) - private static void doNotChangePositionIfLithiumSinglePosCall(BlockView world, BlockPos.Mutable pos, PathNodeType nodeType, CallbackInfoReturnable cir, int posX, int posY, int posZ, int dX, int dY, int dZ) { - if (nodeType == null) { - if (dX == -1 && dY == -1 && dZ == -1) { - pos.set(posX, posY, posZ); - } else { + private static void doNotIteratePositionsIfLithiumSinglePosCall(PathContext context, int x, int y, int z, PathNodeType fallback, CallbackInfoReturnable cir) { + if (fallback == null) { + if (x != -1 || y != -1 || z != -1) { cir.setReturnValue(null); } } @@ -91,8 +89,8 @@ private static void doNotChangePositionIfLithiumSinglePosCall(BlockView world, B * @reason Use optimized implementation which avoids scanning blocks for dangers where possible * @author JellySquid, 2No2Name */ - @Redirect(method = "getLandNodeType", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/ai/pathing/LandPathNodeMaker;getNodeTypeFromNeighbors(Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos$Mutable;Lnet/minecraft/entity/ai/pathing/PathNodeType;)Lnet/minecraft/entity/ai/pathing/PathNodeType;")) - private static PathNodeType getNodeTypeFromNeighbors(BlockView world, BlockPos.Mutable pos, PathNodeType type) { - return PathNodeCache.getNodeTypeFromNeighbors(world, pos, type); + @Redirect(method = "getLandNodeType(Lnet/minecraft/entity/ai/pathing/PathContext;Lnet/minecraft/util/math/BlockPos$Mutable;)Lnet/minecraft/entity/ai/pathing/PathNodeType;", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/ai/pathing/LandPathNodeMaker;getNodeTypeFromNeighbors(Lnet/minecraft/entity/ai/pathing/PathContext;IIILnet/minecraft/entity/ai/pathing/PathNodeType;)Lnet/minecraft/entity/ai/pathing/PathNodeType;")) + private static PathNodeType getNodeTypeFromNeighbors(PathContext context, int x, int y, int z, PathNodeType fallback) { + return PathNodeCache.getNodeTypeFromNeighbors(context, x, y, z, fallback); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextAccessor.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextAccessor.java new file mode 100644 index 000000000..77c6ec7ef --- /dev/null +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextAccessor.java @@ -0,0 +1,14 @@ +package me.jellysquid.mods.lithium.mixin.ai.pathing; + +import net.minecraft.entity.ai.pathing.PathContext; +import net.minecraft.util.math.BlockPos; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + +@Mixin(PathContext.class) +public interface PathContextAccessor { + + @Accessor + BlockPos.Mutable getLastNodePos(); + +} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextMixin.java new file mode 100644 index 000000000..14a9d1850 --- /dev/null +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/pathing/PathContextMixin.java @@ -0,0 +1,36 @@ +package me.jellysquid.mods.lithium.mixin.ai.pathing; + +import com.llamalad7.mixinextras.injector.wrapoperation.Operation; +import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation; +import net.minecraft.entity.ai.pathing.PathContext; +import net.minecraft.entity.mob.MobEntity; +import net.minecraft.util.math.BlockPos; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; + +@Mixin(PathContext.class) +public class PathContextMixin { + + @WrapOperation( + method = "", + at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/mob/MobEntity;getWorld()Lnet/minecraft/world/World;") + ) + private World getWorldIfNonNull(MobEntity instance, Operation original) { + if (instance == null) { + return null; + } + return original.call(instance); + } + + @WrapOperation( + method = "", + at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/mob/MobEntity;getBlockPos()Lnet/minecraft/util/math/BlockPos;") + ) + private BlockPos getBlockPosIfNonNull(MobEntity instance, Operation original) { + if (instance == null) { + return null; + } + return original.call(instance); + } +} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestSetMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestSetMixin.java index 813d52fbe..958313cd4 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestSetMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestSetMixin.java @@ -48,7 +48,7 @@ private void reinit(Runnable updateListener, boolean bl, List l } @Override - public void collectMatchingPoints(Predicate> type, PointOfInterestStorage.OccupationStatus status, Consumer consumer) { + public void lithium$collectMatchingPoints(Predicate> type, PointOfInterestStorage.OccupationStatus status, Consumer consumer) { if (type instanceof SinglePointOfInterestTypeFilter) { this.getWithSingleTypeFilter(((SinglePointOfInterestTypeFilter) type).getType(), status, consumer); } else { diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestStorageMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestStorageMixin.java index 457483ed0..6c22a45c5 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestStorageMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/PointOfInterestStorageMixin.java @@ -1,6 +1,5 @@ package me.jellysquid.mods.lithium.mixin.ai.poi; -import com.mojang.datafixers.DataFixer; import com.mojang.serialization.Codec; import me.jellysquid.mods.lithium.common.util.Distances; import me.jellysquid.mods.lithium.common.world.interests.PointOfInterestSetExtended; @@ -9,7 +8,6 @@ import me.jellysquid.mods.lithium.common.world.interests.iterator.NearbyPointOfInterestStream; import me.jellysquid.mods.lithium.common.world.interests.iterator.SinglePointOfInterestTypeFilter; import me.jellysquid.mods.lithium.common.world.interests.iterator.SphereChunkOrderedPoiSetSpliterator; -import net.minecraft.datafixer.DataFixTypes; import net.minecraft.registry.DynamicRegistryManager; import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.util.annotation.Debug; @@ -24,13 +22,13 @@ import net.minecraft.world.poi.PointOfInterestSet; import net.minecraft.world.poi.PointOfInterestStorage; import net.minecraft.world.poi.PointOfInterestType; +import net.minecraft.world.storage.ChunkPosKeyedStorage; import net.minecraft.world.storage.SerializingRegionBasedStorage; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Optional; import java.util.function.BiConsumer; @@ -44,8 +42,9 @@ public abstract class PointOfInterestStorageMixin extends SerializingRegionBasedStorage implements PointOfInterestStorageExtended { - public PointOfInterestStorageMixin(Path path, Function> codecFactory, Function factory, DataFixer dataFixer, DataFixTypes dataFixTypes, boolean dsync, DynamicRegistryManager dynamicRegistryManager, HeightLimitView world) { - super(path, codecFactory, factory, dataFixer, dataFixTypes, dsync, dynamicRegistryManager, world); + + public PointOfInterestStorageMixin(ChunkPosKeyedStorage storageAccess, Function> codecFactory, Function factory, DynamicRegistryManager registryManager, HeightLimitView world) { + super(storageAccess, codecFactory, factory, registryManager, world); } /** @@ -58,7 +57,7 @@ public PointOfInterestStorageMixin(Path path, Function getInChunk(Predicate> predicate, ChunkPos pos, PointOfInterestStorage.OccupationStatus status) { return ((RegionBasedStorageSectionExtended) this) - .getWithinChunkColumn(pos.x, pos.z) + .lithium$getWithinChunkColumn(pos.x, pos.z) .flatMap(set -> set.get(predicate, status)); } @@ -143,9 +142,9 @@ public Stream getInCircle(Predicate findNearestForPortalLogic(BlockPos origin, int radius, RegistryEntry type, - PointOfInterestStorage.OccupationStatus status, - Predicate afterSortPredicate, WorldBorder worldBorder) { + public Optional lithium$findNearestForPortalLogic(BlockPos origin, int radius, RegistryEntry type, + PointOfInterestStorage.OccupationStatus status, + Predicate afterSortPredicate, WorldBorder worldBorder) { // Order of the POI: // return closest accepted POI (L2 distance). If several exist: // return the one with most negative Y. If several exist: @@ -201,8 +200,8 @@ private ArrayList withinSphereChunkSectionSorted(Predicate implements RegionBas @SuppressWarnings("rawtypes") @Inject(method = "", at = @At("RETURN")) - private void init(Path path, Function codecFactory, Function factory, DataFixer dataFixer, DataFixTypes dataFixTypes, boolean dsync, DynamicRegistryManager dynamicRegistryManager, HeightLimitView world, CallbackInfo ci) { + private void init(ChunkPosKeyedStorage storageAccess, Function codecFactory, Function factory, DynamicRegistryManager registryManager, HeightLimitView world, CallbackInfo ci) { this.columns = new Long2ObjectOpenHashMap<>(); this.loadedElements = new ListeningLong2ObjectOpenHashMap<>(this::onEntryAdded, this::onEntryRemoved); } @@ -97,7 +95,7 @@ private void onEntryAdded(long key, Optional value) { } @Override - public Stream getWithinChunkColumn(int chunkX, int chunkZ) { + public Stream lithium$getWithinChunkColumn(int chunkX, int chunkZ) { BitSet sectionsWithPOI = this.getNonEmptyPOISections(chunkX, chunkZ); // No items are present in this column @@ -120,7 +118,7 @@ public Stream getWithinChunkColumn(int chunkX, int chunkZ) { } @Override - public Iterable getInChunkColumn(int chunkX, int chunkZ) { + public Iterable lithium$getInChunkColumn(int chunkX, int chunkZ) { BitSet sectionsWithPOI = this.getNonEmptyPOISections(chunkX, chunkZ); // No items are present in this column diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PointOfInterestStorageMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PointOfInterestStorageMixin.java index ad602884e..382266880 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PointOfInterestStorageMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PointOfInterestStorageMixin.java @@ -1,9 +1,8 @@ package me.jellysquid.mods.lithium.mixin.ai.poi.fast_portals; -import com.mojang.datafixers.DataFixer; +import com.mojang.serialization.Codec; import it.unimi.dsi.fastutil.longs.LongOpenHashSet; import it.unimi.dsi.fastutil.longs.LongSet; -import net.minecraft.datafixer.DataFixTypes; import net.minecraft.registry.DynamicRegistryManager; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; @@ -13,11 +12,12 @@ import net.minecraft.world.chunk.ChunkStatus; import net.minecraft.world.poi.PointOfInterestSet; import net.minecraft.world.poi.PointOfInterestStorage; +import net.minecraft.world.storage.ChunkPosKeyedStorage; import net.minecraft.world.storage.SerializingRegionBasedStorage; import org.spongepowered.asm.mixin.*; -import java.nio.file.Path; import java.util.Optional; +import java.util.function.Function; @Mixin(PointOfInterestStorage.class) public abstract class PointOfInterestStorageMixin extends SerializingRegionBasedStorage { @@ -31,14 +31,8 @@ public abstract class PointOfInterestStorageMixin extends SerializingRegionBased @Unique private int preloadRadius = 0; - public PointOfInterestStorageMixin( - Path path, DataFixer dataFixer, boolean dsync, - DynamicRegistryManager registryManager, HeightLimitView world - ) { - super( - path, PointOfInterestSet::createCodec, PointOfInterestSet::new, - dataFixer, DataFixTypes.POI_CHUNK, dsync, registryManager, world - ); + public PointOfInterestStorageMixin(ChunkPosKeyedStorage storageAccess, Function> codecFactory, Function factory, DynamicRegistryManager registryManager, HeightLimitView world) { + super(storageAccess, codecFactory, factory, registryManager, world); } /** diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PortalForcerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PortalForcerMixin.java index 4e6b3e463..dbaad52db 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PortalForcerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/poi/fast_portals/PortalForcerMixin.java @@ -39,7 +39,7 @@ public Optional getPortalRect(BlockPos centerPos, boole PointOfInterestStorage poiStorage = this.world.getPointOfInterestStorage(); poiStorage.preloadChunks(this.world, centerPos, searchRadius); - Optional ret = ((PointOfInterestStorageExtended) poiStorage).findNearestForPortalLogic(centerPos, searchRadius, + Optional ret = ((PointOfInterestStorageExtended) poiStorage).lithium$findNearestForPortalLogic(centerPos, searchRadius, POIRegistryEntries.NETHER_PORTAL_ENTRY, PointOfInterestStorage.OccupationStatus.ANY, (poi) -> this.world.getBlockState(poi.getPos()).contains(Properties.HORIZONTAL_AXIS), worldBorder diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/PickupBannerAsLeaderGoalMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/PickupBannerAsLeaderGoalMixin.java index 0b33af889..bcdeb034a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/PickupBannerAsLeaderGoalMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/PickupBannerAsLeaderGoalMixin.java @@ -1,25 +1,31 @@ package me.jellysquid.mods.lithium.mixin.ai.raid; +import me.jellysquid.mods.lithium.common.ai.raid.OminousBannerCache; +import net.minecraft.block.entity.BannerPattern; import net.minecraft.entity.raid.RaiderEntity; import net.minecraft.item.ItemStack; -import net.minecraft.village.raid.Raid; +import net.minecraft.registry.RegistryEntryLookup; +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.Redirect; @Mixin(RaiderEntity.PickupBannerAsLeaderGoal.class) -public class PickupBannerAsLeaderGoalMixin { - // The call to Raid#getOminousBanner() is very expensive, so cache it and re-use it during AI ticking - private static final ItemStack CACHED_OMINOUS_BANNER = Raid.getOminousBanner(); +public class PickupBannerAsLeaderGoalMixin { + @Shadow + @Final + private T actor; + // The call to Raid#getOminousBanner() is very expensive, use a cached banner during AI ticking @Redirect( method = "canStart()Z", at = @At( value = "INVOKE", - target = "Lnet/minecraft/village/raid/Raid;getOminousBanner()Lnet/minecraft/item/ItemStack;" + target = "Lnet/minecraft/village/raid/Raid;getOminousBanner(Lnet/minecraft/registry/RegistryEntryLookup;)Lnet/minecraft/item/ItemStack;" ) ) - private ItemStack getOminousBanner() { - return CACHED_OMINOUS_BANNER; + private ItemStack getOminousBanner(RegistryEntryLookup bannerPatternLookup) { + return ((OminousBannerCache) this.actor.getWorld()).lithium$getCachedOminousBanner(); } } \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/RaiderEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/RaiderEntityMixin.java index 8fab93237..951a68ca1 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/RaiderEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/RaiderEntityMixin.java @@ -1,9 +1,14 @@ package me.jellysquid.mods.lithium.mixin.ai.raid; +import me.jellysquid.mods.lithium.common.ai.raid.OminousBannerCache; +import net.minecraft.block.entity.BannerPattern; +import net.minecraft.entity.Entity; +import net.minecraft.entity.EntityType; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.raid.RaiderEntity; import net.minecraft.item.ItemStack; -import net.minecraft.village.raid.Raid; +import net.minecraft.registry.RegistryEntryLookup; +import net.minecraft.world.World; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; @@ -14,23 +19,27 @@ import java.util.function.Predicate; @Mixin(RaiderEntity.class) -public class RaiderEntityMixin { - // The call to Raid#getOminousBanner() is very expensive, so cache it and re-use it during AI ticking - private static final ItemStack CACHED_OMINOUS_BANNER = Raid.getOminousBanner(); +public abstract class RaiderEntityMixin extends Entity { @Mutable @Shadow @Final static Predicate OBTAINABLE_OMINOUS_BANNER_PREDICATE; static { - OBTAINABLE_OMINOUS_BANNER_PREDICATE = (itemEntity) -> !itemEntity.cannotPickup() && itemEntity.isAlive() && ItemStack.areEqual(itemEntity.getStack(), CACHED_OMINOUS_BANNER); + // The call to Raid#getOminousBanner() is very expensive, use a cached banner during AI ticking + OBTAINABLE_OMINOUS_BANNER_PREDICATE = (itemEntity) -> !itemEntity.cannotPickup() && itemEntity.isAlive() && + ItemStack.areEqual(itemEntity.getStack(), ((OminousBannerCache) itemEntity.getWorld()).lithium$getCachedOminousBanner()); + } + + public RaiderEntityMixin(EntityType type, World world) { + super(type, world); } @Redirect( method = "onDeath(Lnet/minecraft/entity/damage/DamageSource;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/village/raid/Raid;getOminousBanner()Lnet/minecraft/item/ItemStack;") + at = @At(value = "INVOKE", target = "Lnet/minecraft/village/raid/Raid;getOminousBanner(Lnet/minecraft/registry/RegistryEntryLookup;)Lnet/minecraft/item/ItemStack;") ) - private ItemStack getOminousBanner() { - return CACHED_OMINOUS_BANNER; + private ItemStack getOminousBanner(RegistryEntryLookup bannerPatternLookup) { + return ((OminousBannerCache) this.getWorld()).lithium$getCachedOminousBanner(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/WorldMixin.java new file mode 100644 index 000000000..f3156483f --- /dev/null +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/raid/WorldMixin.java @@ -0,0 +1,39 @@ +package me.jellysquid.mods.lithium.mixin.ai.raid; + +import me.jellysquid.mods.lithium.common.ai.raid.OminousBannerCache; +import net.minecraft.item.ItemStack; +import net.minecraft.registry.DynamicRegistryManager; +import net.minecraft.registry.RegistryKey; +import net.minecraft.registry.RegistryKeys; +import net.minecraft.registry.entry.RegistryEntry; +import net.minecraft.village.raid.Raid; +import net.minecraft.world.MutableWorldProperties; +import net.minecraft.world.World; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Unique; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; + +import java.util.function.Supplier; + +@Mixin(World.class) +public abstract class WorldMixin implements OminousBannerCache { + + // The call to Raid#getOminousBanner() is very expensive, so cache it and re-use it during AI ticking + @Unique + private ItemStack cachedOminousBanner; + + @Inject( + method = "", + at = @At("RETURN") + ) + protected void initCachedOminousBanner(MutableWorldProperties properties, RegistryKey registryRef, DynamicRegistryManager registryManager, RegistryEntry dimensionEntry, Supplier profiler, boolean isClient, boolean debugWorld, long biomeAccess, int maxChainedNeighborUpdates, CallbackInfo ci) { + this.cachedOminousBanner = Raid.getOminousBanner(registryManager.getWrapperOrThrow(RegistryKeys.BANNER_PATTERN)); + } + + @Override + public ItemStack lithium$getCachedOminousBanner() { + return cachedOminousBanner; + } +} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/BrainMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/BrainMixin.java index 7b26a9e53..8019c01a2 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/BrainMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/BrainMixin.java @@ -32,7 +32,7 @@ private Object increaseMemoryModificationCount(Map map, Object k } @Override - public long getModCount() { + public long lithium$getModCount() { return memoryModCount; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/MultiTickTaskMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/MultiTickTaskMixin.java index 2f6efa4e9..12c5bc826 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/MultiTickTaskMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/ai/task/memory_change_counting/MultiTickTaskMixin.java @@ -40,7 +40,7 @@ private void init(Map, MemoryModuleState> map, int int_1, in @Overwrite public boolean hasRequiredMemoryState(E entity) { Brain brain = entity.getBrain(); - long modCount = ((MemoryModificationCounter) brain).getModCount(); + long modCount = ((MemoryModificationCounter) brain).lithium$getModCount(); if (this.cachedMemoryModCount == modCount) { return this.cachedHasRequiredMemoryState; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/ServerWorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/ServerWorldMixin.java index a61b3d40d..0d2e02b29 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/ServerWorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/ServerWorldMixin.java @@ -25,7 +25,7 @@ public abstract class ServerWorldMixin { ) ) private BlockPos redirectTickGetRandomPosInChunk(ServerWorld serverWorld, int x, int y, int z, int mask) { - ((ChunkRandomSource) serverWorld).getRandomPosInChunk(x, y, z, mask, this.randomPosInChunkCachedPos); + ((ChunkRandomSource) serverWorld).lithium$getRandomPosInChunk(x, y, z, mask, this.randomPosInChunkCachedPos); return this.randomPosInChunkCachedPos; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/WorldMixin.java index e4211795f..1a3f62c70 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/WorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/alloc/chunk_random/WorldMixin.java @@ -15,7 +15,7 @@ public class WorldMixin implements ChunkRandomSource { * {@inheritDoc} */ @Override - public void getRandomPosInChunk(int x, int y, int z, int mask, BlockPos.Mutable out) { + public void lithium$getRandomPosInChunk(int x, int y, int z, int mask, BlockPos.Mutable out) { this.lcgBlockSeed = this.lcgBlockSeed * 3 + 1013904223; int rand = this.lcgBlockSeed >> 2; out.set(x + (rand & 15), y + (rand >> 16 & mask), z + (rand >> 8 & 15)); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/flatten_states/FluidStateMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/flatten_states/FluidStateMixin.java index 93c8e5256..74ae45ce4 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/flatten_states/FluidStateMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/flatten_states/FluidStateMixin.java @@ -1,10 +1,9 @@ package me.jellysquid.mods.lithium.mixin.block.flatten_states; -import com.google.common.collect.ImmutableMap; import com.mojang.serialization.MapCodec; +import it.unimi.dsi.fastutil.objects.Reference2ObjectArrayMap; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.FluidState; -import net.minecraft.state.property.Property; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow; @@ -19,9 +18,8 @@ public abstract class FluidStateMixin { private boolean isEmptyCache; - @Inject(method = "(Lnet/minecraft/fluid/Fluid;Lcom/google/common/collect/ImmutableMap;Lcom/mojang/serialization/MapCodec;)V", at = @At("RETURN")) - private void initFluidCache(Fluid fluid, ImmutableMap, Comparable> propertyMap, - MapCodec codec, CallbackInfo ci) { + @Inject(method = "", at = @At("RETURN")) + private void initFluidCache(Fluid fluid, Reference2ObjectArrayMap propertyMap, MapCodec codec, CallbackInfo ci) { this.isEmptyCache = this.getFluid().isEmpty(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/AbstractMinecartEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/AbstractMinecartEntityMixin.java index d50e42e48..45273d76a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/AbstractMinecartEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/AbstractMinecartEntityMixin.java @@ -34,7 +34,7 @@ private void avoidNotifyingMovementListeners(BlockPos pos, BlockState state, Cal this.beforeMoveOnRailPos = this.getPos(); EntityChangeListener changeListener = ((EntityAccessor) this).getChangeListener(); if (changeListener instanceof ToggleableMovementTracker toggleableMovementTracker) { - this.beforeMoveOnRailNotificationMask = toggleableMovementTracker.setNotificationMask(0); + this.beforeMoveOnRailNotificationMask = toggleableMovementTracker.lithium$setNotificationMask(0); } } } @@ -47,7 +47,7 @@ private void notifyMovementListeners(BlockPos pos, BlockState state, CallbackInf if (this instanceof Inventory) { EntityChangeListener changeListener = ((EntityAccessor) this).getChangeListener(); if (changeListener instanceof ToggleableMovementTracker toggleableMovementTracker) { - this.beforeMoveOnRailNotificationMask = toggleableMovementTracker.setNotificationMask(this.beforeMoveOnRailNotificationMask); + this.beforeMoveOnRailNotificationMask = toggleableMovementTracker.lithium$setNotificationMask(this.beforeMoveOnRailNotificationMask); if (!this.beforeMoveOnRailPos.equals(this.getPos())) { changeListener.updateEntityPosition(); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/ChestBoatEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/ChestBoatEntityMixin.java index ed7999f07..39ca7f23d 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/ChestBoatEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/ChestBoatEntityMixin.java @@ -34,11 +34,11 @@ private void tickRidingSummarizeMovementNotifications(Entity entity) { EntityChangeListener changeListener = ((EntityAccessor) this).getChangeListener(); if (changeListener instanceof ToggleableMovementTracker toggleableMovementTracker) { Vec3d beforeTickPos = this.getPos(); - int beforeMovementNotificationMask = toggleableMovementTracker.setNotificationMask(0); + int beforeMovementNotificationMask = toggleableMovementTracker.lithium$setNotificationMask(0); super.tickRiding(); - toggleableMovementTracker.setNotificationMask(beforeMovementNotificationMask); + toggleableMovementTracker.lithium$setNotificationMask(beforeMovementNotificationMask); if (!beforeTickPos.equals(this.getPos())) { changeListener.updateEntityPosition(); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockEntityMixin.java index c84992c5d..f7c25dc1b 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockEntityMixin.java @@ -29,19 +29,15 @@ import net.minecraft.util.math.Direction; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; -import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; 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.ModifyVariable; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; -import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -56,10 +52,6 @@ public HopperBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState super(type, pos, state); } - @Shadow - @Nullable - private static native Inventory getInputInventory(World world, Hopper hopper); - @Shadow protected abstract boolean isDisabled(); @@ -85,8 +77,7 @@ public HopperBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState private SectionedItemEntityMovementTracker collectItemEntityTracker; private boolean collectItemEntityTrackerWasEmpty; - //item pickup bounding boxes in order. The last box in the array is the box that encompasses all of the others - private Box[] collectItemEntityBoxes; + private Box collectItemEntityBox; private long collectItemEntityAttemptTime; private SectionedInventoryEntityMovementTracker extractInventoryEntityTracker; @@ -99,13 +90,13 @@ public HopperBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState private boolean shouldCheckSleep; - @Redirect(method = "extract(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/HopperBlockEntity;getInputInventory(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Lnet/minecraft/inventory/Inventory;")) - private static Inventory getExtractInventory(World world, Hopper hopper) { + @Redirect(method = "extract(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/HopperBlockEntity;getInputInventory(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Lnet/minecraft/inventory/Inventory;")) + private static Inventory getExtractInventory(World world, Hopper hopper, BlockPos extractBlockPos, BlockState extractBlockState) { if (!(hopper instanceof HopperBlockEntityMixin hopperBlockEntity)) { - return getInputInventory(world, hopper); //Hopper Minecarts do not cache Inventories + return getInputInventory(world, hopper, extractBlockPos, extractBlockState); //Hopper Minecarts do not cache Inventories } - Inventory blockInventory = hopperBlockEntity.getExtractBlockInventory(world); + Inventory blockInventory = hopperBlockEntity.getExtractBlockInventory(world, extractBlockPos, extractBlockState); if (blockInventory != null) { return blockInventory; } @@ -148,19 +139,20 @@ private static Inventory getExtractInventory(World world, Hopper hopper) { @SuppressWarnings("JavadocReference") @Inject( cancellable = true, - method = "ejectItems", + method = "insert(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/entity/HopperBlockEntity;)Z", at = @At( value = "INVOKE", shift = At.Shift.BEFORE, target = "Lnet/minecraft/block/entity/HopperBlockEntity;isInventoryFull(Lnet/minecraft/inventory/Inventory;Lnet/minecraft/util/math/Direction;)Z" ), locals = LocalCapture.CAPTURE_FAILHARD ) - private static void lithiumInsert(World world, BlockPos pos, BlockState hopperState, HopperBlockEntity hopper, CallbackInfoReturnable cir, Inventory insertInventory, Direction direction) { - if (insertInventory == null || !(hopper instanceof HopperBlockEntity) || hopper instanceof SidedInventory) { + private static void lithiumInsert(World world, BlockPos pos, HopperBlockEntity blockEntity, CallbackInfoReturnable cir, Inventory insertInventory, Direction direction) { + if (insertInventory == null || !(blockEntity instanceof HopperBlockEntity) || blockEntity instanceof SidedInventory) { //call the vanilla code to allow other mods inject features //e.g. carpet mod allows hoppers to insert items into wool blocks return; } - HopperBlockEntityMixin hopperBlockEntity = (HopperBlockEntityMixin) (Object) hopper; + + HopperBlockEntityMixin hopperBlockEntity = (HopperBlockEntityMixin) (Object) blockEntity; LithiumStackList hopperStackList = InventoryHelper.getLithiumStackList(hopperBlockEntity); if (hopperBlockEntity.insertInventory == insertInventory && hopperStackList.getModCount() == hopperBlockEntity.myModCountAtLastInsert) { @@ -184,7 +176,7 @@ private static void lithiumInsert(World world, BlockPos pos, BlockState hopperSt //noinspection ConstantConditions if (!(hopperBlockEntity.insertInventory == insertInventory && hopperBlockEntity.insertStackList.getFullSlots() == hopperBlockEntity.insertStackList.size())) { - Direction fromDirection = hopperState.get(HopperBlock.FACING).getOpposite(); + Direction fromDirection = hopperBlockEntity.facing.getOpposite(); int size = hopperStackList.size(); //noinspection ForLoopReplaceableByForEach for (int i = 0; i < size; ++i) { @@ -225,7 +217,7 @@ private static void lithiumInsert(World world, BlockPos pos, BlockState hopperSt * @param from Inventory the hopper is extracting from */ @Inject(method = "extract(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Z", at = @At(value = "FIELD", target = "Lnet/minecraft/util/math/Direction;DOWN:Lnet/minecraft/util/math/Direction;", shift = At.Shift.AFTER), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD) - private static void lithiumExtract(World world, Hopper to, CallbackInfoReturnable cir, Boolean unUsed, Inventory from) { + private static void lithiumExtract(World world, Hopper to, CallbackInfoReturnable cir, BlockPos blockPos, BlockState blockState, Boolean unUsed, Inventory from) { if (!(to instanceof HopperBlockEntityMixin hopperBlockEntity)) { return; //optimizations not implemented for hopper minecarts } @@ -238,7 +230,7 @@ private static void lithiumExtract(World world, Hopper to, CallbackInfoReturnabl if (hopperStackList.getModCount() == hopperBlockEntity.myModCountAtLastExtract) { if (fromStackList.getModCount() == hopperBlockEntity.extractStackListModCount) { - if (!(from instanceof ComparatorTracker comparatorTracker) || comparatorTracker.hasAnyComparatorNearby()) { + if (!(from instanceof ComparatorTracker comparatorTracker) || comparatorTracker.lithium$hasAnyComparatorNearby()) { //noinspection CollectionAddedToSelf fromStackList.runComparatorUpdatePatternOnFailedExtract(fromStackList, from); } @@ -316,8 +308,19 @@ private static boolean lithiumHopperIsEmpty(HopperBlockEntity hopperBlockEntity) @Shadow private static native boolean canExtract(Inventory hopperInventory, Inventory fromInventory, ItemStack stack, int slot, Direction facing); + @Shadow + private Direction facing; + + @Shadow + @Nullable + private static native Inventory getBlockInventoryAt(World world, BlockPos pos, BlockState state); + + @Shadow + @Nullable + protected static native Inventory getInputInventory(World world, Hopper hopper, BlockPos pos, BlockState state); + @Override - public void invalidateCacheOnNeighborUpdate(boolean fromAbove) { + public void lithium$invalidateCacheOnNeighborUpdate(boolean fromAbove) { //Clear the block inventory cache (composter inventories and no inventory present) on block update / observer update if (fromAbove) { if (this.extractionMode == HopperCachingState.BlockInventory.NO_BLOCK_INVENTORY || this.extractionMode == HopperCachingState.BlockInventory.BLOCK_STATE) { @@ -331,28 +334,18 @@ public void invalidateCacheOnNeighborUpdate(boolean fromAbove) { } @Override - public void invalidateCacheOnNeighborUpdate(Direction fromDirection) { + public void lithium$invalidateCacheOnNeighborUpdate(Direction fromDirection) { boolean fromAbove = fromDirection == Direction.UP; if (fromAbove || this.getCachedState().get(HopperBlock.FACING) == fromDirection) { - this.invalidateCacheOnNeighborUpdate(fromAbove); + this.lithium$invalidateCacheOnNeighborUpdate(fromAbove); } } - @Redirect(method = "ejectItems", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/HopperBlockEntity;getOutputInventory(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Lnet/minecraft/inventory/Inventory;")) - private static Inventory nullify(World world, BlockPos pos, BlockState state) { - return null; - } - @ModifyVariable( - method = "ejectItems", - at = @At( - value = "INVOKE_ASSIGN", - target = "Lnet/minecraft/block/entity/HopperBlockEntity;getOutputInventory(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;)Lnet/minecraft/inventory/Inventory;" - ) - ) - private static Inventory getLithiumOutputInventory(Inventory inventory, World world, BlockPos pos, BlockState hopperState, HopperBlockEntity hopper) { - HopperBlockEntityMixin hopperBlockEntity = (HopperBlockEntityMixin) (Object) hopper; - return hopperBlockEntity.getInsertInventory(world, hopperState); + @Redirect(method = "insert(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/entity/HopperBlockEntity;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/HopperBlockEntity;getOutputInventory(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/entity/HopperBlockEntity;)Lnet/minecraft/inventory/Inventory;")) + private static Inventory getLithiumOutputInventory(World world, BlockPos pos, HopperBlockEntity blockEntity) { + HopperBlockEntityMixin hopperBlockEntity = (HopperBlockEntityMixin) (Object) blockEntity; + return hopperBlockEntity.getInsertInventory(world); } @Redirect(method = "extract(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Z", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/entity/HopperBlockEntity;getInputItemEntities(Lnet/minecraft/world/World;Lnet/minecraft/block/entity/Hopper;)Ljava/util/List;")) @@ -373,7 +366,7 @@ private static List lithiumGetInputItemEntities(World world, Hopper hopperBlockEntity.myModCountAtLastItemCollect = modCount; hopperBlockEntity.shouldCheckSleep = false; - List itemEntities = hopperBlockEntity.collectItemEntityTracker.getEntities(hopperBlockEntity.collectItemEntityBoxes); + List itemEntities = hopperBlockEntity.collectItemEntityTracker.getEntities(hopperBlockEntity.collectItemEntityBox); hopperBlockEntity.collectItemEntityAttemptTime = hopperBlockEntity.lastTickTime; hopperBlockEntity.collectItemEntityTrackerWasEmpty = itemEntities.isEmpty(); //set unchanged so that if this extract fails and there is no other change to hoppers or items, extracting @@ -429,23 +422,6 @@ private void cacheExtractLithiumInventory(LithiumInventory optimizedInventory) { this.extractStackListModCount = extractInventoryStackList.getModCount() - 1; } - /** - * @author 2No2Name - * @reason avoid stream code - */ - @Overwrite - private static boolean isInventoryEmpty(Inventory inv, Direction side) { - int[] availableSlots = inv instanceof SidedInventory ? ((SidedInventory) inv).getAvailableSlots(side) : null; - int fromSize = availableSlots != null ? availableSlots.length : inv.size(); - for (int i = 0; i < fromSize; i++) { - int slot = availableSlots != null ? availableSlots[i] : i; - if (!inv.getStack(slot).isEmpty()) { - return false; - } - } - return true; - } - /** * Makes this hopper remember the given inventory. * @@ -480,7 +456,7 @@ private void cacheExtractBlockInventory(Inventory extractInventory) { } } - public Inventory getExtractBlockInventory(World world) { + public Inventory getExtractBlockInventory(World world, BlockPos extractBlockPos, BlockState extractBlockState) { Inventory blockInventory = this.extractBlockInventory; if (this.extractionMode == HopperCachingState.BlockInventory.NO_BLOCK_INVENTORY) { return null; @@ -492,11 +468,7 @@ public Inventory getExtractBlockInventory(World world) { BlockEntity blockEntity = (BlockEntity) Objects.requireNonNull(blockInventory); //Movable Block Entity compatibility - position comparison BlockPos pos = blockEntity.getPos(); - BlockPos thisPos = this.getPos(); - if (!(blockEntity).isRemoved() && - pos.getX() == thisPos.getX() && - pos.getY() == thisPos.getY() + 1 && - pos.getZ() == thisPos.getZ()) { + if (!(blockEntity).isRemoved() && pos.equals(extractBlockPos)) { LithiumInventory optimizedInventory; if ((optimizedInventory = this.extractInventory) != null) { LithiumStackList insertInventoryStackList = InventoryHelper.getLithiumStackList(optimizedInventory); @@ -513,13 +485,13 @@ public Inventory getExtractBlockInventory(World world) { } //No Cached Inventory: Get like vanilla and cache - blockInventory = HopperHelper.vanillaGetBlockInventory(world, this.getPos().up()); + blockInventory = getBlockInventoryAt(world, extractBlockPos, extractBlockState); blockInventory = HopperHelper.replaceDoubleInventory(blockInventory); this.cacheExtractBlockInventory(blockInventory); return blockInventory; } - public Inventory getInsertBlockInventory(World world, BlockState hopperState) { + public Inventory getInsertBlockInventory(World world) { Inventory blockInventory = this.insertBlockInventory; if (this.insertionMode == HopperCachingState.BlockInventory.NO_BLOCK_INVENTORY) { return null; @@ -531,7 +503,7 @@ public Inventory getInsertBlockInventory(World world, BlockState hopperState) { BlockEntity blockEntity = (BlockEntity) Objects.requireNonNull(blockInventory); //Movable Block Entity compatibility - position comparison BlockPos pos = blockEntity.getPos(); - Direction direction = hopperState.get(HopperBlock.FACING); + Direction direction = this.facing; BlockPos transferPos = this.getPos().offset(direction); if (!(blockEntity).isRemoved() && pos.equals(transferPos)) { @@ -551,22 +523,24 @@ public Inventory getInsertBlockInventory(World world, BlockState hopperState) { } //No Cached Inventory: Get like vanilla and cache - Direction direction = hopperState.get(HopperBlock.FACING); - blockInventory = HopperHelper.vanillaGetBlockInventory(world, this.getPos().offset(direction)); + Direction direction = this.facing; + BlockPos insertBlockPos = this.getPos().offset(direction); + BlockState blockState = world.getBlockState(insertBlockPos); + blockInventory = getBlockInventoryAt(world, insertBlockPos, blockState); blockInventory = HopperHelper.replaceDoubleInventory(blockInventory); this.cacheInsertBlockInventory(blockInventory); return blockInventory; } - public Inventory getInsertInventory(World world, BlockState hopperState) { - Inventory blockInventory = this.getInsertBlockInventory(world, hopperState); + public Inventory getInsertInventory(World world) { + Inventory blockInventory = this.getInsertBlockInventory(world); if (blockInventory != null) { return blockInventory; } if (this.insertInventoryEntityTracker == null) { - this.initInsertInventoryTracker(world, hopperState); + this.initInsertInventoryTracker(world); } if (this.insertInventoryEntityTracker.isUnchangedSince(this.insertInventoryEntityFailedSearchTime)) { this.insertInventoryEntityFailedSearchTime = this.lastTickTime; @@ -596,23 +570,12 @@ public Inventory getInsertInventory(World world, BlockState hopperState) { private void initCollectItemEntityTracker() { assert this.world instanceof ServerWorld; - List list = new ArrayList<>(); - Box encompassingBox = null; - for (Box box : HopperHelper.getHopperPickupVolumeBoxes(this)) { - Box offsetBox = box.offset(this.pos.getX(), this.pos.getY(), this.pos.getZ()); - list.add(offsetBox); - if (encompassingBox == null) { - encompassingBox = offsetBox; - } else { - encompassingBox = encompassingBox.union(offsetBox); - } - } - list.add(encompassingBox); - this.collectItemEntityBoxes = list.toArray(new Box[0]); + Box inputBox = this.getInputAreaShape().offset(this.pos.getX(), this.pos.getY(), this.pos.getZ()); + this.collectItemEntityBox = inputBox; this.collectItemEntityTracker = SectionedItemEntityMovementTracker.registerAt( (ServerWorld) this.world, - encompassingBox, + inputBox, ItemEntity.class ); this.collectItemEntityAttemptTime = Long.MIN_VALUE; @@ -631,9 +594,9 @@ private void initExtractInventoryTracker(World world) { this.extractInventoryEntityFailedSearchTime = Long.MIN_VALUE; } - private void initInsertInventoryTracker(World world, BlockState hopperState) { + private void initInsertInventoryTracker(World world) { assert world instanceof ServerWorld; - Direction direction = hopperState.get(HopperBlock.FACING); + Direction direction = this.facing; BlockPos pos = this.pos.offset(direction); this.insertInventoryEntityBox = new Box(pos.getX(), pos.getY(), pos.getZ(), pos.getX() + 1, pos.getY() + 1, pos.getZ() + 1); this.insertInventoryEntityTracker = @@ -646,15 +609,8 @@ private void initInsertInventoryTracker(World world, BlockState hopperState) { } //Cached data invalidation: - @SuppressWarnings("deprecation") - @Intrinsic - @Override - public void setCachedState(BlockState state) { - super.setCachedState(state); - } - @SuppressWarnings({"MixinAnnotationTarget", "UnresolvedMixinReference"}) - @Inject(method = {"setCachedState(Lnet/minecraft/block/BlockState;)V","setBlockState(Lnet/minecraft/world/level/block/state/BlockState;)V"}, at = @At("HEAD"), remap = false) + @Inject(method = "setCachedState(Lnet/minecraft/block/BlockState;)V", at = @At("HEAD")) private void invalidateOnSetCachedState(BlockState state, CallbackInfo ci) { if (this.world != null && !this.world.isClient() && state.get(HopperBlock.FACING) != this.getCachedState().get(HopperBlock.FACING)) { this.invalidateCachedData(); @@ -707,7 +663,7 @@ private void invalidateExtractionData() { if (this.collectItemEntityTracker != null) { this.collectItemEntityTracker.unRegister(serverWorld); this.collectItemEntityTracker = null; - this.collectItemEntityBoxes = null; + this.collectItemEntityBox = null; this.collectItemEntityTrackerWasEmpty = false; } } @@ -767,7 +723,7 @@ private void checkSleepingConditions() { Inventory blockInventory = this.extractBlockInventory; if (this.extractStackList != null && blockInventory instanceof InventoryChangeTracker) { - if (!this.extractStackList.maybeSendsComparatorUpdatesOnFailedExtract() || (blockInventory instanceof ComparatorTracker comparatorTracker && !comparatorTracker.hasAnyComparatorNearby())) { + if (!this.extractStackList.maybeSendsComparatorUpdatesOnFailedExtract() || (blockInventory instanceof ComparatorTracker comparatorTracker && !comparatorTracker.lithium$hasAnyComparatorNearby())) { listenToExtractTracker = true; } else { return; @@ -810,7 +766,7 @@ private void checkSleepingConditions() { } if (listenToInsertEntities) { if (this.insertInventoryEntityTracker == null) { - this.initInsertInventoryTracker(this.world, this.getCachedState()); + this.initInsertInventoryTracker(this.world); } this.insertInventoryEntityTracker.listenToEntityMovementOnce(this); } @@ -825,20 +781,20 @@ private void checkSleepingConditions() { this.collectItemEntityTracker.listenToEntityMovementOnce(this); } thisTracker.listenForContentChangesOnce(thisStackList, this); - thisSleepingBlockEntity.startSleeping(); + thisSleepingBlockEntity.lithium$startSleeping(); } } } @Override - public void handleInventoryContentModified(Inventory inventory) { + public void lithium$handleInventoryContentModified(Inventory inventory) { if (this instanceof SleepingBlockEntity sleepingBlockEntity) { sleepingBlockEntity.wakeUpNow(); } } @Override - public void handleInventoryRemoved(Inventory inventory) { + public void lithium$handleInventoryRemoved(Inventory inventory) { if (this instanceof SleepingBlockEntity sleepingBlockEntity) { sleepingBlockEntity.wakeUpNow(); } @@ -854,7 +810,7 @@ public void handleInventoryRemoved(Inventory inventory) { } @Override - public boolean handleComparatorAdded(Inventory inventory) { + public boolean lithium$handleComparatorAdded(Inventory inventory) { if (inventory == this.extractBlockInventory && this instanceof SleepingBlockEntity sleepingBlockEntity) { sleepingBlockEntity.wakeUpNow(); return true; @@ -863,7 +819,7 @@ public boolean handleComparatorAdded(Inventory inventory) { } @Override - public void handleEntityMovement(Class category) { + public void lithium$handleEntityMovement(Class category) { if (this instanceof SleepingBlockEntity sleepingBlockEntity) { sleepingBlockEntity.wakeUpNow(); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockMixin.java index b79f472a9..5c661ac71 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/HopperBlockMixin.java @@ -22,7 +22,6 @@ protected HopperBlockMixin(Settings settings) { super(settings); } - @SuppressWarnings("deprecation") @Intrinsic @Override public BlockState getStateForNeighborUpdate(BlockState myBlockState, Direction direction, BlockState newState, WorldAccess world, BlockPos myPos, BlockPos posFrom) { @@ -53,9 +52,9 @@ private void updateHopper(WorldAccess world, BlockState myBlockState, BlockPos m Direction facing = myBlockState.get(HopperBlock.FACING); boolean above = posFrom.getY() == myPos.getY() + 1; if (above || posFrom.getX() == myPos.getX() + facing.getOffsetX() && posFrom.getY() == myPos.getY() + facing.getOffsetY() && posFrom.getZ() == myPos.getZ() + facing.getOffsetZ()) { - BlockEntity hopper = ((BlockEntityGetter) world).getLoadedExistingBlockEntity(myPos); + BlockEntity hopper = ((BlockEntityGetter) world).lithium$getLoadedExistingBlockEntity(myPos); if (hopper instanceof UpdateReceiver updateReceiver) { - updateReceiver.invalidateCacheOnNeighborUpdate(above); + updateReceiver.lithium$invalidateCacheOnNeighborUpdate(above); } } } @@ -72,9 +71,9 @@ private void workAroundVanillaUpdateSuppression(BlockState state, World world, B //invalidate caches of nearby hoppers when placing an update suppressed hopper if (world.getBlockState(pos) != state) { for (Direction direction : DIRECTIONS) { - BlockEntity hopper = ((BlockEntityGetter) world).getLoadedExistingBlockEntity(pos.offset(direction)); + BlockEntity hopper = ((BlockEntityGetter) world).lithium$getLoadedExistingBlockEntity(pos.offset(direction)); if (hopper instanceof UpdateReceiver updateReceiver) { - updateReceiver.invalidateCacheOnNeighborUpdate(direction == Direction.DOWN); + updateReceiver.lithium$invalidateCacheOnNeighborUpdate(direction == Direction.DOWN); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/WorldMixin.java index 6f5cdf872..119861d59 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/WorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/WorldMixin.java @@ -38,9 +38,9 @@ private void updateHopperOnUpdateSuppression(BlockPos pos, WorldChunk worldChunk for (Direction direction : DirectionConstants.ALL) { BlockPos offsetPos = pos.offset(direction); //Directly get the block entity instead of getting the block state first. Maybe that is faster, maybe not. - BlockEntity hopper = blockEntities != null ? blockEntities.get(offsetPos) : ((BlockEntityGetter) this).getLoadedExistingBlockEntity(offsetPos); + BlockEntity hopper = blockEntities != null ? blockEntities.get(offsetPos) : ((BlockEntityGetter) this).lithium$getLoadedExistingBlockEntity(offsetPos); if (hopper instanceof UpdateReceiver updateReceiver) { - updateReceiver.invalidateCacheOnNeighborUpdate(direction == Direction.DOWN); + updateReceiver.lithium$invalidateCacheOnNeighborUpdate(direction == Direction.DOWN); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/worldedit_compat/WorldChunkMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/worldedit_compat/WorldChunkMixin.java index 4067e8812..a2f9d3c8e 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/worldedit_compat/WorldChunkMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/hopper/worldedit_compat/WorldChunkMixin.java @@ -41,9 +41,9 @@ private static void updateHopperCachesOnNewInventoryAdded(WorldChunk worldChunk, BlockEntity neighborBlockEntity = WorldHelper.arePosWithinSameChunk(pos, neighborPos) ? worldChunk.getBlockEntity(neighborPos, WorldChunk.CreationType.CHECK) : - ((BlockEntityGetter) world).getLoadedExistingBlockEntity(neighborPos); + ((BlockEntityGetter) world).lithium$getLoadedExistingBlockEntity(neighborPos); if (neighborBlockEntity instanceof UpdateReceiver updateReceiver) { - updateReceiver.invalidateCacheOnNeighborUpdate(offsetDirection.getOpposite()); + updateReceiver.lithium$invalidateCacheOnNeighborUpdate(offsetDirection.getOpposite()); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/PistonBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/PistonBlockEntityMixin.java index 1d2917489..b826b5082 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/PistonBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/PistonBlockEntityMixin.java @@ -79,11 +79,11 @@ private void skipVoxelShapeUnion(BlockView world, BlockPos pos, CallbackInfoRetu * @return blockShape offset and simplified */ private static VoxelShape getOffsetAndSimplified(VoxelShape blockShape, float offset, Direction direction) { - VoxelShape offsetSimplifiedShape = ((OffsetVoxelShapeCache) blockShape).getOffsetSimplifiedShape(offset, direction); + VoxelShape offsetSimplifiedShape = ((OffsetVoxelShapeCache) blockShape).lithium$getOffsetSimplifiedShape(offset, direction); if (offsetSimplifiedShape == null) { //create the offset shape and store it for later use offsetSimplifiedShape = blockShape.offset(direction.getOffsetX() * offset, direction.getOffsetY() * offset, direction.getOffsetZ() * offset).simplify(); - ((OffsetVoxelShapeCache) blockShape).setShape(offset, direction, offsetSimplifiedShape); + ((OffsetVoxelShapeCache) blockShape).lithium$setShape(offset, direction, offsetSimplifiedShape); } return offsetSimplifiedShape; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/VoxelShapeMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/VoxelShapeMixin.java index 8ffc626cb..12e96c02e 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/VoxelShapeMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/block/moving_block_shapes/VoxelShapeMixin.java @@ -10,7 +10,7 @@ public class VoxelShapeMixin implements OffsetVoxelShapeCache { private volatile VoxelShape[] offsetAndSimplified; - public void setShape(float offset, Direction direction, VoxelShape offsetShape) { + public void lithium$setShape(float offset, Direction direction, VoxelShape offsetShape) { if (offsetShape == null) { throw new IllegalArgumentException("offsetShape must not be null!"); } @@ -25,7 +25,7 @@ public void setShape(float offset, Direction direction, VoxelShape offsetShape) this.offsetAndSimplified = offsetAndSimplifiedShapes; } - public VoxelShape getOffsetSimplifiedShape(float offset, Direction direction) { + public VoxelShape lithium$getOffsetSimplifiedShape(float offset, Direction direction) { VoxelShape[] offsetAndSimplified = this.offsetAndSimplified; if (offsetAndSimplified == null) { return null; diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/ClientWorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/ClientWorldMixin.java index 030977f69..3022cc802 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/ClientWorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/ClientWorldMixin.java @@ -15,7 +15,7 @@ public class ClientWorldMixin implements ClientWorldAccessor { private ClientEntityManager entityManager; @Override - public ClientEntityManager getEntityManager() { + public ClientEntityManager lithium$getEntityManager() { return this.entityManager; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/TypeFilterableListMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/TypeFilterableListMixin.java index a37bccf8b..bb9466d67 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/TypeFilterableListMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/entity_class_groups/TypeFilterableListMixin.java @@ -58,7 +58,7 @@ public Object remove(Object o) { /** * Get entities of a class group */ - public Collection getAllOfGroupType(EntityClassGroup type) { + public Collection lithium$getAllOfGroupType(EntityClassGroup type) { Collection collection = this.entitiesByGroup.get(type); if (collection == null) { diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PackedIntegerArrayMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PackedIntegerArrayMixin.java index 5c345a7d7..754bd861c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PackedIntegerArrayMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PackedIntegerArrayMixin.java @@ -33,7 +33,7 @@ public abstract class PackedIntegerArrayMixin implements CompactingPackedInteger private long[] data; @Override - public void compact(Palette srcPalette, Palette dstPalette, short[] out) { + public void lithium$compact(Palette srcPalette, Palette dstPalette, short[] out) { if (this.size >= Short.MAX_VALUE) { throw new IllegalStateException("Array too large"); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PalettedContainerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PalettedContainerMixin.java index 78427e36f..f037217d4 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PalettedContainerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/chunk/serialization/PalettedContainerMixin.java @@ -80,7 +80,7 @@ public PalettedContainer.Serialized serialize(IndexedIterable idList, Pale LithiumHashPalette compactedPalette = new LithiumHashPalette<>(idList, storage.getElementBits(), this.dummyListener); short[] array = this.getOrCreate(provider.getContainerSize()); - ((CompactingPackedIntegerArray) storage).compact(this.data.palette(), compactedPalette, array); + ((CompactingPackedIntegerArray) storage).lithium$compact(this.data.palette(), compactedPalette, array); // If the palette didn't change during compaction, do a simple copy of the data array if (hashPalette != null && hashPalette.getSize() == compactedPalette.getSize() && storage.getElementBits() == provider.getBits(idList, hashPalette.getSize())) { // paletteSize can de-sync from palette - see https://github.com/CaffeineMC/lithium-fabric/issues/279 diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/collections/mob_spawning/PoolMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/collections/mob_spawning/PoolMixin.java index ab078d0fd..b7bc3273f 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/collections/mob_spawning/PoolMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/collections/mob_spawning/PoolMixin.java @@ -20,12 +20,13 @@ public class PoolMixin { @Final private ImmutableList entries; //Need a separate variable due to entries being type ImmutableList + @Unique private List entryHashList; @Inject(method = "(Ljava/util/List;)V", at = @At("RETURN")) private void init(List entries, CallbackInfo ci) { //We are using reference equality here, because all vanilla implementations of Weighted use reference equality - this.entryHashList = this.entries.size() < 4 ? this.entries : Collections.unmodifiableList(new HashedReferenceList<>(this.entries)); + this.entryHashList = this.entries.size() > 4 ? Collections.unmodifiableList(new HashedReferenceList<>(this.entries)) : this.entries; } /** diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/EntityMixin.java index 436e54893..ec8a5bf82 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/EntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/EntityMixin.java @@ -8,10 +8,14 @@ import me.jellysquid.mods.lithium.common.entity.FluidCachingEntity; import me.jellysquid.mods.lithium.common.util.Pos; import net.minecraft.entity.Entity; +import net.minecraft.entity.vehicle.BoatEntity; +import net.minecraft.fluid.Fluid; +import net.minecraft.registry.tag.TagKey; import net.minecraft.util.math.Box; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkSection; +import net.neoforged.neoforge.common.extensions.IEntityExtension; import net.neoforged.neoforge.fluids.FluidType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; @@ -19,22 +23,44 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; +import javax.annotation.Nullable; import java.util.function.BiPredicate; -@Mixin(Entity.class) -public abstract class EntityMixin implements FluidCachingEntity { +@Mixin(value = Entity.class, priority = 900) +public abstract class EntityMixin implements FluidCachingEntity, IEntityExtension { @Shadow public abstract Box getBoundingBox(); @Shadow - public World world; + private World world; @Shadow protected Object2DoubleMap forgeFluidTypeHeight; + @Shadow + @Deprecated + protected Object2DoubleMap> fluidHeight; + + @Shadow + abstract void checkWaterState(); + + @Shadow + public abstract boolean isInFluidType(); + + @Shadow + @Nullable + public abstract Entity getVehicle(); + + @Shadow + public float fallDistance; + + @Shadow + public abstract void extinguish(); + + private boolean radium$isInModdedFluid; + /** * @author 2No2Name, embeddedt * @reason Skip computing fluid heights if we know none of the relevant chunk sections contain any fluids. @@ -47,7 +73,8 @@ public abstract class EntityMixin implements FluidCachingEntity { shift = At.Shift.BEFORE ), cancellable = true, - locals = LocalCapture.CAPTURE_FAILHARD + locals = LocalCapture.CAPTURE_FAILHARD, + require = 0 ) public void tryShortcutFluidPushing(CallbackInfo ci, Box box, int x1, int x2, int y1, int y2, int z1, int z2, double zero) { int chunkX1 = x1 >> 4; @@ -61,7 +88,7 @@ public void tryShortcutFluidPushing(CallbackInfo ci, Box box, int x1, int x2, in Chunk chunk = this.world.getChunk(chunkX, chunkZ); for (int chunkYIndex = chunkYIndex1; chunkYIndex <= chunkYIndex2; chunkYIndex++) { ChunkSection section = chunk.getSectionArray()[chunkYIndex]; - if (((BlockCountingSection) section).mayContainAny(BlockStateFlags.ANY_FLUID)) { + if (((BlockCountingSection) section).lithium$mayContainAny(BlockStateFlags.ANY_FLUID)) { //fluid found, cannot skip code return; } @@ -79,12 +106,53 @@ public void tryShortcutFluidPushing(CallbackInfo ci, Box box, int x1, int x2, in /** * @author embeddedt - * @reason Skip running expensive logic from Forge if the entity is known not to be in a fluid. + * @reason Track when the entity is in a non-vanilla fluid type. This flag is used to skip looping through + * fluid types when entities are only in vanilla fluids. */ - @Inject(method = "updateWaterState", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/Entity;checkWaterState()V", shift = At.Shift.AFTER), cancellable = true) - private void earlyExitIfTouchingNone(CallbackInfoReturnable cir) { - if(this.forgeFluidTypeHeight.isEmpty()) { - cir.setReturnValue(false); + @Inject(method = "setFluidTypeHeight", at = @At("RETURN")) + private void markInModdedFluid(FluidType type, double height, CallbackInfo ci) { + if(!type.isAir() && !type.isVanilla()) { + this.radium$isInModdedFluid = true; + } + } + + /** + * @author embeddedt + * @reason Early-exit when not in a modded fluid, avoid streams & allocations for other calculations + */ + @Overwrite + protected boolean updateWaterState() { + this.fluidHeight.clear(); + this.forgeFluidTypeHeight.clear(); + this.radium$isInModdedFluid = false; + this.checkWaterState(); + + if (this.radium$isInModdedFluid) { + this.handleModdedFluidBehaviors(); + } + + return this.isInFluidType(); + } + + private void handleModdedFluidBehaviors() { + if (!(this.getVehicle() instanceof BoatEntity)) { + float fallDistanceModifier = Float.MAX_VALUE; + boolean canExtinguish = false; + + for(FluidType type : this.forgeFluidTypeHeight.keySet()) { + if(!type.isAir() && !type.isVanilla()) { + fallDistanceModifier = Math.min(this.getFluidFallDistanceModifier(type), fallDistanceModifier); + canExtinguish |= this.canFluidExtinguish(type); + } + } + + if (fallDistanceModifier != Float.MAX_VALUE) { + this.fallDistance *= fallDistanceModifier; + } + + if (canExtinguish) { + this.extinguish(); + } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/package-info.java index 82b609e8b..1e5c6e5ac 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/package-info.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/fluid/package-info.java @@ -1,8 +1,7 @@ @MixinConfigOption( description = "Skips being pushed by fluids when the nearby chunk sections do not contain this fluid", depends = { - @MixinConfigDependency(dependencyPath = "mixin.util.block_tracking"), - @MixinConfigDependency(dependencyPath = "mixin.experimental.entity.block_caching.fluid_pushing", enabled = false) + @MixinConfigDependency(dependencyPath = "mixin.util.block_tracking") } ) package me.jellysquid.mods.lithium.mixin.entity.collisions.fluid; diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityMixin.java index 0dbd4f6b9..595a00dab 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityMixin.java @@ -14,7 +14,7 @@ @Mixin(Entity.class) public class EntityMixin implements BlockCachingEntity { @Shadow - private @Nullable BlockState blockStateAtPos; + private @Nullable BlockState stateAtPos; @Inject( method = "setPos(DDD)V", @@ -26,7 +26,7 @@ public class EntityMixin implements BlockCachingEntity { ) ) private void onPositionChanged(double x, double y, double z, CallbackInfo ci) { - this.lithiumOnBlockCacheDeleted(); + this.lithium$OnBlockCacheDeleted(); } @Inject( @@ -39,7 +39,7 @@ private void onPositionChanged(double x, double y, double z, CallbackInfo ci) { ) ) private void onBaseTick(CallbackInfo ci) { - this.lithiumOnBlockCacheDeleted(); + this.lithium$OnBlockCacheDeleted(); } @Inject( @@ -51,11 +51,11 @@ private void onBaseTick(CallbackInfo ci) { ) ) private void onBlockCached(CallbackInfoReturnable cir) { - this.lithiumOnBlockCacheSet(this.blockStateAtPos); + this.lithium$OnBlockCacheSet(this.stateAtPos); } @Override - public BlockState getCachedFeetBlockState() { - return this.blockStateAtPos; + public BlockState lithium$getCachedFeetBlockState() { + return this.stateAtPos; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityTrackingSectionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityTrackingSectionMixin.java index 359999693..9682f2049 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityTrackingSectionMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/EntityTrackingSectionMixin.java @@ -44,7 +44,7 @@ public abstract class EntityTrackingSectionMixin implement private ReferenceMaskedList pushableEntities; @Override - public LazyIterationConsumer.NextIteration collectPushableEntities(World world, Entity except, Box box, EntityPushablePredicate entityPushablePredicate, ArrayList entities) { + public LazyIterationConsumer.NextIteration lithium$collectPushableEntities(World world, Entity except, Box box, EntityPushablePredicate entityPushablePredicate, ArrayList entities) { Iterator entityIterator; if (this.pushableEntities != null) { entityIterator = this.pushableEntities.iterator(); @@ -84,9 +84,9 @@ private void stopFilteringPushableEntities() { //This might be called while the world is in an inconsistent state. E.g. the entity may be in a different section than //it is registered to. @Override - public void onEntityModifiedCachedBlock(BlockCachingEntity entity, BlockState newBlockState) { + public void lithium$onEntityModifiedCachedBlock(BlockCachingEntity entity, BlockState newBlockState) { if (this.pushableEntities == null) { - entity.lithiumSetClimbingMobCachingSectionUpdateBehavior(false); + entity.lithium$SetClimbingMobCachingSectionUpdateBehavior(false); } else { this.updatePushabilityOnCachedStateChange(entity, newBlockState); } @@ -107,8 +107,8 @@ private void onStartClimbingCachingEntity(Entity entity) { boolean shouldTrackBlockChanges = PushableEntityClassGroup.CACHABLE_UNPUSHABILITY.contains(entityClass); if (shouldTrackBlockChanges) { BlockCachingEntity blockCachingEntity = (BlockCachingEntity) entity; - this.updatePushabilityOnCachedStateChange(blockCachingEntity, blockCachingEntity.getCachedFeetBlockState()); - blockCachingEntity.lithiumSetClimbingMobCachingSectionUpdateBehavior(true); + this.updatePushabilityOnCachedStateChange(blockCachingEntity, blockCachingEntity.lithium$getCachedFeetBlockState()); + blockCachingEntity.lithium$SetClimbingMobCachingSectionUpdateBehavior(true); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/LivingEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/LivingEntityMixin.java index 4463111c0..8f21a75a2 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/LivingEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/collisions/unpushable_cramming/LivingEntityMixin.java @@ -55,12 +55,12 @@ private List getOtherPushableEntities(World world, @Nullable Entity exce } @Override - public void lithiumSetClimbingMobCachingSectionUpdateBehavior(boolean listenForCachedBlockChanges) { + public void lithium$SetClimbingMobCachingSectionUpdateBehavior(boolean listenForCachedBlockChanges) { this.updateClimbingMobCachingSectionOnChange = listenForCachedBlockChanges; } @Override - public void lithiumOnBlockCacheDeleted() { + public void lithium$OnBlockCacheDeleted() { if (this.updateClimbingMobCachingSectionOnChange) { this.updateClimbingMobCachingSection(null); } @@ -68,7 +68,7 @@ public void lithiumOnBlockCacheDeleted() { @Override - public void lithiumOnBlockCacheSet(BlockState newState) { + public void lithium$OnBlockCacheSet(BlockState newState) { if (this.updateClimbingMobCachingSectionOnChange) { this.updateClimbingMobCachingSection(newState); } @@ -79,7 +79,7 @@ private void updateClimbingMobCachingSection(BlockState newState) { if (entityCacheOrNull != null) { EntityTrackingSection trackingSection = entityCacheOrNull.findTrackingSection(ChunkSectionPos.toLong(this.getBlockPos())); if (trackingSection != null) { - ((ClimbingMobCachingSection) trackingSection).onEntityModifiedCachedBlock(this, newState); + ((ClimbingMobCachingSection) trackingSection).lithium$onEntityModifiedCachedBlock(this, newState); } else { this.updateClimbingMobCachingSectionOnChange = false; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/DataTrackerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/DataTrackerMixin.java deleted file mode 100644 index 76ab87e5c..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/DataTrackerMixin.java +++ /dev/null @@ -1,38 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.entity.data_tracker.no_locks; - -import me.jellysquid.mods.lithium.common.util.lock.NullReadWriteLock; -import net.minecraft.entity.Entity; -import net.minecraft.entity.data.DataTracker; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -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 java.util.concurrent.locks.ReadWriteLock; - -/** - * The vanilla implementation of {@link DataTracker} performs locking when fetching or updating data due to a legacy - * quirk in older versions of the game where updates would occur on a network thread for (de)serialization while entities - * were ticking and accessing values from it on the main thread. In newer versions (1.14+) this no longer happens. - *

- * The DataTracker is expected to only ever updated on the main-thread (or the thread owning it in recent versions when - * baking entities) during entity initialization and main-thread network updates, and as such the locking mechanism - * is unnecessary since the job is to only protect against simultaneous reading and writing. - */ -@Mixin(value = DataTracker.class, priority = 1001) -public abstract class DataTrackerMixin { - private static final NullReadWriteLock NULL_READ_WRITE_LOCK = new NullReadWriteLock(); - - @Mutable - @Shadow - @Final - private ReadWriteLock lock; - - @Inject(method = "(Lnet/minecraft/entity/Entity;)V", at = @At("RETURN")) - private void init(Entity entity, CallbackInfo ci) { - this.lock = NULL_READ_WRITE_LOCK; - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/package-info.java deleted file mode 100644 index 7c27a06cb..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/no_locks/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@MixinConfigOption(description = "Remove unnecessary locking when accessing the data tracker") -package me.jellysquid.mods.lithium.mixin.entity.data_tracker.no_locks; - -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/package-info.java deleted file mode 100644 index 145bb97cb..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@MixinConfigOption(description = "Various entity data tracker optimizations") -package me.jellysquid.mods.lithium.mixin.entity.data_tracker; - -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/DataTrackerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/DataTrackerMixin.java deleted file mode 100644 index 19c14319f..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/DataTrackerMixin.java +++ /dev/null @@ -1,112 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.entity.data_tracker.use_arrays; - -import it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import net.minecraft.entity.data.DataTracker; -import net.minecraft.entity.data.TrackedData; -import net.minecraft.util.crash.CrashException; -import net.minecraft.util.crash.CrashReport; -import net.minecraft.util.crash.CrashReportSection; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Arrays; -import java.util.concurrent.locks.ReadWriteLock; - -/** - * Optimizes the DataTracker to use a simple array-based storage for entries and avoids integer boxing. This reduces - * a lot of the overhead associated with retrieving tracked data about an entity. - */ -@Mixin(DataTracker.class) -public abstract class DataTrackerMixin { - private static final int DEFAULT_ENTRY_COUNT = 10, GROW_FACTOR = 8; - - @Shadow - @Final - private ReadWriteLock lock; - - @Mutable - @Shadow - @Final - private Int2ObjectMap> entries; - /** - * Mirrors the vanilla backing entries map. Each DataTracker.Entry can be accessed in this array through its ID. - **/ - private DataTracker.Entry[] entriesArray = new DataTracker.Entry[DEFAULT_ENTRY_COUNT]; - - /** - * We redirect the call to add a tracked data to the internal map so we can add it to our new storage structure. This - * should only ever occur during entity initialization. Type-erasure is a bit of a pain here since we must redirect - * a calls to the generic Map interface. - */ - @Redirect( - method = "addTrackedData(Lnet/minecraft/entity/data/TrackedData;Ljava/lang/Object;)V", - at = @At( - value = "INVOKE", - target = "Lit/unimi/dsi/fastutil/ints/Int2ObjectMap;put(ILjava/lang/Object;)Ljava/lang/Object;", - remap = false - ) - ) - private Object onAddTrackedDataInsertMap(Int2ObjectMap int2ObjectMap, int k, Object valueRaw) { - DataTracker.Entry v = (DataTracker.Entry) valueRaw; - - DataTracker.Entry[] storage = this.entriesArray; - - // Check if we need to grow the backing array to accommodate the new key range - if (storage.length <= k) { - // Grow the array to accommodate 8 entries after this one, but limit it to never be larger - // than 256 entries as per the vanilla limit - int newSize = Math.min(k + GROW_FACTOR, 256); - - this.entriesArray = storage = Arrays.copyOf(storage, newSize); - } - - // Update the storage - storage[k] = v; - - // Ensure that the vanilla backing storage is still updated appropriately - return this.entries.put(k, v); - } - - /** - * @reason Avoid integer boxing/unboxing and use our array-based storage - * @author JellySquid - */ - @Overwrite - private DataTracker.Entry getEntry(TrackedData data) { - this.lock.readLock().lock(); - - try { - DataTracker.Entry[] array = this.entriesArray; - - int id = data.getId(); - - // The vanilla implementation will simply return null if the tracker doesn't contain the specified entry. However, - // accessing an array with an invalid pointer will throw a OOB exception, where-as a HashMap would simply - // return null. We check this case (which should be free, even if so insignificant, as the subsequent bounds - // check will hopefully be eliminated) - if (id < 0 || id >= array.length) { - return null; - } - - // This cast can fail if trying to access a entry which doesn't belong to this tracker, as the ID could - // instead point to an entry of a different type. However, that is also vanilla behaviour. - // noinspection unchecked - return (DataTracker.Entry) array[id]; - } catch (Throwable cause) { - // Move to another method so this function can be in-lined better - throw onGetException(cause, data); - } finally { - this.lock.readLock().unlock(); - } - } - - private static CrashException onGetException(Throwable cause, TrackedData data) { - CrashReport report = CrashReport.create(cause, "Getting synced entity data"); - - CrashReportSection section = report.addElement("Synced entity data"); - section.add("Data ID", data); - - return new CrashException(report); - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/package-info.java deleted file mode 100644 index 2407e4e7d..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/data_tracker/use_arrays/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@MixinConfigOption(description = "Data trackers use a custom optimized entry map") -package me.jellysquid.mods.lithium.mixin.entity.data_tracker.use_arrays; - -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/fast_powder_snow_check/LivingEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/fast_powder_snow_check/LivingEntityMixin.java index f0fb10bce..825c03a1a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/fast_powder_snow_check/LivingEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/fast_powder_snow_check/LivingEntityMixin.java @@ -6,6 +6,7 @@ import net.minecraft.entity.LivingEntity; import net.minecraft.entity.attribute.EntityAttribute; import net.minecraft.entity.attribute.EntityAttributeInstance; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import org.spongepowered.asm.mixin.Mixin; @@ -17,8 +18,7 @@ public abstract class LivingEntityMixin extends Entity { @Shadow - public @Nullable - abstract EntityAttributeInstance getAttributeInstance(EntityAttribute attribute); + public abstract @Nullable EntityAttributeInstance getAttributeInstance(RegistryEntry attribute); public LivingEntityMixin(EntityType type, World world) { super(type, world); @@ -50,10 +50,10 @@ private boolean delayAirTest(BlockState instance) { method = "addPowderSnowSlowIfNeeded()V", at = @At( value = "INVOKE", - target = "Lnet/minecraft/entity/LivingEntity;getAttributeInstance(Lnet/minecraft/entity/attribute/EntityAttribute;)Lnet/minecraft/entity/attribute/EntityAttributeInstance;" + target = "Lnet/minecraft/entity/LivingEntity;getAttributeInstance(Lnet/minecraft/registry/entry/RegistryEntry;)Lnet/minecraft/entity/attribute/EntityAttributeInstance;" ) ) - private EntityAttributeInstance doDelayedBlockStateAirTest(LivingEntity instance, EntityAttribute attribute) { + private EntityAttributeInstance doDelayedBlockStateAirTest(LivingEntity instance, RegistryEntry attribute) { //noinspection deprecation return this.getLandingBlockState().isAir() ? null : this.getAttributeInstance(attribute); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/HopperBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/HopperBlockEntityMixin.java deleted file mode 100644 index fbc77bf21..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/HopperBlockEntityMixin.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.entity.hopper_minecart; - -import me.jellysquid.mods.lithium.common.world.ItemEntityHelper; -import net.minecraft.block.entity.Hopper; -import net.minecraft.block.entity.HopperBlockEntity; -import net.minecraft.entity.ItemEntity; -import net.minecraft.predicate.entity.EntityPredicates; -import net.minecraft.util.math.Box; -import net.minecraft.world.World; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Overwrite; - -import java.util.Collections; -import java.util.List; - -@Mixin(HopperBlockEntity.class) -public class HopperBlockEntityMixin { - - /** - * @author 2No2Name - * @reason avoid checking 5 boxes - *

- * This code is run by hopper minecarts. Hopper blocks use a different optimization unless it is disabled. - */ - @Overwrite - public static List getInputItemEntities(World world, Hopper hopper) { - Box encompassingBox = hopper.getInputAreaShape().getBoundingBox(); - double xOffset = hopper.getHopperX() - 0.5; - double yOffset = hopper.getHopperY() - 0.5; - double zOffset = hopper.getHopperZ() - 0.5; - List nearbyEntities = world.getEntitiesByClass(ItemEntity.class, encompassingBox.offset(xOffset, yOffset, zOffset), EntityPredicates.VALID_ENTITY); - - if (nearbyEntities.isEmpty()) { - return Collections.emptyList(); - } - - return ItemEntityHelper.getItemEntityBucketedList(hopper, xOffset, yOffset, zOffset, nearbyEntities); - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/package-info.java deleted file mode 100644 index 68e2bc07a..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/hopper_minecart/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -@MixinConfigOption(description = "Hopper minecarts search for item entities faster by combining multiple item entity searches. Also eliminates duplicated item entity pickup attempts") -package me.jellysquid.mods.lithium.mixin.entity.hopper_minecart; - -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityLeaveWaterGoalMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityLeaveWaterGoalMixin.java index b42cd84c3..45e418a6e 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityLeaveWaterGoalMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityLeaveWaterGoalMixin.java @@ -17,6 +17,6 @@ public class DrownedEntityLeaveWaterGoalMixin { @Inject(method = "start()V", at = @At(value = "RETURN")) private void updateInactivityState(CallbackInfo ci) { - ((NavigatingEntity) this.drowned).updateNavigationRegistration(); + ((NavigatingEntity) this.drowned).lithium$updateNavigationRegistration(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityMixin.java index c1c68b305..bb45f98cd 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/DrownedEntityMixin.java @@ -11,6 +11,6 @@ public class DrownedEntityMixin { @Inject(method = "updateSwimming()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/mob/DrownedEntity;setSwimming(Z)V")) private void updateInactivityState(CallbackInfo ci) { - ((NavigatingEntity) this).updateNavigationRegistration(); + ((NavigatingEntity) this).lithium$updateNavigationRegistration(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/EntityNavigationMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/EntityNavigationMixin.java index f35c0cdf4..56df09652 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/EntityNavigationMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/EntityNavigationMixin.java @@ -37,30 +37,30 @@ public abstract class EntityNavigationMixin { ) ) private void updateListeningState(CallbackInfo ci) { - if (((NavigatingEntity) this.entity).isRegisteredToWorld()) { + if (((NavigatingEntity) this.entity).lithium$isRegisteredToWorld()) { if (this.currentPath == null) { - ((ServerWorldExtended) this.world).setNavigationInactive(this.entity); + ((ServerWorldExtended) this.world).lithium$setNavigationInactive(this.entity); } else { - ((ServerWorldExtended) this.world).setNavigationActive(this.entity); + ((ServerWorldExtended) this.world).lithium$setNavigationActive(this.entity); } } } @Inject(method = "startMovingAlong(Lnet/minecraft/entity/ai/pathing/Path;D)Z", at = @At(value = "RETURN")) private void updateListeningState2(Path path, double speed, CallbackInfoReturnable cir) { - if (((NavigatingEntity) this.entity).isRegisteredToWorld()) { + if (((NavigatingEntity) this.entity).lithium$isRegisteredToWorld()) { if (this.currentPath == null) { - ((ServerWorldExtended) this.world).setNavigationInactive(this.entity); + ((ServerWorldExtended) this.world).lithium$setNavigationInactive(this.entity); } else { - ((ServerWorldExtended) this.world).setNavigationActive(this.entity); + ((ServerWorldExtended) this.world).lithium$setNavigationActive(this.entity); } } } @Inject(method = "stop()V", at = @At(value = "RETURN")) private void stopListening(CallbackInfo ci) { - if (((NavigatingEntity) this.entity).isRegisteredToWorld()) { - ((ServerWorldExtended) this.world).setNavigationInactive(this.entity); + if (((NavigatingEntity) this.entity).lithium$isRegisteredToWorld()) { + ((ServerWorldExtended) this.world).lithium$setNavigationInactive(this.entity); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/MobEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/MobEntityMixin.java index 6cbfbef05..cc03ad0cb 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/MobEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/MobEntityMixin.java @@ -27,23 +27,23 @@ public MobEntityMixin(EntityType type, World world) { public abstract EntityNavigation getNavigation(); @Override - public boolean isRegisteredToWorld() { + public boolean lithium$isRegisteredToWorld() { return this.registeredNavigation != null; } @Override - public void setRegisteredToWorld(EntityNavigation navigation) { + public void lithium$setRegisteredToWorld(EntityNavigation navigation) { this.registeredNavigation = navigation; } @Override - public EntityNavigation getRegisteredNavigation() { + public EntityNavigation lithium$getRegisteredNavigation() { return this.registeredNavigation; } @Inject(method = "startRiding(Lnet/minecraft/entity/Entity;Z)Z", at = @At("RETURN")) private void onNavigationReplacement(Entity entity, boolean force, CallbackInfoReturnable cir) { - this.updateNavigationRegistration(); + this.lithium$updateNavigationRegistration(); } @Override @@ -55,19 +55,19 @@ public void stopRiding() { @SuppressWarnings({"MixinAnnotationTarget", "UnresolvedMixinReference"}) @Inject(method = "stopRiding()V", at = @At("RETURN")) private void updateOnStopRiding(CallbackInfo ci) { - this.updateNavigationRegistration(); + this.lithium$updateNavigationRegistration(); } @Override - public void updateNavigationRegistration() { - if (this.isRegisteredToWorld()) { + public void lithium$updateNavigationRegistration() { + if (this.lithium$isRegisteredToWorld()) { EntityNavigation navigation = this.getNavigation(); if (this.registeredNavigation != navigation) { - ((ServerWorldExtended) this.getWorld()).setNavigationInactive((MobEntity) (Object) this); + ((ServerWorldExtended) this.getWorld()).lithium$setNavigationInactive((MobEntity) (Object) this); this.registeredNavigation = navigation; if (navigation.getCurrentPath() != null) { - ((ServerWorldExtended) this.getWorld()).setNavigationActive((MobEntity) (Object) this); + ((ServerWorldExtended) this.getWorld()).lithium$setNavigationActive((MobEntity) (Object) this); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerEntityHandlerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerEntityHandlerMixin.java index d2a01cd8c..c424f7b35 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerEntityHandlerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerEntityHandlerMixin.java @@ -27,9 +27,9 @@ private void inj(ServerWorld outer, CallbackInfo ci) { private boolean startListeningOnEntityLoad(Set set, Object mobEntityObj) { MobEntity mobEntity = (MobEntity) mobEntityObj; EntityNavigation navigation = mobEntity.getNavigation(); - ((NavigatingEntity) mobEntity).setRegisteredToWorld(navigation); + ((NavigatingEntity) mobEntity).lithium$setRegisteredToWorld(navigation); if (navigation.getCurrentPath() != null) { - ((ServerWorldExtended) this.outer).setNavigationActive(mobEntity); + ((ServerWorldExtended) this.outer).lithium$setNavigationActive(mobEntity); } return set.add(mobEntity); } @@ -38,12 +38,12 @@ private boolean startListeningOnEntityLoad(Set set, Object mobEntityO private boolean stopListeningOnEntityUnload(Set set, Object mobEntityObj) { MobEntity mobEntity = (MobEntity) mobEntityObj; NavigatingEntity navigatingEntity = (NavigatingEntity) mobEntity; - if (navigatingEntity.isRegisteredToWorld()) { - EntityNavigation registeredNavigation = navigatingEntity.getRegisteredNavigation(); + if (navigatingEntity.lithium$isRegisteredToWorld()) { + EntityNavigation registeredNavigation = navigatingEntity.lithium$getRegisteredNavigation(); if (registeredNavigation.getCurrentPath() != null) { - ((ServerWorldExtended) this.outer).setNavigationInactive(mobEntity); + ((ServerWorldExtended) this.outer).lithium$setNavigationInactive(mobEntity); } - navigatingEntity.setRegisteredToWorld(null); + navigatingEntity.lithium$setRegisteredToWorld(null); } return set.remove(mobEntity); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerWorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerWorldMixin.java index 1c3c425b8..836ea0a3c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerWorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/inactive_navigations/ServerWorldMixin.java @@ -92,13 +92,13 @@ private void init(MinecraftServer server, Executor workerExecutor, LevelStorage. } @Override - public void setNavigationActive(MobEntity mobEntity) { - this.activeNavigations.add(((NavigatingEntity) mobEntity).getRegisteredNavigation()); + public void lithium$setNavigationActive(MobEntity mobEntity) { + this.activeNavigations.add(((NavigatingEntity) mobEntity).lithium$getRegisteredNavigation()); } @Override - public void setNavigationInactive(MobEntity mobEntity) { - this.activeNavigations.remove(((NavigatingEntity) mobEntity).getRegisteredNavigation()); + public void lithium$setNavigationInactive(MobEntity mobEntity) { + this.activeNavigations.remove(((NavigatingEntity) mobEntity).lithium$getRegisteredNavigation()); } @Inject( @@ -127,7 +127,7 @@ public boolean isConsistent() { int i = 0; for (MobEntity mobEntity : this.loadedMobs) { EntityNavigation entityNavigation = mobEntity.getNavigation(); - if ((entityNavigation.getCurrentPath() != null && ((NavigatingEntity) mobEntity).isRegisteredToWorld()) != this.activeNavigations.contains(entityNavigation)) { + if ((entityNavigation.getCurrentPath() != null && ((NavigatingEntity) mobEntity).lithium$isRegisteredToWorld()) != this.activeNavigations.contains(entityNavigation)) { return false; } if (entityNavigation.getCurrentPath() != null) { diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/ArmorStandEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/ArmorStandEntityMixin.java index 126fde715..ddb8a40b0 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/ArmorStandEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/ArmorStandEntityMixin.java @@ -18,7 +18,7 @@ public class ArmorStandEntityMixin implements EquipmentEntity.EquipmentTrackingE at = @At("RETURN") ) private void trackEquipChange(NbtCompound nbt, CallbackInfo ci) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } @Inject( @@ -26,7 +26,7 @@ private void trackEquipChange(NbtCompound nbt, CallbackInfo ci) { at = @At("RETURN") ) private void trackEquipChange(EquipmentSlot slot, ItemStack stack, CallbackInfo ci) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } @Inject( @@ -34,6 +34,6 @@ private void trackEquipChange(EquipmentSlot slot, ItemStack stack, CallbackInfo at = @At("RETURN") ) private void trackEquipChange(DamageSource damageSource, CallbackInfo ci) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/LivingEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/LivingEntityMixin.java index 2e360e52f..b2a61d1c6 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/LivingEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/LivingEntityMixin.java @@ -34,7 +34,7 @@ public LivingEntityMixin(EntityType type, World world) { } @Override - public void lithiumOnEquipmentChanged() { + public void lithium$OnEquipmentChanged() { this.equipmentChanged = true; } @@ -69,6 +69,6 @@ private void resetEquipmentChanged(CallbackInfo ci) { at = @At("RETURN") ) private void trackEatingEquipmentChange(World world, ItemStack stack, CallbackInfoReturnable cir) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/MobEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/MobEntityMixin.java index a26002b08..64219aedd 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/MobEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/entity/skip_equipment_change_check/MobEntityMixin.java @@ -17,7 +17,7 @@ public class MobEntityMixin implements EquipmentEntity.EquipmentTrackingEntity, at = @At("RETURN") ) private void trackEquipChange(NbtCompound nbt, CallbackInfo ci) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } @Inject( @@ -25,6 +25,6 @@ private void trackEquipChange(NbtCompound nbt, CallbackInfo ci) { at = @At("RETURN") ) private void trackEquipChange(EquipmentSlot slot, ItemStack stack, CallbackInfo ci) { - this.lithiumOnEquipmentChanged(); + this.lithium$OnEquipmentChanged(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/chunk_tickets/ChunkTicketManagerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/chunk_tickets/ChunkTicketManagerMixin.java index af83e35a4..238721dce 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/chunk_tickets/ChunkTicketManagerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/chunk_tickets/ChunkTicketManagerMixin.java @@ -41,7 +41,7 @@ private static boolean canNoneExpire(SortedArraySet> tickets) { return true; } - @Redirect(method = { "lambda$getTickets$5" }, at = @At(value = "INVOKE", target = "Lnet/minecraft/util/collection/SortedArraySet;create(I)Lnet/minecraft/util/collection/SortedArraySet;")) + @Redirect(method = { "method_14041", "m_183922_", "lambda$getTickets$6" }, at = @At(value = "INVOKE", target = "Lnet/minecraft/util/collection/SortedArraySet;create(I)Lnet/minecraft/util/collection/SortedArraySet;")) private static SortedArraySet> useLithiumSortedArraySet(int initialCapacity) { // TODO fix redirect method return new ChunkTicketSortedArraySet<>(initialCapacity); } @@ -86,7 +86,7 @@ private void unregisterExpiringTicket(long pos, ChunkTicket ticket, CallbackI ), locals = LocalCapture.CAPTURE_FAILHARD ) - private void updateSetMinExpiryTime(long position, ChunkTicket ticket, CallbackInfo ci, SortedArraySet> sortedArraySet, int i) { + private void updateSetMinExpiryTime(long position, ChunkTicket ticket, CallbackInfo ci, SortedArraySet sortedArraySet, int i) { if (canExpire(ticket) && sortedArraySet instanceof ChunkTicketSortedArraySet chunkTickets) { chunkTickets.addExpireTime(this.age + ticket.getType().getExpiryTicks()); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/EntityMixin.java index cbd8974af..98ed23642 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/EntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/EntityMixin.java @@ -13,7 +13,7 @@ public class EntityMixin implements BlockCacheProvider { private final BlockCache blockCache = new BlockCache(); @Override - public BlockCache getBlockCache() { + public BlockCache lithium$getBlockCache() { return blockCache; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_support/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_support/EntityMixin.java index 7ee113201..0cb0ec107 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_support/EntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_support/EntityMixin.java @@ -33,7 +33,7 @@ private void cancelIfSkippable(boolean onGround, Vec3d movement, CallbackInfo ci at = @At(value = "INVOKE", ordinal = 0, target = "Lnet/minecraft/world/World;findSupportingBlockPos(Lnet/minecraft/entity/Entity;Lnet/minecraft/util/math/Box;)Ljava/util/Optional;") ) private void cacheSupportingBlockSearch(CallbackInfo ci) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); if (bc.isTracking()) { bc.setCanSkipSupportingBlockSearch(true); } @@ -44,7 +44,7 @@ private void cacheSupportingBlockSearch(CallbackInfo ci) { at = @At(value = "INVOKE", ordinal = 1, target = "Lnet/minecraft/world/World;findSupportingBlockPos(Lnet/minecraft/entity/Entity;Lnet/minecraft/util/math/Box;)Ljava/util/Optional;") ) private void uncacheSupportingBlockSearch(CallbackInfo ci) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); if (bc.isTracking()) { bc.setCanSkipSupportingBlockSearch(false); } @@ -55,7 +55,7 @@ private void uncacheSupportingBlockSearch(CallbackInfo ci) { at = @At(value = "INVOKE", target = "Ljava/util/Optional;empty()Ljava/util/Optional;", remap = false) ) private void uncacheSupportingBlockSearch1(boolean onGround, Vec3d movement, CallbackInfo ci) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); if (bc.isTracking()) { bc.setCanSkipSupportingBlockSearch(false); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_touching/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_touching/EntityMixin.java index 03d4f7e91..a177eb5e3 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_touching/EntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/block_touching/EntityMixin.java @@ -40,7 +40,7 @@ private void cancelIfSkippable(CallbackInfo ci) { at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/BlockPos;getX()I", ordinal = 0) ) private void assumeNoTouchableBlock(CallbackInfo ci) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); if (bc.isTracking()) { bc.setCanSkipBlockTouching(true); } @@ -51,7 +51,7 @@ private void assumeNoTouchableBlock(CallbackInfo ci) { at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;onEntityCollision(Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/entity/Entity;)V") ) private void checkTouchableBlock(CallbackInfo ci, Box box, BlockPos blockPos, BlockPos blockPos2, BlockPos.Mutable mutable, int i, int j, int k, BlockState blockState) { - BlockCache bc = this.getBlockCache(); + BlockCache bc = this.lithium$getBlockCache(); if (bc.canSkipBlockTouching() && 0 != (((BlockStateFlagHolder)blockState).lithium$getAllFlags() & 1 << BlockStateFlags.ENTITY_TOUCHABLE.getIndex()) ) { diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/EntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/EntityMixin.java deleted file mode 100644 index 0e3669cb3..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/EntityMixin.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.jellysquid.mods.lithium.mixin.experimental.entity.block_caching.fluid_pushing; - -import it.unimi.dsi.fastutil.objects.Object2DoubleMap; -import me.jellysquid.mods.lithium.common.entity.block_tracking.BlockCache; -import me.jellysquid.mods.lithium.common.entity.block_tracking.BlockCacheProvider; -import net.minecraft.entity.Entity; -import net.minecraft.fluid.Fluid; -import net.minecraft.registry.tag.TagKey; -import net.minecraft.util.math.Box; -import net.minecraft.util.math.Vec3d; -import net.minecraft.world.World; -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.CallbackInfoReturnable; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -@Mixin(Entity.class) -public abstract class EntityMixin implements BlockCacheProvider { - @Shadow - public abstract Box getBoundingBox(); - - @Shadow - protected Object2DoubleMap> fluidHeight; - - @Shadow - public abstract World getWorld(); - - @Inject( - method = "updateMovementInFluid", - at = @At("HEAD"), - cancellable = true - ) - private void skipFluidSearchUsingCache(TagKey fluid, double speed, CallbackInfoReturnable cir) { - BlockCache bc = this.getUpdatedBlockCache((Entity)(Object)this); - double fluidHeight = bc.getStationaryFluidHeightOrDefault(fluid, -1d); - if (fluidHeight != -1d) { - this.fluidHeight.put(fluid, fluidHeight); //Note: If the region is unloaded in target method, this still puts 0. However, default return value is 0, and vanilla doesn't use any method that reveals this difference. - boolean touchingFluid = fluidHeight != 0d; - cir.setReturnValue(touchingFluid); - } - } - - @SuppressWarnings("InvalidInjectorMethodSignature") - @Inject( - method = "updateMovementInFluid", locals = LocalCapture.CAPTURE_FAILHARD, - at = @At(value = "INVOKE", target = "Lnet/minecraft/util/math/Vec3d;length()D", ordinal = 0, shift = At.Shift.BEFORE) - ) - private void cacheFluidSearchResult(TagKey fluid, double speed, CallbackInfoReturnable cir, Box box, int i1, int i2, int i3, int i4, int i5, int i6, double fluidHeight, boolean isPushedbyFluids, boolean touchingFluid, Vec3d fluidPush, int i7) { - BlockCache bc = this.getBlockCache(); - if (bc.isTracking() && fluidPush.lengthSquared() == 0d) { - if (touchingFluid == (fluidHeight == 0d)) { - throw new IllegalArgumentException("Expected fluid touching IFF fluid height is not 0! Fluid height: " + fluidHeight + " Touching fluid: " + touchingFluid + " Fluid Tag: " + fluid); - } - bc.setCachedFluidHeight(fluid, fluidHeight); - } - } -} diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/package-info.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/package-info.java deleted file mode 100644 index 81cd998ce..000000000 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/entity/block_caching/fluid_pushing/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -@MixinConfigOption(description = "Use the block listening system to cache entity fluid interaction when not touching fluid currents.", -depends = @MixinConfigDependency(dependencyPath = "mixin.util.block_tracking.block_listening")) -package me.jellysquid.mods.lithium.mixin.experimental.entity.block_caching.fluid_pushing; - -import net.caffeinemc.gradle.MixinConfigDependency; -import net.caffeinemc.gradle.MixinConfigOption; \ No newline at end of file diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/SectionedEntityCacheMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/SectionedEntityCacheMixin.java index 1428c7a29..4dabf931c 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/SectionedEntityCacheMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/SectionedEntityCacheMixin.java @@ -23,7 +23,7 @@ public abstract class SectionedEntityCacheMixin implements private Long2ObjectMap> trackingSections; @Override - public Iterable lithiumIterateEntitiesInTrackedSections() { + public Iterable lithium$IterateEntitiesInTrackedSections() { ObjectCollection> sections = this.trackingSections.values(); return () -> { ObjectIterator> sectionsIterator = sections.iterator(); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/ServerChunkManagerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/ServerChunkManagerMixin.java index 8d0a213d7..7d5fc0365 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/ServerChunkManagerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/experimental/spawning/ServerChunkManagerMixin.java @@ -20,6 +20,6 @@ public class ServerChunkManagerMixin { ) private Iterable iterateEntitiesChunkAware(ServerWorld serverWorld) { //noinspection unchecked - return ((ChunkAwareEntityIterable)((ServerEntityManagerAccessor) ((ServerWorldAccessor) serverWorld).getEntityManager()).getCache()).lithiumIterateEntitiesInTrackedSections(); + return ((ChunkAwareEntityIterable) ((ServerEntityManagerAccessor) ((ServerWorldAccessor) serverWorld).getEntityManager()).getCache()).lithium$IterateEntitiesInTrackedSections(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_entity_retrieval/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_entity_retrieval/WorldMixin.java index 1b09e07cf..bda8a2f09 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_entity_retrieval/WorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_entity_retrieval/WorldMixin.java @@ -32,7 +32,7 @@ public abstract class WorldMixin implements BlockEntityGetter, WorldAccess { public abstract Chunk getChunk(int chunkX, int chunkZ, ChunkStatus leastStatus, boolean create); @Override - public BlockEntity getLoadedExistingBlockEntity(BlockPos pos) { + public BlockEntity lithium$getLoadedExistingBlockEntity(BlockPos pos) { if (!this.isOutOfHeightLimit(pos)) { if (this.isClient || Thread.currentThread() == this.thread) { Chunk chunk = this.getChunk(ChunkSectionPos.getSectionCoord(pos.getX()), ChunkSectionPos.getSectionCoord(pos.getZ()), ChunkStatus.FULL, false); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/ChunkSectionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/ChunkSectionMixin.java index e34b57420..b1e241931 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/ChunkSectionMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/ChunkSectionMixin.java @@ -5,6 +5,7 @@ import me.jellysquid.mods.lithium.common.entity.block_tracking.SectionedBlockChangeTracker; import net.minecraft.block.BlockState; import net.minecraft.network.PacketByteBuf; +import net.minecraft.util.math.ChunkSectionPos; import net.minecraft.world.chunk.ChunkSection; import net.minecraft.world.chunk.PalettedContainer; import org.spongepowered.asm.mixin.Final; @@ -30,19 +31,34 @@ public abstract class ChunkSectionMixin implements BlockCountingSection, BlockLi @Shadow @Final private PalettedContainer blockStateContainer; + @Unique private short[] countsByFlag = null; + @Unique private ChunkSectionChangeCallback changeListener; + @Unique private short listeningMask; + @Unique + private static void addToFlagCount(short[] countsByFlag, BlockState state, short change) { + int flags = ((BlockStateFlagHolder) state).lithium$getAllFlags(); + int i; + while ((i = Integer.numberOfTrailingZeros(flags)) < 32 && i < countsByFlag.length) { + //either count up by one (prevFlag not set) or down by one (prevFlag set) + countsByFlag[i] += change; + flags &= ~(1 << i); + } + } + @Override - public boolean mayContainAny(TrackedBlockStatePredicate trackedBlockStatePredicate) { + public boolean lithium$mayContainAny(TrackedBlockStatePredicate trackedBlockStatePredicate) { if (this.countsByFlag == null) { fastInitClientCounts(); } return this.countsByFlag[trackedBlockStatePredicate.getIndex()] != (short) 0; } + @Unique private void fastInitClientCounts() { this.countsByFlag = new short[BlockStateFlags.NUM_TRACKED_FLAGS]; for (TrackedBlockStatePredicate trackedBlockStatePredicate : BlockStateFlags.TRACKED_FLAGS) { @@ -64,20 +80,10 @@ private void fastInitClientCounts() { private void initFlagCounters(PalettedContainer palettedContainer, PalettedContainer.Counter consumer) { palettedContainer.count((state, count) -> { consumer.accept(state, count); - addToFlagCount(this.countsByFlag, state, count); + addToFlagCount(this.countsByFlag, state, (short) count); }); } - private static void addToFlagCount(short[] countsByFlag, BlockState state, int change) { - int flags = ((BlockStateFlagHolder) state).lithium$getAllFlags(); - int i; - while ((i = Integer.numberOfTrailingZeros(flags)) < 32 && i < countsByFlag.length) { - //either count up by one (prevFlag not set) or down by one (prevFlag set) - countsByFlag[i] += change; - flags &= ~(1 << i); - } - } - @Inject(method = "calculateCounts()V", at = @At("HEAD")) private void createFlagCounters(CallbackInfo ci) { this.countsByFlag = new short[BlockStateFlags.NUM_TRACKED_FLAGS]; @@ -102,6 +108,11 @@ private void resetData(PacketByteBuf buf, CallbackInfo ci) { locals = LocalCapture.CAPTURE_FAILHARD ) private void updateFlagCounters(int x, int y, int z, BlockState newState, boolean lock, CallbackInfoReturnable cir, BlockState oldState) { + this.lithium$trackBlockStateChange(newState, oldState); + } + + @Override + public void lithium$trackBlockStateChange(BlockState newState, BlockState oldState) { short[] countsByFlag = this.countsByFlag; if (countsByFlag == null) { return; @@ -122,7 +133,7 @@ private void updateFlagCounters(int x, int y, int z, BlockState newState, boolea int flagBit = 1 << flagIndex; //either count up by one (prevFlag not set) or down by one (prevFlag set) if ((flagsXOR & flagBit) != 0) { - countsByFlag[flagIndex] += 1 - (((prevFlags >>> flagIndex) & 1) << 1); + countsByFlag[flagIndex] += (short) (1 - (((prevFlags >>> flagIndex) & 1) << 1)); } if ((this.listeningMask & flagBit) != 0) { this.listeningMask = this.changeListener.onBlockChange(flagIndex, this); @@ -132,7 +143,7 @@ private void updateFlagCounters(int x, int y, int z, BlockState newState, boolea } @Override - public void addToCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker) { + public void lithium$addToCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker) { if (this.changeListener == null) { this.changeListener = new ChunkSectionChangeCallback(); } @@ -141,17 +152,19 @@ public void addToCallback(ListeningBlockStatePredicate blockGroup, SectionedBloc } @Override - public void removeFromCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker) { + public void lithium$removeFromCallback(ListeningBlockStatePredicate blockGroup, SectionedBlockChangeTracker tracker) { if (this.changeListener != null) { this.listeningMask = this.changeListener.removeTracker(tracker, blockGroup); } } - private boolean isListening(ListeningBlockStatePredicate blockGroup) { - return (this.listeningMask & (1 << blockGroup.getIndex())) != 0; - } + @Override + @Unique + public void lithium$invalidateListeningSection(ChunkSectionPos sectionPos) { + //TODO call this on chunk unload. Entities should already be unloaded, but just to be safe, try to unregister too - public void invalidateSection() { - //TODO on section unload, unregister all kinds of stuff + if ((this.listeningMask) != 0) { + this.changeListener.onChunkSectionInvalidated(sectionPos); + } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/block_listening/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/block_listening/WorldMixin.java index 9d5d018f4..c5dbce752 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/block_listening/WorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/block_tracking/block_listening/WorldMixin.java @@ -11,12 +11,12 @@ public class WorldMixin implements LithiumInternerWrapper blockChangeTrackers = new LithiumInterner<>(); @Override - public SectionedBlockChangeTracker getCanonical(SectionedBlockChangeTracker value) { + public SectionedBlockChangeTracker lithium$getCanonical(SectionedBlockChangeTracker value) { return this.blockChangeTrackers.getCanonical(value); } @Override - public void deleteCanonical(SectionedBlockChangeTracker value) { + public void lithium$deleteCanonical(SectionedBlockChangeTracker value) { this.blockChangeTrackers.deleteCanonical(value); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/ChunkCacheMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/ChunkCacheMixin.java index c231e88af..dd1f1a702 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/ChunkCacheMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/ChunkCacheMixin.java @@ -14,7 +14,7 @@ public abstract class ChunkCacheMixin implements ChunkView { protected abstract Chunk getChunk(int chunkX, int chunkZ); @Override - public @Nullable Chunk getLoadedChunk(int chunkX, int chunkZ) { + public @Nullable Chunk lithium$getLoadedChunk(int chunkX, int chunkZ) { return this.getChunk(chunkX, chunkZ); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/WorldViewMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/WorldViewMixin.java index 10b2da380..06f7bbb86 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/WorldViewMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/chunk_access/WorldViewMixin.java @@ -15,7 +15,7 @@ public interface WorldViewMixin extends ChunkView { @Nullable Chunk getChunk(int var1, int var2, ChunkStatus var3, boolean var4); @Override - default @Nullable Chunk getLoadedChunk(int chunkX, int chunkZ) { + default @Nullable Chunk lithium$getLoadedChunk(int chunkX, int chunkZ) { return this.getChunk(chunkX, chunkZ, ChunkStatus.FULL, false); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/EntityTrackingSectionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/EntityTrackingSectionMixin.java index 71210a1ed..b8adf3a87 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/EntityTrackingSectionMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/EntityTrackingSectionMixin.java @@ -1,5 +1,6 @@ package me.jellysquid.mods.lithium.mixin.util.entity_movement_tracking; +import com.llamalad7.mixinextras.injector.ModifyReturnValue; import it.unimi.dsi.fastutil.objects.ReferenceOpenHashSet; import me.jellysquid.mods.lithium.common.entity.PositionedEntityTrackingSection; import me.jellysquid.mods.lithium.common.entity.movement_tracker.EntityMovementTrackerSection; @@ -11,28 +12,30 @@ import net.minecraft.world.entity.SectionedEntityCache; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.ModifyVariable; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.ArrayList; @Mixin(EntityTrackingSection.class) -public abstract class EntityTrackingSectionMixin implements EntityMovementTrackerSection, PositionedEntityTrackingSection { +public abstract class EntityTrackingSectionMixin implements EntityMovementTrackerSection, PositionedEntityTrackingSection { @Shadow private EntityTrackingStatus status; @Shadow public abstract boolean isEmpty(); + @Unique private final ReferenceOpenHashSet> sectionVisibilityListeners = new ReferenceOpenHashSet<>(0); + @Unique @SuppressWarnings("unchecked") private final ArrayList>[] entityMovementListenersByType = new ArrayList[MovementTrackerHelper.NUM_MOVEMENT_NOTIFYING_CLASSES]; + @Unique private final long[] lastEntityMovementByType = new long[MovementTrackerHelper.NUM_MOVEMENT_NOTIFYING_CLASSES]; @Override - public void addListener(SectionedEntityMovementTracker listener) { + public void lithium$addListener(SectionedEntityMovementTracker listener) { this.sectionVisibilityListeners.add(listener); if (this.status.shouldTrack()) { listener.onSectionEnteredRange(this); @@ -40,18 +43,18 @@ public void addListener(SectionedEntityMovementTracker listener) { } @Override - public void removeListener(SectionedEntityCache sectionedEntityCache, SectionedEntityMovementTracker listener) { + public void lithium$removeListener(SectionedEntityCache sectionedEntityCache, SectionedEntityMovementTracker listener) { boolean removed = this.sectionVisibilityListeners.remove(listener); if (this.status.shouldTrack() && removed) { listener.onSectionLeftRange(this); } if (this.isEmpty()) { - sectionedEntityCache.removeSection(this.getPos()); + sectionedEntityCache.removeSection(this.lithium$getPos()); } } @Override - public void trackEntityMovement(int notificationMask, long time) { + public void lithium$trackEntityMovement(int notificationMask, long time) { long[] lastEntityMovementByType = this.lastEntityMovementByType; int size = lastEntityMovementByType.length; int mask; @@ -72,15 +75,13 @@ public void trackEntityMovement(int notificationMask, long time) { } @Override - public long getChangeTime(int trackedClass) { + public long lithium$getChangeTime(int trackedClass) { return this.lastEntityMovementByType[trackedClass]; } - @Inject(method = "isEmpty()Z", at = @At(value = "HEAD"), cancellable = true) - public void isEmpty(CallbackInfoReturnable cir) { - if (!this.sectionVisibilityListeners.isEmpty()) { - cir.setReturnValue(false); - } + @ModifyReturnValue(method = "isEmpty()Z", at = @At(value = "RETURN")) + public boolean modifyIsEmpty(boolean previousIsEmpty) { + return previousIsEmpty && this.sectionVisibilityListeners.isEmpty(); } @@ -105,7 +106,7 @@ public EntityTrackingStatus swapStatus(final EntityTrackingStatus newStatus) { } @Override - public void listenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass) { + public void lithium$listenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass) { if (this.entityMovementListenersByType[trackedClass] == null) { this.entityMovementListenersByType[trackedClass] = new ArrayList<>(); } @@ -113,7 +114,7 @@ public void listenToMovementOnce(SectionedEntityMoveme } @Override - public void removeListenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass) { + public void lithium$removeListenToMovementOnce(SectionedEntityMovementTracker listener, int trackedClass) { if (this.entityMovementListenersByType[trackedClass] != null) { this.entityMovementListenersByType[trackedClass].remove(listener); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/SectionedEntityCacheMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/SectionedEntityCacheMixin.java index 811cce8a9..7b9264f0a 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/SectionedEntityCacheMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/SectionedEntityCacheMixin.java @@ -13,12 +13,12 @@ public class SectionedEntityCacheMixin implements Movement private final Object2ReferenceOpenHashMap, SectionedEntityMovementTracker> sectionEntityMovementTrackers = new Object2ReferenceOpenHashMap<>(); @Override - public void remove(SectionedEntityMovementTracker tracker) { + public void lithium$remove(SectionedEntityMovementTracker tracker) { this.sectionEntityMovementTrackers.remove(tracker); } @Override - public > S deduplicate(S tracker) { + public > S lithium$deduplicate(S tracker) { //noinspection unchecked S storedTracker = (S) this.sectionEntityMovementTrackers.putIfAbsent(tracker, tracker); return storedTracker == null ? tracker : storedTracker; diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/ServerEntityManagerListenerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/ServerEntityManagerListenerMixin.java index f86655272..fe4f32831 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/ServerEntityManagerListenerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_movement_tracking/ServerEntityManagerListenerMixin.java @@ -65,12 +65,12 @@ private void onRemoveEntity(Entity.RemovalReason reason, CallbackInfo ci) { private void notifyMovementListeners() { if (this.notificationMask != 0) { - ((EntityMovementTrackerSection) this.section).trackEntityMovement(this.notificationMask, ((Entity) this.entity).getEntityWorld().getTime()); + ((EntityMovementTrackerSection) this.section).lithium$trackEntityMovement(this.notificationMask, ((Entity) this.entity).getEntityWorld().getTime()); } } @Override - public int setNotificationMask(int notificationMask) { + public int lithium$setNotificationMask(int notificationMask) { int oldNotificationMask = this.notificationMask; this.notificationMask = notificationMask; return oldNotificationMask; diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/EntityTrackingSectionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/EntityTrackingSectionMixin.java index 985e797e8..99d015445 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/EntityTrackingSectionMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/EntityTrackingSectionMixin.java @@ -9,12 +9,12 @@ public class EntityTrackingSectionMixin implements PositionedEntityTrackingSecti private long pos; @Override - public void setPos(long chunkSectionPos) { + public void lithium$setPos(long chunkSectionPos) { this.pos = chunkSectionPos; } @Override - public long getPos() { + public long lithium$getPos() { return this.pos; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/SectionedEntityCacheMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/SectionedEntityCacheMixin.java index df6384b2c..66fe0bdfc 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/SectionedEntityCacheMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/entity_section_position/SectionedEntityCacheMixin.java @@ -13,6 +13,6 @@ public class SectionedEntityCacheMixin { @Inject(method = "addSection(J)Lnet/minecraft/world/entity/EntityTrackingSection;", at = @At("RETURN")) private void rememberPos(long sectionPos, CallbackInfoReturnable> cir) { - ((PositionedEntityTrackingSection) cir.getReturnValue()).setPos(sectionPos); + ((PositionedEntityTrackingSection) cir.getReturnValue()).lithium$setPos(sectionPos); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/BlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/BlockEntityMixin.java index e2b112a87..28670d3aa 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/BlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/BlockEntityMixin.java @@ -23,7 +23,7 @@ public class BlockEntityMixin { ) private void updateStackListTracking(CallbackInfo ci) { if (this.world != null && !this.world.isClient() && this instanceof InventoryChangeTracker inventoryChangeTracker) { - inventoryChangeTracker.emitRemoved(); + inventoryChangeTracker.lithium$emitRemoved(); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/ChestBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/ChestBlockEntityMixin.java index 722b3b8c3..1b8217bf1 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/ChestBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/ChestBlockEntityMixin.java @@ -6,7 +6,6 @@ import net.minecraft.block.entity.ChestBlockEntity; import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.util.math.BlockPos; -import org.spongepowered.asm.mixin.Intrinsic; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -18,17 +17,17 @@ protected ChestBlockEntityMixin(BlockEntityType blockEntityType, BlockPos blo super(blockEntityType, blockPos, blockState); } - @SuppressWarnings("deprecation") - // @Intrinsic + /*@SuppressWarnings("deprecation") + @Intrinsic @Override public void setCachedState(BlockState state) { super.setCachedState(state); - } + }*/ - @SuppressWarnings({"MixinAnnotationTarget", "UnresolvedMixinReference"}) + // @SuppressWarnings({"MixinAnnotationTarget", "UnresolvedMixinReference"}) @Inject(method = "setCachedState(Lnet/minecraft/block/BlockState;)V", at = @At("RETURN")) private void emitRemovedOnSetCachedState(CallbackInfo ci) { //Handle switching double / single chest state - this.emitRemoved(); + this.lithium$emitRemoved(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/LockableContainerBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/LockableContainerBlockEntityMixin.java index 5092c5959..796ff2f74 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/LockableContainerBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/LockableContainerBlockEntityMixin.java @@ -18,18 +18,18 @@ public abstract class LockableContainerBlockEntityMixin implements InventoryChan ReferenceArraySet inventoryHandlingTypeListeners = null; @Override - public void emitContentModified() { + public void lithium$emitContentModified() { ReferenceArraySet inventoryChangeListeners = this.inventoryChangeListeners; if (inventoryChangeListeners != null) { for (InventoryChangeListener inventoryChangeListener : inventoryChangeListeners) { - inventoryChangeListener.handleInventoryContentModified(this); + inventoryChangeListener.lithium$handleInventoryContentModified(this); } inventoryChangeListeners.clear(); } } @Override - public void emitStackListReplaced() { + public void lithium$emitStackListReplaced() { ReferenceArraySet listeners = this.inventoryHandlingTypeListeners; if (listeners != null && !listeners.isEmpty()) { for (InventoryChangeListener inventoryChangeListener : listeners) { @@ -46,17 +46,17 @@ public void emitStackListReplaced() { } @Override - public void emitRemoved() { + public void lithium$emitRemoved() { ReferenceArraySet listeners = this.inventoryHandlingTypeListeners; if (listeners != null && !listeners.isEmpty()) { for (InventoryChangeListener listener : listeners) { - listener.handleInventoryRemoved(this); + listener.lithium$handleInventoryRemoved(this); } listeners.clear(); } if (this instanceof InventoryChangeListener listener) { - listener.handleInventoryRemoved(this); + listener.lithium$handleInventoryRemoved(this); } this.invalidateChangeListening(); @@ -74,15 +74,15 @@ private void invalidateChangeListening() { } @Override - public void emitFirstComparatorAdded() { + public void lithium$emitFirstComparatorAdded() { ReferenceArraySet inventoryChangeListeners = this.inventoryChangeListeners; if (inventoryChangeListeners != null && !inventoryChangeListeners.isEmpty()) { - inventoryChangeListeners.removeIf(inventoryChangeListener -> inventoryChangeListener.handleComparatorAdded(this)); + inventoryChangeListeners.removeIf(inventoryChangeListener -> inventoryChangeListener.lithium$handleComparatorAdded(this)); } } @Override - public void forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker) { + public void lithium$forwardContentChangeOnce(InventoryChangeListener inventoryChangeListener, LithiumStackList stackList, InventoryChangeTracker thisTracker) { if (this.inventoryChangeListeners == null) { this.inventoryChangeListeners = new ReferenceArraySet<>(1); } @@ -92,7 +92,7 @@ public void forwardContentChangeOnce(InventoryChangeListener inventoryChangeList } @Override - public void forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { + public void lithium$forwardMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { if (this.inventoryHandlingTypeListeners == null) { this.inventoryHandlingTypeListeners = new ReferenceArraySet<>(1); } @@ -100,7 +100,7 @@ public void forwardMajorInventoryChanges(InventoryChangeListener inventoryChange } @Override - public void stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { + public void lithium$stopForwardingMajorInventoryChanges(InventoryChangeListener inventoryChangeListener) { if (this.inventoryHandlingTypeListeners != null) { this.inventoryHandlingTypeListeners.remove(inventoryChangeListener); } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/StackListReplacementTracking.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/StackListReplacementTracking.java index f3130f124..305998e17 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/StackListReplacementTracking.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_change_listening/StackListReplacementTracking.java @@ -4,6 +4,7 @@ import net.minecraft.block.entity.*; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper; import net.minecraft.util.collection.DefaultedList; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -25,50 +26,50 @@ public abstract static class InventoryChangeTrackingBrewingStandBlockEntity impl @Mixin(LockableContainerBlockEntity.class) public abstract static class StackListReplacementTrackingLockableContainerBlockEntity { @Inject(method = "readNbt", at = @At("RETURN" )) - public void readNbtStackListReplacement(NbtCompound nbt, CallbackInfo ci) { + public void readNbtStackListReplacement(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup, CallbackInfo ci) { if (this instanceof InventoryChangeTracker inventoryChangeTracker) { - inventoryChangeTracker.emitStackListReplaced(); + inventoryChangeTracker.lithium$emitStackListReplaced(); } } } @Mixin(BarrelBlockEntity.class) public abstract static class InventoryChangeTrackingBarrelBlockEntity implements InventoryChangeTracker { - @Inject(method = "setInvStackList", at = @At("RETURN" )) + @Inject(method = "setHeldStacks", at = @At("RETURN")) public void setInventoryStackListReplacement(DefaultedList list, CallbackInfo ci) { - this.emitStackListReplaced(); + this.lithium$emitStackListReplaced(); } } @Mixin(ChestBlockEntity.class) public abstract static class InventoryChangeTrackingChestBlockEntity implements InventoryChangeTracker { - @Inject(method = "setInvStackList", at = @At("RETURN" )) + @Inject(method = "setHeldStacks", at = @At("RETURN")) public void setInventoryStackListReplacement(DefaultedList list, CallbackInfo ci) { - this.emitStackListReplaced(); + this.lithium$emitStackListReplaced(); } } @Mixin(DispenserBlockEntity.class) public abstract static class InventoryChangeTrackingDispenserBlockEntity implements InventoryChangeTracker { - @Inject(method = "setInvStackList", at = @At("RETURN" )) + @Inject(method = "setHeldStacks", at = @At("RETURN")) public void setInventoryStackListReplacement(DefaultedList list, CallbackInfo ci) { - this.emitStackListReplaced(); + this.lithium$emitStackListReplaced(); } } @Mixin(HopperBlockEntity.class) public abstract static class InventoryChangeTrackingHopperBlockEntity implements InventoryChangeTracker { - @Inject(method = "setInvStackList", at = @At("RETURN" )) + @Inject(method = "setHeldStacks", at = @At("RETURN")) public void setInventoryStackListReplacement(DefaultedList list, CallbackInfo ci) { - this.emitStackListReplaced(); + this.lithium$emitStackListReplaced(); } } @Mixin(ShulkerBoxBlockEntity.class) public abstract static class InventoryChangeTrackingShulkerBoxBlockEntity implements InventoryChangeTracker { - @Inject(method = "setInvStackList", at = @At("RETURN" )) + @Inject(method = "setHeldStacks", at = @At("RETURN")) public void setInventoryStackListReplacement(DefaultedList list, CallbackInfo ci) { - this.emitStackListReplaced(); + this.lithium$emitStackListReplaced(); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_comparator_tracking/BlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_comparator_tracking/BlockEntityMixin.java index f67e238d7..7bf329802 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_comparator_tracking/BlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/util/inventory_comparator_tracking/BlockEntityMixin.java @@ -43,19 +43,19 @@ private void init(BlockEntityType type, BlockPos pos, BlockState state, Callb } @Override - public void onComparatorAdded(Direction direction, int offset) { + public void lithium$onComparatorAdded(Direction direction, int offset) { byte hasComparators = this.hasComparators; if (direction.getAxis() != Direction.Axis.Y && hasComparators != COMPARATOR_PRESENT && offset >= 1 && offset <= 2) { this.hasComparators = 1; if (this instanceof InventoryChangeTracker inventoryChangeTracker) { - inventoryChangeTracker.emitFirstComparatorAdded(); + inventoryChangeTracker.lithium$emitFirstComparatorAdded(); } } } @Override - public boolean hasAnyComparatorNearby() { + public boolean lithium$hasAnyComparatorNearby() { if (this.hasComparators == UNKNOWN) { this.hasComparators = ComparatorTracking.findNearbyComparators(this.world, this.pos) ? COMPARATOR_PRESENT : COMPARATOR_ABSENT; } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/WorldChunkMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/WorldChunkMixin.java index e33a6d004..16b391817 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/WorldChunkMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/WorldChunkMixin.java @@ -25,7 +25,7 @@ public class WorldChunkMixin { ) private void setBlockEntityTickingOrder(BlockEntity blockEntity, BlockEntityTicker blockEntityTicker, BlockPos pos, @Coerce Object wrappedBlockEntityTickInvoker, CallbackInfoReturnable cir, BlockEntityTickInvoker blockEntityTickInvoker, @Coerce Object wrappedBlockEntityTickInvoker2) { if (blockEntity instanceof SleepingBlockEntity sleepingBlockEntity) { - sleepingBlockEntity.setTickWrapper((WrappedBlockEntityTickInvokerAccessor) wrappedBlockEntityTickInvoker2); + sleepingBlockEntity.lithium$setTickWrapper((WrappedBlockEntityTickInvokerAccessor) wrappedBlockEntityTickInvoker2); } } @@ -38,7 +38,7 @@ private void setBlockEntityTickingOrder(BlockEntity blockEntity, BlockEntityTick ) private void setBlockEntityTickingOrder(BlockEntity blockEntity, BlockEntityTicker blockEntityTicker, BlockPos pos, @Coerce Object wrappedBlockEntityTickInvoker, CallbackInfoReturnable cir, BlockEntityTickInvoker blockEntityTickInvoker) { if (blockEntity instanceof SleepingBlockEntity sleepingBlockEntity) { - sleepingBlockEntity.setTickWrapper((WrappedBlockEntityTickInvokerAccessor) wrappedBlockEntityTickInvoker); + sleepingBlockEntity.lithium$setTickWrapper((WrappedBlockEntityTickInvokerAccessor) wrappedBlockEntityTickInvoker); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/brewing_stand/BrewingStandBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/brewing_stand/BrewingStandBlockEntityMixin.java index 780ec38c4..23b863b36 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/brewing_stand/BrewingStandBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/brewing_stand/BrewingStandBlockEntityMixin.java @@ -31,23 +31,23 @@ public BrewingStandBlockEntityMixin(BlockEntityType type, BlockPos pos, Block } @Override - public WrappedBlockEntityTickInvokerAccessor getTickWrapper() { + public WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper() { return tickWrapper; } @Override - public void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { + public void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { this.tickWrapper = tickWrapper; - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } @Override - public BlockEntityTickInvoker getSleepingTicker() { + public BlockEntityTickInvoker lithium$getSleepingTicker() { return sleepingTicker; } @Override - public void setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { + public void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { this.sleepingTicker = sleepingTicker; } @@ -63,7 +63,7 @@ private static void wakeUpOnMarkDirty(World world, BlockPos pos, BlockState stat private void checkSleep(BlockState state) { if (this.brewTime == 0 && state.isOf(Blocks.BREWING_STAND) && this.world != null) { - this.startSleeping(); + this.lithium$startSleeping(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/CampfireBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/CampfireBlockEntityMixin.java index 39bfa7b48..1c30143fa 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/CampfireBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/CampfireBlockEntityMixin.java @@ -9,6 +9,7 @@ import net.minecraft.entity.Entity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; +import net.minecraft.registry.RegistryWrapper; import net.minecraft.util.math.BlockPos; import net.minecraft.world.chunk.BlockEntityTickInvoker; import org.spongepowered.asm.mixin.Mixin; @@ -28,23 +29,23 @@ public CampfireBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockStat } @Override - public WrappedBlockEntityTickInvokerAccessor getTickWrapper() { + public WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper() { return tickWrapper; } @Override - public void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { + public void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { this.tickWrapper = tickWrapper; - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } @Override - public BlockEntityTickInvoker getSleepingTicker() { + public BlockEntityTickInvoker lithium$getSleepingTicker() { return sleepingTicker; } @Override - public void setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { + public void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { this.sleepingTicker = sleepingTicker; } @@ -61,7 +62,7 @@ private void wakeUpOnAddItem(Entity user, ItemStack stack, int cookTime, Callbac method = "readNbt", at = @At(value = "RETURN") ) - private void wakeUpOnReadNbt(NbtCompound nbt, CallbackInfo ci) { + private void wakeUpOnReadNbt(NbtCompound nbt, RegistryWrapper.WrapperLookup registryLookup, CallbackInfo ci) { this.wakeUpNow(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/lit/CampfireBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/lit/CampfireBlockEntityMixin.java index f0d6e15c6..f12d74b0d 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/lit/CampfireBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/lit/CampfireBlockEntityMixin.java @@ -28,7 +28,7 @@ public CampfireBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockStat private static void trySleepLit(World world, BlockPos pos, BlockState state, CampfireBlockEntity campfire, CallbackInfo ci, boolean hadProgress) { if (!hadProgress) { CampfireBlockEntityMixin self = (CampfireBlockEntityMixin) (Object) campfire; - self.startSleeping(); + self.lithium$startSleeping(); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/unlit/CampfireBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/unlit/CampfireBlockEntityMixin.java index 3a04dc3ec..3fc9ffc24 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/unlit/CampfireBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/campfire/unlit/CampfireBlockEntityMixin.java @@ -28,7 +28,7 @@ public CampfireBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockStat private static void trySleepUnlit(World world, BlockPos pos, BlockState state, CampfireBlockEntity campfire, CallbackInfo ci, boolean hadProgress) { if (!hadProgress) { CampfireBlockEntityMixin self = (CampfireBlockEntityMixin) (Object) campfire; - self.startSleeping(); + self.lithium$startSleeping(); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/furnace/AbstractFurnaceBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/furnace/AbstractFurnaceBlockEntityMixin.java index 175c2b67b..2078bd279 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/furnace/AbstractFurnaceBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/furnace/AbstractFurnaceBlockEntityMixin.java @@ -33,23 +33,23 @@ public AbstractFurnaceBlockEntityMixin(BlockEntityType type, BlockPos pos, Bl } @Override - public WrappedBlockEntityTickInvokerAccessor getTickWrapper() { + public WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper() { return tickWrapper; } @Override - public void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { + public void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { this.tickWrapper = tickWrapper; - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } @Override - public BlockEntityTickInvoker getSleepingTicker() { + public BlockEntityTickInvoker lithium$getSleepingTicker() { return sleepingTicker; } @Override - public void setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { + public void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { this.sleepingTicker = sleepingTicker; } @@ -60,7 +60,7 @@ private static void checkSleep(World world, BlockPos pos, BlockState state, Abst private void checkSleep(BlockState state) { if (!this.isBurning() && this.cookTime == 0 && (state.isOf(Blocks.FURNACE) || state.isOf(Blocks.BLAST_FURNACE) || state.isOf(Blocks.SMOKER)) && this.world != null) { - this.startSleeping(); + this.lithium$startSleeping(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/hopper/HopperBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/hopper/HopperBlockEntityMixin.java index 459ae7965..b109cc188 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/hopper/HopperBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/hopper/HopperBlockEntityMixin.java @@ -31,52 +31,52 @@ public class HopperBlockEntityMixin extends BlockEntity implements SleepingBlock private WrappedBlockEntityTickInvokerAccessor tickWrapper = null; private BlockEntityTickInvoker sleepingTicker = null; + @Inject( + method = "insertAndExtract", + at = @At(value = "RETURN", ordinal = 2) + ) + private static void sleepIfNoCooldownAndLocked(World world, BlockPos pos, BlockState state, HopperBlockEntity blockEntity, BooleanSupplier booleanSupplier, CallbackInfoReturnable cir) { + if (!((HopperBlockEntityMixin) (Object) blockEntity).needsCooldown() && + !((HopperBlockEntityMixin) (Object) blockEntity).isSleeping() && + !state.get(HopperBlock.ENABLED)) { + ((HopperBlockEntityMixin) (Object) blockEntity).lithium$startSleeping(); + } + } + @Override - public WrappedBlockEntityTickInvokerAccessor getTickWrapper() { + public WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper() { return tickWrapper; } @Override - public void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { + public void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { this.tickWrapper = tickWrapper; - this.setSleepingTicker(null); + this.lithium$setSleepingTicker(null); } @Override - public BlockEntityTickInvoker getSleepingTicker() { + public BlockEntityTickInvoker lithium$getSleepingTicker() { return sleepingTicker; } - @Override - public void setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { - this.sleepingTicker = sleepingTicker; - } - public HopperBlockEntityMixin(BlockEntityType type, BlockPos pos, BlockState state) { super(type, pos, state); } - @Inject( - method = "insertAndExtract", - at = @At(value = "RETURN", ordinal = 2) - ) - private static void sleepIfNoCooldownAndLocked(World world, BlockPos pos, BlockState state, HopperBlockEntity blockEntity, BooleanSupplier booleanSupplier, CallbackInfoReturnable cir) { - if (!((HopperBlockEntityMixin) (Object) blockEntity).needsCooldown() && - !((HopperBlockEntityMixin) (Object) blockEntity).isSleeping() && - !state.get(HopperBlock.ENABLED)) { - ((HopperBlockEntityMixin) (Object) blockEntity).startSleeping(); - } + @Override + public void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { + this.sleepingTicker = sleepingTicker; } @Override - public boolean startSleeping() { + public boolean lithium$startSleeping() { if (this.isSleeping()) { return false; } - WrappedBlockEntityTickInvokerAccessor tickWrapper = this.getTickWrapper(); + WrappedBlockEntityTickInvokerAccessor tickWrapper = this.lithium$getTickWrapper(); if (tickWrapper != null) { - this.setSleepingTicker(tickWrapper.getWrapped()); + this.lithium$setSleepingTicker(tickWrapper.getWrapped()); tickWrapper.callSetWrapped(SleepingBlockEntity.SLEEPING_BLOCK_ENTITY_TICKER); // Set the last tick time to max value, so other hoppers transferring into this hopper will set it to 7gt diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/shulker_box/ShulkerBoxBlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/shulker_box/ShulkerBoxBlockEntityMixin.java index cfad264bf..e0cc32bad 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/shulker_box/ShulkerBoxBlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/sleeping/shulker_box/ShulkerBoxBlockEntityMixin.java @@ -26,22 +26,22 @@ public class ShulkerBoxBlockEntityMixin implements SleepingBlockEntity { private BlockEntityTickInvoker sleepingTicker = null; @Override - public WrappedBlockEntityTickInvokerAccessor getTickWrapper() { + public WrappedBlockEntityTickInvokerAccessor lithium$getTickWrapper() { return tickWrapper; } @Override - public void setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { + public void lithium$setTickWrapper(WrappedBlockEntityTickInvokerAccessor tickWrapper) { this.tickWrapper = tickWrapper; } @Override - public BlockEntityTickInvoker getSleepingTicker() { + public BlockEntityTickInvoker lithium$getSleepingTicker() { return sleepingTicker; } @Override - public void setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { + public void lithium$setSleepingTicker(BlockEntityTickInvoker sleepingTicker) { this.sleepingTicker = sleepingTicker; } @@ -61,7 +61,7 @@ private void wakeUpOnSyncedBlockEvent(int type, int data, CallbackInfoReturnable ) private void sleepOnAnimationEnd(World world, BlockPos pos, BlockState state, CallbackInfo ci) { if (this.animationStage == ShulkerBoxBlockEntity.AnimationStage.CLOSED && this.prevAnimationProgress == 0.0f && this.animationProgress == 0.0f) { - this.startSleeping(); + this.lithium$startSleeping(); } } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/BlockEntityMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/BlockEntityMixin.java index 5cc99cea5..6bd289155 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/BlockEntityMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/BlockEntityMixin.java @@ -29,7 +29,7 @@ private void updateSupportCache(BlockState cachedState, CallbackInfo ci) { } @Override - public boolean isSupported() { + public boolean lithium$isSupported() { return this.supportTestResult; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/DirectBlockEntityTickInvokerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/DirectBlockEntityTickInvokerMixin.java index e7326f175..d37c7022b 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/DirectBlockEntityTickInvokerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/support_cache/DirectBlockEntityTickInvokerMixin.java @@ -48,7 +48,7 @@ private BlockState getCachedState(WorldChunk chunk, BlockPos pos) { ) ) private boolean cachedIsSupported(BlockEntityType blockEntityType, BlockState block) { - return ((SupportCache) this.blockEntity).isSupported(); + return ((SupportCache) this.blockEntity).lithium$isSupported(); } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/world_border/DirectBlockEntityTickInvokerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/world_border/DirectBlockEntityTickInvokerMixin.java index 1c0cda149..1a9b128ac 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/world_border/DirectBlockEntityTickInvokerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/block_entity_ticking/world_border/DirectBlockEntityTickInvokerMixin.java @@ -75,7 +75,7 @@ private void startWorldBorderCaching() { } @Override - public void onWorldBorderShapeChange(WorldBorder worldBorder) { + public void lithium$onWorldBorderShapeChange(WorldBorder worldBorder) { this.worldBorderState = (byte) 0; } } diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ChunkHolderMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ChunkHolderMixin.java index 361f75d06..046213396 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ChunkHolderMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ChunkHolderMixin.java @@ -1,8 +1,8 @@ package me.jellysquid.mods.lithium.mixin.world.chunk_access; -import com.mojang.datafixers.util.Either; import me.jellysquid.mods.lithium.common.world.chunk.ChunkHolderExtended; import net.minecraft.server.world.ChunkHolder; +import net.minecraft.server.world.OptionalChunk; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.WorldChunk; import org.spongepowered.asm.mixin.Final; @@ -14,27 +14,26 @@ @Mixin(ChunkHolder.class) public class ChunkHolderMixin implements ChunkHolderExtended { - @Shadow - @Final - private AtomicReferenceArray>> futuresByStatus; + ; @Shadow WorldChunk currentlyLoading; + private AtomicReferenceArray>> futuresByStatus; private long lastRequestTime; @Override - public CompletableFuture> getFutureByStatus(int index) { + public CompletableFuture> lithium$getFutureByStatus(int index) { return this.futuresByStatus.get(index); } @Override - public void setFutureForStatus(int index, CompletableFuture> future) { + public void lithium$setFutureForStatus(int index, CompletableFuture> future) { this.futuresByStatus.set(index, future); } @Override - public boolean updateLastAccessTime(long time) { + public boolean lithium$updateLastAccessTime(long time) { long prev = this.lastRequestTime; this.lastRequestTime = time; diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ServerChunkManagerMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ServerChunkManagerMixin.java index 9c2035782..a95550d56 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ServerChunkManagerMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/chunk_access/ServerChunkManagerMixin.java @@ -1,6 +1,5 @@ package me.jellysquid.mods.lithium.mixin.world.chunk_access; -import com.mojang.datafixers.util.Either; import me.jellysquid.mods.lithium.common.world.chunk.ChunkHolderExtended; import net.minecraft.server.world.*; import net.minecraft.util.Util; @@ -16,7 +15,6 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.Arrays; -import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.function.BooleanSupplier; @@ -157,26 +155,25 @@ private Chunk getChunkBlocking(int x, int z, ChunkStatus status, boolean create) // The holder is absent and we weren't asked to create anything, so return null return null; } - } else if (create && ((ChunkHolderExtended) holder).updateLastAccessTime(this.time)) { + } else if (create && ((ChunkHolderExtended) holder).lithium$updateLastAccessTime(this.time)) { // Only create a new chunk ticket if one hasn't already been submitted this tick // This maintains vanilla behavior (preventing chunks from being immediately unloaded) while also // eliminating the cost of submitting a ticket for most chunk fetches this.createChunkLoadTicket(x, z, level); } - CompletableFuture> loadFuture = null; - CompletableFuture> statusFuture = ((ChunkHolderExtended) holder).getFutureByStatus(status.getIndex()); + CompletableFuture> loadFuture = null; + CompletableFuture> statusFuture = ((ChunkHolderExtended) holder).lithium$getFutureByStatus(status.getIndex()); if (statusFuture != null) { - Either immediate = statusFuture.getNow(null); + OptionalChunk optionalChunk = statusFuture.getNow(null); // If the result is already available, return it - if (immediate != null) { - Optional chunk = immediate.left(); + if (optionalChunk != null) { - if (chunk.isPresent()) { + if (optionalChunk.isPresent()) { // Early-return with the already ready chunk - return chunk.get(); + return optionalChunk.orElse(null); } } else { // The load future will first start with the existing future for this status @@ -188,11 +185,11 @@ private Chunk getChunkBlocking(int x, int z, ChunkStatus status, boolean create) if (loadFuture == null) { if (ChunkLevels.getStatus(holder.getLevel()).isAtLeast(status)) { // Create a new future which upgrades the chunk from the previous status level to the desired one - CompletableFuture> mergedFuture = this.threadedAnvilChunkStorage.getChunk(holder, status); + CompletableFuture> mergedFuture = this.threadedAnvilChunkStorage.getChunk(holder, status); // Add this future to the chunk holder so subsequent calls will see it holder.combineSavingFuture(mergedFuture, "schedule chunk status"); - ((ChunkHolderExtended) holder).setFutureForStatus(status.getIndex(), mergedFuture); + ((ChunkHolderExtended) holder).lithium$setFutureForStatus(status.getIndex(), mergedFuture); loadFuture = mergedFuture; } else { @@ -214,7 +211,7 @@ private Chunk getChunkBlocking(int x, int z, ChunkStatus status, boolean create) } // Wait for the result of the future and unwrap it, returning null if the chunk is absent - return loadFuture.join().left().orElse(null); + return loadFuture.join().orElse(null); } private void createChunkLoadTicket(int x, int z, int level) { diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/explosions/ExplosionMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/explosions/ExplosionMixin.java index d3c6770ac..5e71d01a1 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/explosions/ExplosionMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/explosions/ExplosionMixin.java @@ -11,7 +11,7 @@ import net.minecraft.fluid.FluidState; import net.minecraft.fluid.Fluids; import net.minecraft.particle.ParticleEffect; -import net.minecraft.sound.SoundEvent; +import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.random.Random; @@ -85,10 +85,10 @@ public abstract class ExplosionMixin { private int minY, maxY; @Inject( - method = "(Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/entity/damage/DamageSource;Lnet/minecraft/world/explosion/ExplosionBehavior;DDDFZLnet/minecraft/world/explosion/Explosion$DestructionType;Lnet/minecraft/particle/ParticleEffect;Lnet/minecraft/particle/ParticleEffect;Lnet/minecraft/sound/SoundEvent;)V", + method = "(Lnet/minecraft/world/World;Lnet/minecraft/entity/Entity;Lnet/minecraft/entity/damage/DamageSource;Lnet/minecraft/world/explosion/ExplosionBehavior;DDDFZLnet/minecraft/world/explosion/Explosion$DestructionType;Lnet/minecraft/particle/ParticleEffect;Lnet/minecraft/particle/ParticleEffect;Lnet/minecraft/registry/entry/RegistryEntry;)V", at = @At("TAIL") ) - private void init(World world, Entity entity, DamageSource damageSource, ExplosionBehavior behavior, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType destructionType, ParticleEffect particle, ParticleEffect emitterParticle, SoundEvent soundEvent, CallbackInfo ci) { + private void init(World world, Entity entity, DamageSource damageSource, ExplosionBehavior behavior, double x, double y, double z, float power, boolean createFire, Explosion.DestructionType destructionType, ParticleEffect particle, ParticleEffect emitterParticle, RegistryEntry soundEvent, CallbackInfo ci) { this.minY = this.world.getBottomY(); this.maxY = this.world.getTopY(); diff --git a/src/main/java/me/jellysquid/mods/lithium/mixin/world/inline_height/WorldMixin.java b/src/main/java/me/jellysquid/mods/lithium/mixin/world/inline_height/WorldMixin.java index 4be2462ec..0d5d7b2a2 100644 --- a/src/main/java/me/jellysquid/mods/lithium/mixin/world/inline_height/WorldMixin.java +++ b/src/main/java/me/jellysquid/mods/lithium/mixin/world/inline_height/WorldMixin.java @@ -9,7 +9,6 @@ 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; @@ -21,9 +20,6 @@ */ @Mixin(World.class) public abstract class WorldMixin implements HeightLimitView { - @Shadow - public abstract DimensionType getDimension(); - private int bottomY; private int height; private int topYInclusive; @@ -32,9 +28,9 @@ public abstract class WorldMixin implements HeightLimitView { method = "", at = @At("RETURN") ) - private void initHeightCache(MutableWorldProperties properties, RegistryKey registryRef, DynamicRegistryManager registryManager, RegistryEntry dimensionEntry, Supplier profiler, boolean isClient, boolean debugWorld, long biomeAccess, int maxChainedNeighborUpdates, CallbackInfo ci) { - this.height = this.getDimension().height(); - this.bottomY = this.getDimension().minY(); + private void initHeightCache(MutableWorldProperties properties, RegistryKey registryRef, DynamicRegistryManager registryManager, RegistryEntry dimensionEntry, Supplier profiler, boolean isClient, boolean debugWorld, long biomeAccess, int maxChainedNeighborUpdates, CallbackInfo ci) { + this.height = dimensionEntry.value().height(); + this.bottomY = dimensionEntry.value().minY(); this.topYInclusive = this.bottomY + this.height - 1; } diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/neoforge.mods.toml similarity index 93% rename from src/main/resources/META-INF/mods.toml rename to src/main/resources/META-INF/neoforge.mods.toml index e2fd6d1c9..a0f2bb224 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/neoforge.mods.toml @@ -14,6 +14,6 @@ updateJSONURL = "https://api.modrinth.com/updates/radium/forge_updates.json" logoFile = "icon.png" description = "A Forge port of mod designed to improve the general performance of Minecraft without breaking things" credits = "JellySquid, 2No2Name" -authors = "dima_dencep, NanoLive" +authors = "embeddedt, dima_dencep, NanoLive" displayURL = "https://curseforge.com/minecraft/mc-mods/radium-reforged" provides=["lithium"] diff --git a/src/main/resources/lithium.mixins.json b/src/main/resources/lithium.mixins.json index 3aa099a19..f65f7fe2d 100644 --- a/src/main/resources/lithium.mixins.json +++ b/src/main/resources/lithium.mixins.json @@ -11,17 +11,13 @@ "conformVisibility": true }, "mixins": [ - "ai.nearby_entity_tracking.EntityMixin", - "ai.nearby_entity_tracking.EntityTrackingSectionMixin", - "ai.nearby_entity_tracking.ServerEntityManagerListenerMixin", - "ai.nearby_entity_tracking.ServerEntityManagerMixin", - "ai.nearby_entity_tracking.goals.FleeEntityGoalMixin", - "ai.nearby_entity_tracking.goals.LookAtEntityGoalMixin", "ai.pathing.AbstractBlockStateMixin", "ai.pathing.BirdPathNodeMakerMixin", "ai.pathing.ChunkCacheMixin", "ai.pathing.LandPathNodeMakerMixin", "ai.pathing.MixinBlock", + "ai.pathing.PathContextAccessor", + "ai.pathing.PathContextMixin", "ai.poi.PointOfInterestSetMixin", "ai.poi.PointOfInterestStorageMixin", "ai.poi.PointOfInterestTypesMixin", @@ -33,6 +29,7 @@ "ai.raid.PickupBannerAsLeaderGoalMixin", "ai.raid.RaiderEntityMixin", "ai.raid.RaidMixin", + "ai.raid.WorldMixin", "ai.sensor.secondary_poi.SecondaryPointsOfInterestSensorMixin", "ai.task.launch.BrainMixin", "ai.task.memory_change_counting.BrainMixin", @@ -115,13 +112,10 @@ "entity.collisions.unpushable_cramming.EntityPredicatesMixin", "entity.collisions.unpushable_cramming.EntityTrackingSectionMixin", "entity.collisions.unpushable_cramming.LivingEntityMixin", - "entity.data_tracker.no_locks.DataTrackerMixin", - "entity.data_tracker.use_arrays.DataTrackerMixin", "entity.fast_elytra_check.LivingEntityMixin", "entity.fast_hand_swing.LivingEntityMixin", "entity.fast_powder_snow_check.LivingEntityMixin", "entity.fast_retrieval.SectionedEntityCacheMixin", - "entity.hopper_minecart.HopperBlockEntityMixin", "entity.inactive_navigations.DrownedEntityLeaveWaterGoalMixin", "entity.inactive_navigations.DrownedEntityMixin", "entity.inactive_navigations.EntityNavigationMixin", @@ -142,16 +136,15 @@ "experimental.entity.block_caching.block_support.EntityMixin", "experimental.entity.block_caching.block_touching.EntityMixin", "experimental.entity.block_caching.fire_lava_touching.EntityMixin", - "experimental.entity.block_caching.fluid_pushing.EntityMixin", "experimental.entity.block_caching.suffocation.EntityMixin", "experimental.entity.item_entity_merging.ItemEntityMixin", - "experimental.util.item_entity_by_type.ItemEntityMixin", - "experimental.util.item_entity_by_type.TypeFilterableListMixin", "experimental.spawning.EntityTrackingSectionAccessor", "experimental.spawning.SectionedEntityCacheMixin", "experimental.spawning.ServerChunkManagerMixin", "experimental.spawning.ServerEntityManagerAccessor", "experimental.spawning.ServerWorldAccessor", + "experimental.util.item_entity_by_type.ItemEntityMixin", + "experimental.util.item_entity_by_type.TypeFilterableListMixin", "gen.cached_generator_settings.NoiseChunkGeneratorMixin", "gen.chunk_region.ChunkRegionMixin", "math.fast_blockpos.BlockPosMixin",