Compare commits

..

No commits in common. "a8d1a99e286bc7fae355d6b44c4fd64b07afb7a1" and "c8adbc271abbab8bf8e59ca714484d96c6744e2c" have entirely different histories.

64 changed files with 792 additions and 763 deletions

View file

@ -3,16 +3,7 @@ plugins {
id 'eclipse' id 'eclipse'
id 'idea' id 'idea'
id 'maven-publish' id 'maven-publish'
id 'net.neoforged.gradle.userdev' version '7.0.163' id 'net.neoforged.gradle.userdev' version '7.0.80'
}
tasks.named('wrapper', Wrapper).configure {
// Define wrapper values here so as to not have to always do so when updating gradlew.properties.
// Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
// documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
// file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
// (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
distributionType = Wrapper.DistributionType.BIN
} }
// Enable the Jar-in-Jar system for your mod // Enable the Jar-in-Jar system for your mod
@ -36,8 +27,8 @@ base {
archivesName = mod_name archivesName = mod_name
} }
// Mojang ships Java 21 to end users starting in 1.20.5, so mods should target Java 21. // Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(21) java.toolchain.languageVersion = JavaLanguageVersion.of(17)
println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}" println "Java: ${System.getProperty 'java.version'}, JVM: ${System.getProperty 'java.vm.version'} (${System.getProperty 'java.vendor'}), Arch: ${System.getProperty 'os.arch'}"
runs { runs {
@ -71,7 +62,7 @@ runs {
server { server {
systemProperty 'forge.enabledGameTestNamespaces', project.mod_id systemProperty 'forge.enabledGameTestNamespaces', project.mod_id
argument '--nogui' programArgument '--nogui'
} }
// This run config launches GameTestServer and runs all registered gametests, then exits. // This run config launches GameTestServer and runs all registered gametests, then exits.
@ -86,7 +77,7 @@ runs {
// workingDirectory project.file('run-data') // workingDirectory project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
arguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath() programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
} }
} }
@ -136,8 +127,8 @@ tasks.withType(ProcessResources).configureEach {
] ]
inputs.properties replaceProperties inputs.properties replaceProperties
filesMatching(['META-INF/neoforge.mods.toml']) { filesMatching(['META-INF/mods.toml']) {
expand replaceProperties expand replaceProperties + [project: project]
} }
} }
@ -163,11 +154,3 @@ publishing {
tasks.withType(JavaCompile).configureEach { tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
} }
// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}

View file

@ -1,24 +1,22 @@
org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=false
org.gradle.debug=false org.gradle.debug=false
#read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings #read more on this at https://github.com/neoforged/NeoGradle/blob/NG_7.0/README.md#apply-parchment-mappings
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started # you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
neogradle.subsystems.parchment.minecraftVersion=1.21 neogradle.subsystems.parchment.minecraftVersion=1.20.3
neogradle.subsystems.parchment.mappingsVersion=2024.07.28 neogradle.subsystems.parchment.mappingsVersion=2023.12.31
# Environment Properties # Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge # You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact # The Minecraft version must agree with the Neo version to get a valid artifact
minecraft_version=1.21.1 minecraft_version=1.20.4
minecraft_version_range=[1.21.1,1.22) minecraft_version_range=[1.20.4,1.21)
# The Neo version must agree with the Minecraft version to get a valid artifact # The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=21.1.45 neo_version=20.4.195
# The Neo version range can use any version of Neo as bounds # The Neo version range can use any version of Neo as bounds
neo_version_range=[21.1.0,) neo_version_range=[20.4,)
# The loader version range can only use the major version of FML as bounds # The loader version range can only use the major version of FML as bounds
loader_version_range=[4,) loader_version_range=[2,)
jei_version=19.18.3.204 jei_version=17.3.0.49
jgt_version=1.5.2 jgt_version=1.5.2
jheaps_version=0.14 jheaps_version=0.14
apfloat_version=1.10.1 apfloat_version=1.10.1

Binary file not shown.

View file

@ -1,7 +1,6 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists

54
gradlew vendored
View file

@ -1,7 +1,7 @@
#!/bin/sh #!/bin/sh
# #
# Copyright © 2015-2021 the original authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@ -15,8 +15,6 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@ -34,10 +32,10 @@
# Busybox and similar reduced shells will NOT work, because this script # Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features: # requires all of these POSIX shell features:
# * functions; # * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»; # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»; # * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit». # * various built-in commands including «command», «set», and «ulimit».
# #
# Important for patching: # Important for patching:
# #
@ -57,7 +55,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@ -82,12 +80,13 @@ do
esac esac
done done
# This is normally unused APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
' "$PWD" ) || exit DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@ -134,29 +133,22 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
if ! command -v java >/dev/null 2>&1 which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
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 Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) 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 ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | 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" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@ -201,15 +193,11 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# Collect all arguments for the java command: # * put everything else in single quotes, so that it's not re-expanded.
# * 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 -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
@ -217,12 +205,6 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ 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. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.

33
gradlew.bat vendored
View file

@ -13,8 +13,6 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@ -28,7 +26,6 @@ if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%" == "" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@ -43,13 +40,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if "%ERRORLEVEL%" == "0" goto execute
echo. 1>&2 echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo. 1>&2 echo.
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. 1>&2 echo location of your Java installation.
goto fail goto fail
@ -59,11 +56,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto execute
echo. 1>&2 echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo. 1>&2 echo.
echo Please set the JAVA_HOME variable in your environment to match the 1>&2 echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation. 1>&2 echo location of your Java installation.
goto fail goto fail
@ -78,15 +75,13 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd if "%ERRORLEVEL%"=="0" goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL% if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
if %EXIT_CODE% equ 0 set EXIT_CODE=1 exit /b 1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal

View file

@ -3,9 +3,7 @@ package de.ellpeck.prettypipes;
import de.ellpeck.prettypipes.entities.PipeFrameEntity; import de.ellpeck.prettypipes.entities.PipeFrameEntity;
import de.ellpeck.prettypipes.entities.PipeFrameRenderer; import de.ellpeck.prettypipes.entities.PipeFrameRenderer;
import de.ellpeck.prettypipes.items.*; import de.ellpeck.prettypipes.items.*;
import de.ellpeck.prettypipes.misc.DirectionSelector;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.misc.ModuleClearingRecipe; import de.ellpeck.prettypipes.misc.ModuleClearingRecipe;
import de.ellpeck.prettypipes.packets.*; import de.ellpeck.prettypipes.packets.*;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
@ -49,6 +47,7 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui; import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalGui;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.entity.EntityRenderers; import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
@ -69,26 +68,24 @@ import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour.Properties; import net.minecraft.world.level.block.state.BlockBehaviour.Properties;
import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.fml.common.Mod.EventBusSubscriber;
import net.neoforged.fml.common.Mod.EventBusSubscriber.Bus;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent; import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.neoforged.neoforge.capabilities.BlockCapability; import net.neoforged.neoforge.capabilities.BlockCapability;
import net.neoforged.neoforge.capabilities.Capabilities; import net.neoforged.neoforge.capabilities.Capabilities;
import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent; import net.neoforged.neoforge.capabilities.RegisterCapabilitiesEvent;
import net.neoforged.neoforge.client.event.RegisterMenuScreensEvent;
import net.neoforged.neoforge.common.extensions.IMenuTypeExtension; import net.neoforged.neoforge.common.extensions.IMenuTypeExtension;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent; import net.neoforged.neoforge.network.event.RegisterPayloadHandlerEvent;
import net.neoforged.neoforge.registries.RegisterEvent; import net.neoforged.neoforge.registries.RegisterEvent;
import java.util.Comparator; import java.util.Comparator;
import java.util.Locale; import java.util.Locale;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import static net.neoforged.fml.common.EventBusSubscriber.Bus;
@EventBusSubscriber(bus = Bus.MOD) @EventBusSubscriber(bus = Bus.MOD)
public final class Registry { public final class Registry {
public static BlockCapability<IPipeConnectable, Direction> pipeConnectableCapability = BlockCapability.createSided(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class); public static BlockCapability<IPipeConnectable, Direction> pipeConnectableCapability = BlockCapability.createSided(new ResourceLocation(PrettyPipes.ID, "pipe_connectable"), IPipeConnectable.class);
public static Item wrenchItem; public static Item wrenchItem;
public static Item pipeFrameItem; public static Item pipeFrameItem;
@ -122,19 +119,19 @@ public final class Registry {
@SubscribeEvent @SubscribeEvent
public static void register(RegisterEvent event) { public static void register(RegisterEvent event) {
event.register(Registries.BLOCK, h -> { event.register(Registries.BLOCK, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeBlock = new PipeBlock(Properties.of().strength(2).sound(SoundType.STONE).noOcclusion())); h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeBlock = new PipeBlock(Properties.of().strength(2).sound(SoundType.STONE).noOcclusion()));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlock = new ItemTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE))); h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlock = new ItemTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlock = new CraftingTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE))); h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlock = new CraftingTerminalBlock(Properties.of().strength(3).sound(SoundType.STONE)));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlock = new PressurizerBlock(Properties.of().strength(3).sound(SoundType.STONE))); h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlock = new PressurizerBlock(Properties.of().strength(3).sound(SoundType.STONE)));
}); });
event.register(Registries.ITEM, h -> { event.register(Registries.ITEM, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "wrench"), Registry.wrenchItem = new WrenchItem()); h.register(new ResourceLocation(PrettyPipes.ID, "wrench"), Registry.wrenchItem = new WrenchItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "blank_module"), new Item(new Item.Properties())); h.register(new ResourceLocation(PrettyPipes.ID, "blank_module"), new Item(new Item.Properties()));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameItem = new PipeFrameItem()); h.register(new ResourceLocation(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameItem = new PipeFrameItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "stack_size_module"), new StackSizeModuleItem()); h.register(new ResourceLocation(PrettyPipes.ID, "stack_size_module"), new StackSizeModuleItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "redstone_module"), new RedstoneModuleItem()); h.register(new ResourceLocation(PrettyPipes.ID, "redstone_module"), new RedstoneModuleItem());
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "filter_increase_modifier"), new FilterIncreaseModuleItem()); h.register(new ResourceLocation(PrettyPipes.ID, "filter_increase_modifier"), new FilterIncreaseModuleItem());
Registry.registerTieredModule(h, "extraction_module", ExtractionModuleItem::new); Registry.registerTieredModule(h, "extraction_module", ExtractionModuleItem::new);
Registry.registerTieredModule(h, "filter_module", FilterModuleItem::new); Registry.registerTieredModule(h, "filter_module", FilterModuleItem::new);
@ -146,11 +143,11 @@ public final class Registry {
for (var type : ItemEquality.Type.values()) { for (var type : ItemEquality.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_filter_modifier"; var name = type.name().toLowerCase(Locale.ROOT) + "_filter_modifier";
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type)); h.register(new ResourceLocation(PrettyPipes.ID, name), new FilterModifierModuleItem(name, type));
} }
for (var type : SortingModuleItem.Type.values()) { for (var type : SortingModuleItem.Type.values()) {
var name = type.name().toLowerCase(Locale.ROOT) + "_sorting_modifier"; var name = type.name().toLowerCase(Locale.ROOT) + "_sorting_modifier";
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), new SortingModuleItem(name, type)); h.register(new ResourceLocation(PrettyPipes.ID, name), new SortingModuleItem(name, type));
} }
BuiltInRegistries.BLOCK.entrySet().stream() BuiltInRegistries.BLOCK.entrySet().stream()
@ -159,20 +156,20 @@ public final class Registry {
}); });
event.register(Registries.BLOCK_ENTITY_TYPE, h -> { event.register(Registries.BLOCK_ENTITY_TYPE, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeBlockEntity = BlockEntityType.Builder.of(PipeBlockEntity::new, Registry.pipeBlock).build(null)); h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeBlockEntity = BlockEntityType.Builder.of(PipeBlockEntity::new, Registry.pipeBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlockEntity = BlockEntityType.Builder.of(ItemTerminalBlockEntity::new, Registry.itemTerminalBlock).build(null)); h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalBlockEntity = BlockEntityType.Builder.of(ItemTerminalBlockEntity::new, Registry.itemTerminalBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlockEntity = BlockEntityType.Builder.of(CraftingTerminalBlockEntity::new, Registry.craftingTerminalBlock).build(null)); h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalBlockEntity = BlockEntityType.Builder.of(CraftingTerminalBlockEntity::new, Registry.craftingTerminalBlock).build(null));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlockEntity = BlockEntityType.Builder.of(PressurizerBlockEntity::new, Registry.pressurizerBlock).build(null)); h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerBlockEntity = BlockEntityType.Builder.of(PressurizerBlockEntity::new, Registry.pressurizerBlock).build(null));
}); });
event.register(Registries.ENTITY_TYPE, h -> event.register(Registries.ENTITY_TYPE, h ->
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame"))); h.register(new ResourceLocation(PrettyPipes.ID, "pipe_frame"), Registry.pipeFrameEntity = EntityType.Builder.<PipeFrameEntity>of(PipeFrameEntity::new, MobCategory.MISC).build("pipe_frame")));
event.register(Registries.MENU, h -> { event.register(Registries.MENU, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe"), Registry.pipeContainer = IMenuTypeExtension.create((windowId, inv, data) -> new MainPipeContainer(Registry.pipeContainer, windowId, inv.player, data.readBlockPos()))); h.register(new ResourceLocation(PrettyPipes.ID, "pipe"), Registry.pipeContainer = IMenuTypeExtension.create((windowId, inv, data) -> new MainPipeContainer(Registry.pipeContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new ItemTerminalContainer(Registry.itemTerminalContainer, windowId, inv.player, data.readBlockPos()))); h.register(new ResourceLocation(PrettyPipes.ID, "item_terminal"), Registry.itemTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new ItemTerminalContainer(Registry.itemTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new CraftingTerminalContainer(Registry.craftingTerminalContainer, windowId, inv.player, data.readBlockPos()))); h.register(new ResourceLocation(PrettyPipes.ID, "crafting_terminal"), Registry.craftingTerminalContainer = IMenuTypeExtension.create((windowId, inv, data) -> new CraftingTerminalContainer(Registry.craftingTerminalContainer, windowId, inv.player, data.readBlockPos())));
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pressurizer"), Registry.pressurizerContainer = IMenuTypeExtension.create((windowId, inv, data) -> new PressurizerContainer(Registry.pressurizerContainer, windowId, inv.player, data.readBlockPos()))); h.register(new ResourceLocation(PrettyPipes.ID, "pressurizer"), Registry.pressurizerContainer = IMenuTypeExtension.create((windowId, inv, data) -> new PressurizerContainer(Registry.pressurizerContainer, windowId, inv.player, data.readBlockPos())));
Registry.extractionModuleContainer = Registry.registerPipeContainer(h, "extraction_module"); Registry.extractionModuleContainer = Registry.registerPipeContainer(h, "extraction_module");
Registry.filterModuleContainer = Registry.registerPipeContainer(h, "filter_module"); Registry.filterModuleContainer = Registry.registerPipeContainer(h, "filter_module");
@ -184,7 +181,7 @@ public final class Registry {
}); });
event.register(BuiltInRegistries.CREATIVE_MODE_TAB.key(), h -> { event.register(BuiltInRegistries.CREATIVE_MODE_TAB.key(), h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "tab"), CreativeModeTab.builder() h.register(new ResourceLocation(PrettyPipes.ID, "tab"), CreativeModeTab.builder()
.title(Component.translatable("item_group." + PrettyPipes.ID + ".tab")) .title(Component.translatable("item_group." + PrettyPipes.ID + ".tab"))
.icon(() -> new ItemStack(Registry.wrenchItem)) .icon(() -> new ItemStack(Registry.wrenchItem))
.displayItems((params, output) -> BuiltInRegistries.ITEM.entrySet().stream() .displayItems((params, output) -> BuiltInRegistries.ITEM.entrySet().stream()
@ -195,16 +192,7 @@ public final class Registry {
}); });
event.register(Registries.RECIPE_SERIALIZER, h -> { event.register(Registries.RECIPE_SERIALIZER, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "module_clearing"), ModuleClearingRecipe.SERIALIZER); h.register(new ResourceLocation(PrettyPipes.ID, "module_clearing"), ModuleClearingRecipe.SERIALIZER);
});
event.register(Registries.DATA_COMPONENT_TYPE, h -> {
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_module_contents"), CraftingModuleItem.Contents.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_filter_data"), ItemFilter.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "stack_size_module_data"), StackSizeModuleItem.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "direction_selector_data"), DirectionSelector.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "filter_modifier_data"), FilterModifierModuleItem.Data.TYPE);
h.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "sorting_module_data"), SortingModuleItem.Data.TYPE);
}); });
} }
@ -219,14 +207,14 @@ public final class Registry {
} }
@SubscribeEvent @SubscribeEvent
public static void registerPayloads(final RegisterPayloadHandlersEvent event) { public static void registerPayloads(final RegisterPayloadHandlerEvent event) {
var registrar = event.registrar(PrettyPipes.ID); var registrar = event.registrar(PrettyPipes.ID);
registrar.playBidirectional(PacketItemEnterPipe.TYPE, PacketItemEnterPipe.CODEC, PacketItemEnterPipe::onMessage); registrar.play(PacketItemEnterPipe.ID, PacketItemEnterPipe::new, PacketItemEnterPipe::onMessage);
registrar.playBidirectional(PacketButton.TYPE, PacketButton.CODEC, PacketButton::onMessage); registrar.play(PacketButton.ID, PacketButton::new, PacketButton::onMessage);
registrar.playBidirectional(PacketCraftingModuleTransfer.TYPE, PacketCraftingModuleTransfer.CODEC, PacketCraftingModuleTransfer::onMessage); registrar.play(PacketCraftingModuleTransfer.ID, PacketCraftingModuleTransfer::new, PacketCraftingModuleTransfer::onMessage);
registrar.playBidirectional(PacketGhostSlot.TYPE, PacketGhostSlot.CODEC, PacketGhostSlot::onMessage); registrar.play(PacketGhostSlot.ID, PacketGhostSlot::new, PacketGhostSlot::onMessage);
registrar.playBidirectional(PacketNetworkItems.TYPE, PacketNetworkItems.CODEC, PacketNetworkItems::onMessage); registrar.play(PacketNetworkItems.ID, PacketNetworkItems::new, PacketNetworkItems::onMessage);
registrar.playBidirectional(PacketRequest.TYPE, PacketRequest.CODEC, PacketRequest::onMessage); registrar.play(PacketRequest.ID, PacketRequest::new, PacketRequest::onMessage);
} }
private static <T extends AbstractPipeContainer<?>> MenuType<T> registerPipeContainer(RegisterEvent.RegisterHelper<MenuType<?>> helper, String name) { private static <T extends AbstractPipeContainer<?>> MenuType<T> registerPipeContainer(RegisterEvent.RegisterHelper<MenuType<?>> helper, String name) {
@ -236,13 +224,13 @@ public final class Registry {
var moduleStack = tile.modules.getStackInSlot(moduleIndex); var moduleStack = tile.modules.getStackInSlot(moduleIndex);
return ((IModule) moduleStack.getItem()).getContainer(moduleStack, tile, windowId, inv, inv.player, moduleIndex); return ((IModule) moduleStack.getItem()).getContainer(moduleStack, tile, windowId, inv, inv.player, moduleIndex);
}); });
helper.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, name), type); helper.register(new ResourceLocation(PrettyPipes.ID, name), type);
return type; return type;
} }
private static void registerTieredModule(RegisterEvent.RegisterHelper<Item> helper, String name, BiFunction<String, ModuleTier, ModuleItem> item) { private static void registerTieredModule(RegisterEvent.RegisterHelper<Item> helper, String name, BiFunction<String, ModuleTier, ModuleItem> item) {
for (var tier : ModuleTier.values()) for (var tier : ModuleTier.values())
helper.register(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier)); helper.register(new ResourceLocation(PrettyPipes.ID, tier.name().toLowerCase(Locale.ROOT) + "_" + name), item.apply(name, tier));
} }
@EventBusSubscriber(bus = Bus.MOD, value = Dist.CLIENT) @EventBusSubscriber(bus = Bus.MOD, value = Dist.CLIENT)
@ -252,21 +240,18 @@ public final class Registry {
public static void setup(FMLClientSetupEvent event) { public static void setup(FMLClientSetupEvent event) {
BlockEntityRenderers.register(Registry.pipeBlockEntity, PipeRenderer::new); BlockEntityRenderers.register(Registry.pipeBlockEntity, PipeRenderer::new);
EntityRenderers.register(Registry.pipeFrameEntity, PipeFrameRenderer::new); EntityRenderers.register(Registry.pipeFrameEntity, PipeFrameRenderer::new);
}
@SubscribeEvent MenuScreens.register(Registry.pipeContainer, MainPipeGui::new);
public static void registerMenuScreens(RegisterMenuScreensEvent event) { MenuScreens.register(Registry.itemTerminalContainer, ItemTerminalGui::new);
event.register(Registry.pipeContainer, MainPipeGui::new); MenuScreens.register(Registry.pressurizerContainer, PressurizerGui::new);
event.register(Registry.itemTerminalContainer, ItemTerminalGui::new); MenuScreens.register(Registry.craftingTerminalContainer, CraftingTerminalGui::new);
event.register(Registry.pressurizerContainer, PressurizerGui::new); MenuScreens.register(Registry.extractionModuleContainer, ExtractionModuleGui::new);
event.register(Registry.craftingTerminalContainer, CraftingTerminalGui::new); MenuScreens.register(Registry.filterModuleContainer, FilterModuleGui::new);
event.register(Registry.extractionModuleContainer, ExtractionModuleGui::new); MenuScreens.register(Registry.retrievalModuleContainer, RetrievalModuleGui::new);
event.register(Registry.filterModuleContainer, FilterModuleGui::new); MenuScreens.register(Registry.stackSizeModuleContainer, StackSizeModuleGui::new);
event.register(Registry.retrievalModuleContainer, RetrievalModuleGui::new); MenuScreens.register(Registry.filterIncreaseModuleContainer, FilterIncreaseModuleGui::new);
event.register(Registry.stackSizeModuleContainer, StackSizeModuleGui::new); MenuScreens.register(Registry.craftingModuleContainer, CraftingModuleGui::new);
event.register(Registry.filterIncreaseModuleContainer, FilterIncreaseModuleGui::new); MenuScreens.register(Registry.filterModifierModuleContainer, FilterModifierModuleGui::new);
event.register(Registry.craftingModuleContainer, CraftingModuleGui::new);
event.register(Registry.filterModifierModuleContainer, FilterModifierModuleGui::new);
} }
} }

View file

@ -1,17 +1,12 @@
package de.ellpeck.prettypipes; package de.ellpeck.prettypipes;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.resources.language.I18n; import net.minecraft.client.resources.language.I18n;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntArrayTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style; import net.minecraft.network.chat.Style;
import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket;
@ -27,7 +22,6 @@ import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntity;
import net.neoforged.neoforge.common.util.INBTSerializable; import net.neoforged.neoforge.common.util.INBTSerializable;
import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandler;
import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.items.wrapper.SidedInvWrapper; import net.neoforged.neoforge.items.wrapper.SidedInvWrapper;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
@ -35,21 +29,9 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.IntStream;
@SuppressWarnings("ALL")
public final class Utility { public final class Utility {
public static final Codec<ItemStackHandler> ITEM_STACK_HANDLER_CODEC = RecordCodecBuilder.create(builder -> builder.group(
Codec.INT.fieldOf("size").forGetter(h -> h.getSlots()),
Codec.list(ItemStack.CODEC).fieldOf("items").forGetter(h -> IntStream.range(0, h.getSlots()).mapToObj(h::getStackInSlot).toList())
).apply(builder, (size, items) -> {
var ret = new ItemStackHandler(size);
for (var i = 0; i < items.size(); i++)
ret.setStackInSlot(i, items.get(i));
return ret;
}));
public static <T extends BlockEntity> T getBlockEntity(Class<T> type, BlockGetter world, BlockPos pos) { public static <T extends BlockEntity> T getBlockEntity(Class<T> type, BlockGetter world, BlockPos pos) {
var tile = world.getBlockEntity(pos); var tile = world.getBlockEntity(pos);
return type.isInstance(tile) ? (T) tile : null; return type.isInstance(tile) ? (T) tile : null;
@ -122,10 +104,10 @@ public final class Utility {
return ItemStack.EMPTY; return ItemStack.EMPTY;
} }
public static ListTag serializeAll(HolderLookup.Provider provider, Collection<? extends INBTSerializable<CompoundTag>> items) { public static ListTag serializeAll(Collection<? extends INBTSerializable<CompoundTag>> items) {
var list = new ListTag(); var list = new ListTag();
for (INBTSerializable<CompoundTag> item : items) for (INBTSerializable<CompoundTag> item : items)
list.add(item.serializeNBT(provider)); list.add(item.serializeNBT());
return list; return list;
} }
@ -158,19 +140,8 @@ public final class Utility {
return new SidedInvWrapper(inventory, direction); return new SidedInvWrapper(inventory, direction);
} }
public static BlockPos readBlockPos(Tag tag) {
if (tag instanceof IntArrayTag i) {
int[] arr = i.getAsIntArray();
if (arr.length == 3)
return new BlockPos(arr[0], arr[1], arr[2]);
}
return null;
}
public interface IMergeItemStack { public interface IMergeItemStack {
boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection); boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection);
} }
} }

View file

@ -4,21 +4,25 @@ import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.packets.PacketCraftingModuleTransfer; import de.ellpeck.prettypipes.packets.PacketCraftingModuleTransfer;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer; import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import mezz.jei.api.constants.RecipeTypes;
import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.constants.VanillaTypes;
import mezz.jei.api.gui.ingredient.IRecipeSlotsView; import mezz.jei.api.gui.ingredient.IRecipeSlotsView;
import mezz.jei.api.recipe.RecipeIngredientRole; import mezz.jei.api.recipe.RecipeIngredientRole;
import mezz.jei.api.recipe.RecipeType;
import mezz.jei.api.recipe.transfer.IRecipeTransferError; import mezz.jei.api.recipe.transfer.IRecipeTransferError;
import mezz.jei.api.recipe.transfer.IUniversalRecipeTransferHandler; import mezz.jei.api.recipe.transfer.IRecipeTransferHandler;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType; import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.CraftingRecipe;
import net.minecraft.world.item.crafting.RecipeHolder;
import net.neoforged.neoforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Optional; import java.util.Optional;
public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHandler<CraftingModuleContainer> { public class CraftingModuleTransferHandler implements IRecipeTransferHandler<CraftingModuleContainer, RecipeHolder<CraftingRecipe>> {
@Override @Override
public Class<CraftingModuleContainer> getContainerClass() { public Class<CraftingModuleContainer> getContainerClass() {
@ -31,16 +35,21 @@ public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHa
} }
@Override @Override
public @Nullable IRecipeTransferError transferRecipe(CraftingModuleContainer container, Object recipe, IRecipeSlotsView recipeSlots, Player player, boolean maxTransfer, boolean doTransfer) { public RecipeType<RecipeHolder<CraftingRecipe>> getRecipeType() {
return RecipeTypes.CRAFTING;
}
@Override
public @Nullable IRecipeTransferError transferRecipe(CraftingModuleContainer container, RecipeHolder<CraftingRecipe> recipe, IRecipeSlotsView slots, Player player, boolean maxTransfer, boolean doTransfer) {
if (!doTransfer) if (!doTransfer)
return null; return null;
var inputs = new ArrayList<ItemStack>(); var inputs = new ArrayList<ItemStack>();
var outputs = new ArrayList<ItemStack>(); var outputs = new ArrayList<ItemStack>();
for (var entry : recipeSlots.getSlotViews()) { for (var entry : slots.getSlotViews()) {
var allIngredients = entry.getIngredients(VanillaTypes.ITEM_STACK).toList(); var allIngredients = entry.getIngredients(VanillaTypes.ITEM_STACK).toList();
if (allIngredients.isEmpty()) if (allIngredients.isEmpty())
continue; continue;
var remain = allIngredients.getFirst().copy(); var remain = allIngredients.get(0).copy();
var toAdd = entry.getRole() == RecipeIngredientRole.INPUT ? inputs : outputs; var toAdd = entry.getRole() == RecipeIngredientRole.INPUT ? inputs : outputs;
for (var stack : toAdd) { for (var stack : toAdd) {
if (ItemEquality.compareItems(stack, remain)) { if (ItemEquality.compareItems(stack, remain)) {
@ -54,7 +63,7 @@ public class CraftingModuleTransferHandler implements IUniversalRecipeTransferHa
if (!remain.isEmpty()) if (!remain.isEmpty())
toAdd.add(remain); toAdd.add(remain);
} }
PacketDistributor.sendToServer(new PacketCraftingModuleTransfer(inputs, outputs)); PacketDistributor.SERVER.noArg().send(new PacketCraftingModuleTransfer(inputs, outputs));
return null; return null;
} }

View file

@ -46,8 +46,8 @@ public class CraftingTerminalTransferHandler implements IRecipeTransferHandler<C
List<PacketGhostSlot.Entry> stacks = new ArrayList<>(); List<PacketGhostSlot.Entry> stacks = new ArrayList<>();
var ingredients = slots.getSlotViews(RecipeIngredientRole.INPUT); var ingredients = slots.getSlotViews(RecipeIngredientRole.INPUT);
for (var entry : ingredients) for (var entry : ingredients)
stacks.add(PacketGhostSlot.Entry.fromStacks(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList()))); stacks.add(new PacketGhostSlot.Entry(player.level(), entry.getIngredients(VanillaTypes.ITEM_STACK).collect(Collectors.toList())));
PacketDistributor.sendToServer(new PacketGhostSlot(container.getTile().getBlockPos(), stacks)); PacketDistributor.SERVER.noArg().send(new PacketGhostSlot(container.getTile().getBlockPos(), stacks));
return null; return null;
} }

View file

@ -16,10 +16,10 @@ import net.minecraft.client.gui.components.Button;
import net.minecraft.client.renderer.Rect2i; import net.minecraft.client.renderer.Rect2i;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.neoforge.client.event.ClientTickEvent;
import net.neoforged.neoforge.client.event.ScreenEvent; import net.neoforged.neoforge.client.event.ScreenEvent;
import net.neoforged.neoforge.common.NeoForge; import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.TickEvent;
import net.neoforged.bus.api.SubscribeEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -38,7 +38,7 @@ public class JEIPrettyPipesPlugin implements IModPlugin {
@Override @Override
public ResourceLocation getPluginUid() { public ResourceLocation getPluginUid() {
return ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "jei_plugin"); return new ResourceLocation(PrettyPipes.ID, "jei_plugin");
} }
@Override @Override
@ -103,7 +103,7 @@ public class JEIPrettyPipesPlugin implements IModPlugin {
} }
@SubscribeEvent @SubscribeEvent
public void onClientTick(ClientTickEvent event) { public void onClientTick(TickEvent.ClientTickEvent event) {
if (!PlayerPrefs.get().syncJei) if (!PlayerPrefs.get().syncJei)
return; return;

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.network.PipeNetwork;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.network.syncher.SynchedEntityData;
@ -41,9 +41,9 @@ public class PipeFrameEntity extends ItemFrame implements IEntityWithComplexSpaw
} }
@Override @Override
protected void defineSynchedData(SynchedEntityData.Builder pBuilder) { protected void defineSynchedData() {
super.defineSynchedData(pBuilder); super.defineSynchedData();
pBuilder.define(PipeFrameEntity.AMOUNT, -1); this.entityData.define(PipeFrameEntity.AMOUNT, -1);
} }
@Override @Override
@ -154,15 +154,14 @@ public class PipeFrameEntity extends ItemFrame implements IEntityWithComplexSpaw
} }
@Override @Override
public void writeSpawnData(RegistryFriendlyByteBuf buffer) { public void writeSpawnData(FriendlyByteBuf buffer) {
buffer.writeBlockPos(this.pos); buffer.writeBlockPos(this.pos);
buffer.writeInt(this.direction.ordinal()); buffer.writeInt(this.direction.ordinal());
} }
@Override @Override
public void readSpawnData(RegistryFriendlyByteBuf additionalData) { public void readSpawnData(FriendlyByteBuf additionalData) {
this.pos = additionalData.readBlockPos(); this.pos = additionalData.readBlockPos();
this.direction = Direction.values()[additionalData.readInt()]; this.direction = Direction.values()[additionalData.readInt()];
} }
} }

View file

@ -13,10 +13,12 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.items.IItemHandler; import net.neoforged.neoforge.items.IItemHandler;
import javax.annotation.Nullable;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Stack; import java.util.Stack;
@ -26,16 +28,16 @@ public abstract class ModuleItem extends Item implements IModule {
private final String name; private final String name;
public ModuleItem(String name, Item.Properties properties) { public ModuleItem(String name) {
super(properties.stacksTo(16)); super(new Properties().stacksTo(16));
this.name = name; this.name = name;
} }
@Override @Override
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) { public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(pStack, pContext, pTooltipComponents, pTooltipFlag); super.appendHoverText(stack, worldIn, tooltip, flagIn);
Utility.addTooltip(this.name, pTooltipComponents); Utility.addTooltip(this.name, tooltip);
} }
@Override @Override
@ -107,5 +109,4 @@ public abstract class ModuleItem extends Item implements IModule {
public DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile) { public DirectionSelector getDirectionSelector(ItemStack module, PipeBlockEntity tile) {
return null; return null;
} }
} }

View file

@ -5,7 +5,6 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.entities.PipeFrameEntity; import de.ellpeck.prettypipes.entities.PipeFrameEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
@ -15,9 +14,10 @@ import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item; import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.CustomData;
import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
public class PipeFrameItem extends Item { public class PipeFrameItem extends Item {
@ -40,9 +40,10 @@ public class PipeFrameItem extends Item {
var world = context.getLevel(); var world = context.getLevel();
HangingEntity hangingentity = new PipeFrameEntity(Registry.pipeFrameEntity, world, blockpos1, direction); HangingEntity hangingentity = new PipeFrameEntity(Registry.pipeFrameEntity, world, blockpos1, direction);
var customdata = itemstack.getOrDefault(DataComponents.ENTITY_DATA, CustomData.EMPTY); var compoundTag = itemstack.getTag();
if (!customdata.isEmpty()) if (compoundTag != null) {
EntityType.updateCustomEntityTag(world, playerentity, hangingentity, customdata); EntityType.updateCustomEntityTag(world, playerentity, hangingentity, compoundTag);
}
if (hangingentity.survives()) { if (hangingentity.survives()) {
if (!world.isClientSide) { if (!world.isClientSide) {
@ -63,9 +64,8 @@ public class PipeFrameItem extends Item {
} }
@Override @Override
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) { public void appendHoverText(ItemStack stack, @Nullable Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
super.appendHoverText(pStack, pContext, pTooltipComponents, pTooltipFlag); super.appendHoverText(stack, worldIn, tooltip, flagIn);
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), pTooltipComponents); Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), tooltip);
} }
} }

View file

@ -4,7 +4,6 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.pipe.ConnectionType; import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.PipeBlock; import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundEvents;
@ -18,6 +17,7 @@ import net.minecraft.world.item.context.BlockPlaceContext;
import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.item.enchantment.Enchantments;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.EntityBlock;
@ -107,8 +107,8 @@ public class WrenchItem extends Item {
} }
@Override @Override
public void appendHoverText(ItemStack pStack, TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) { public void appendHoverText(ItemStack stack, Level worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), pTooltipComponents); Utility.addTooltip(BuiltInRegistries.ITEM.getKey(this).getPath(), tooltip);
} }
@Override @Override
@ -122,7 +122,7 @@ public class WrenchItem extends Item {
} }
@Override @Override
public boolean supportsEnchantment(ItemStack stack, Holder<Enchantment> enchantment) { public boolean canApplyAtEnchantingTable(ItemStack stack, Enchantment enchantment) {
return enchantment == Enchantments.SILK_TOUCH; return enchantment == Enchantments.SILK_TOUCH;
} }

View file

@ -1,13 +1,11 @@
package de.ellpeck.prettypipes.misc; package de.ellpeck.prettypipes.misc;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
@ -15,8 +13,6 @@ import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.client.gui.widget.ExtendedButton; import net.neoforged.neoforge.client.gui.widget.ExtendedButton;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
import java.util.List;
public class DirectionSelector { public class DirectionSelector {
private static final Direction[] ALL = ArrayUtils.addAll(Direction.values(), (Direction) null); private static final Direction[] ALL = ArrayUtils.addAll(Direction.values(), (Direction) null);
@ -37,7 +33,7 @@ public class DirectionSelector {
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
public AbstractWidget getButton(int x, int y) { public AbstractWidget getButton(int x, int y) {
return new ExtendedButton(x, y, 100, 20, Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> return new ExtendedButton(x, y, 100, 20, Component.translatable("info." + PrettyPipes.ID + ".populate"), button ->
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR, List.of())) { PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.DIRECTION_SELECTOR)) {
@Override @Override
public Component getMessage() { public Component getMessage() {
var pipe = DirectionSelector.this.pipe; var pipe = DirectionSelector.this.pipe;
@ -68,13 +64,18 @@ public class DirectionSelector {
if (!this.modified) if (!this.modified)
return; return;
this.modified = false; this.modified = false;
this.stack.set(Data.TYPE, new Data(this.direction.getName()));
var tag = new CompoundTag();
if (this.direction != null)
tag.putString("direction", this.direction.getName());
this.stack.getOrCreateTag().put("direction_selector", tag);
} }
public void load() { public void load() {
var data = this.stack.get(Data.TYPE); if (this.stack.hasTag()) {
if (data != null) var tag = this.stack.getTag().getCompound("direction_selector");
this.direction = Direction.byName(data.direction); this.direction = Direction.byName(tag.getString("direction"));
}
} }
public Direction[] directions() { public Direction[] directions() {
@ -101,14 +102,4 @@ public class DirectionSelector {
DirectionSelector getSelector(); DirectionSelector getSelector();
} }
public record Data(String direction) {
public static final Codec<DirectionSelector.Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.STRING.fieldOf("direction").forGetter(f -> f.direction)
).apply(i, DirectionSelector.Data::new));
public static final DataComponentType<DirectionSelector.Data> TYPE = DataComponentType.<DirectionSelector.Data>builder().persistent(DirectionSelector.Data.CODEC).cacheEncoding().build();
}
} }

View file

@ -15,7 +15,6 @@ public record EquatableItemStack(ItemStack stack, ItemEquality... equalityTypes)
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(this.stack.getItem(), this.stack.getComponents()); return Objects.hash(this.stack.getItem(), this.stack.getTag());
} }
} }

View file

@ -5,7 +5,7 @@ import de.ellpeck.prettypipes.network.PipeNetwork;
import net.minecraft.commands.Commands; import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber; import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.server.ServerStartingEvent; import net.neoforged.neoforge.event.server.ServerStartingEvent;
import java.io.IOException; import java.io.IOException;
@ -13,7 +13,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
@EventBusSubscriber @Mod.EventBusSubscriber
public final class Events { public final class Events {
@SubscribeEvent @SubscribeEvent

View file

@ -10,7 +10,7 @@ import java.util.function.Supplier;
public class ItemEquality { public class ItemEquality {
public static final ItemEquality DAMAGE = new ItemEquality((stack, filter) -> stack.getDamageValue() == filter.getDamageValue(), false, Type.DAMAGE); public static final ItemEquality DAMAGE = new ItemEquality((stack, filter) -> stack.getDamageValue() == filter.getDamageValue(), false, Type.DAMAGE);
public static final ItemEquality NBT = new ItemEquality((stack, filter) -> Objects.equals(stack.getComponents(), filter.getComponents()), false, Type.NBT); public static final ItemEquality NBT = new ItemEquality((stack, filter) -> Objects.equals(stack.getTag(), filter.getTag()) && stack.areAttachmentsCompatible(filter), false, Type.NBT);
public static final ItemEquality MOD = new ItemEquality((stack, filter) -> stack.getItem().getCreatorModId(stack).equals(filter.getItem().getCreatorModId(filter)), true, Type.MOD); public static final ItemEquality MOD = new ItemEquality((stack, filter) -> stack.getItem().getCreatorModId(stack).equals(filter.getItem().getCreatorModId(filter)), true, Type.MOD);
public final Type type; public final Type type;

View file

@ -1,9 +1,6 @@
package de.ellpeck.prettypipes.misc; package de.ellpeck.prettypipes.misc;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.packets.PacketButton; import de.ellpeck.prettypipes.packets.PacketButton;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem; import de.ellpeck.prettypipes.pipe.modules.modifier.FilterModifierModuleItem;
@ -13,7 +10,7 @@ import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.Tooltip; import net.minecraft.client.gui.components.Tooltip;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.inventory.Slot; import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -26,26 +23,18 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Supplier; import java.util.function.Supplier;
public class ItemFilter { public class ItemFilter extends ItemStackHandler {
public final ItemStackHandler content;
public boolean isWhitelist;
public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true;
private final ItemStack stack; private final ItemStack stack;
private final PipeBlockEntity pipe; private final PipeBlockEntity pipe;
public boolean isWhitelist;
public boolean canPopulateFromInventories;
public boolean canModifyWhitelist = true;
private boolean modified; private boolean modified;
public ItemFilter(int size, ItemStack stack, PipeBlockEntity pipe) { public ItemFilter(int size, ItemStack stack, PipeBlockEntity pipe) {
this.content = new ItemStackHandler(size) { super(size);
@Override
protected void onContentsChanged(int slot) {
ItemFilter.this.modified = true;
}
};
this.stack = stack; this.stack = stack;
this.pipe = pipe; this.pipe = pipe;
this.load(); this.load();
@ -53,8 +42,8 @@ public class ItemFilter {
public List<Slot> getSlots(int x, int y) { public List<Slot> getSlots(int x, int y) {
List<Slot> slots = new ArrayList<>(); List<Slot> slots = new ArrayList<>();
for (var i = 0; i < this.content.getSlots(); i++) for (var i = 0; i < this.getSlots(); i++)
slots.add(new FilterSlot(this.content, i, x + i % 9 * 18, y + i / 9 * 18, true)); slots.add(new FilterSlot(this, i, x + i % 9 * 18, y + i / 9 * 18, true));
return slots; return slots;
} }
@ -64,12 +53,12 @@ public class ItemFilter {
if (this.canModifyWhitelist) { if (this.canModifyWhitelist) {
var whitelistText = (Supplier<String>) () -> "info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist"); var whitelistText = (Supplier<String>) () -> "info." + PrettyPipes.ID + "." + (this.isWhitelist ? "whitelist" : "blacklist");
buttons.add(Button.builder(Component.translatable(whitelistText.get()), button -> { buttons.add(Button.builder(Component.translatable(whitelistText.get()), button -> {
PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(0)); PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 0);
button.setMessage(Component.translatable(whitelistText.get())); button.setMessage(Component.translatable(whitelistText.get()));
}).bounds(x - 20, y, 20, 20).tooltip(Tooltip.create(Component.translatable(whitelistText.get() + ".description").withStyle(ChatFormatting.GRAY))).build()); }).bounds(x - 20, y, 20, 20).tooltip(Tooltip.create(Component.translatable(whitelistText.get() + ".description").withStyle(ChatFormatting.GRAY))).build());
} }
if (this.canPopulateFromInventories) { if (this.canPopulateFromInventories) {
buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, List.of(1))).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build()); buttons.add(Button.builder(Component.translatable("info." + PrettyPipes.ID + ".populate"), button -> PacketButton.sendAndExecute(this.pipe.getBlockPos(), PacketButton.ButtonResult.FILTER_CHANGE, 1)).bounds(x - 42, y, 20, 20).tooltip(Tooltip.create(Component.translatable("info." + PrettyPipes.ID + ".populate.description").withStyle(ChatFormatting.GRAY))).build());
} }
return buttons; return buttons;
} }
@ -95,7 +84,7 @@ public class ItemFilter {
copy.setCount(1); copy.setCount(1);
// try inserting into ourselves and any filter increase modifiers // try inserting into ourselves and any filter increase modifiers
for (var filter : filters) { for (var filter : filters) {
if (ItemHandlerHelper.insertItem(filter.content, copy, false).isEmpty()) { if (ItemHandlerHelper.insertItem(filter, copy, false).isEmpty()) {
changed = true; changed = true;
filter.save(); filter.save();
break; break;
@ -115,9 +104,9 @@ public class ItemFilter {
private boolean isFiltered(ItemStack stack, Direction direction) { private boolean isFiltered(ItemStack stack, Direction direction) {
var types = ItemFilter.getEqualityTypes(this.pipe); var types = ItemFilter.getEqualityTypes(this.pipe);
// also check if any filter increase modules have the item we need // also check if any filter increase modules have the item we need
for (ItemFilter handler : this.pipe.getFilters(direction)) { for (ItemStackHandler handler : this.pipe.getFilters(direction)) {
for (var i = 0; i < handler.content.getSlots(); i++) { for (var i = 0; i < handler.getSlots(); i++) {
var filter = handler.content.getStackInSlot(i); var filter = handler.getStackInSlot(i);
if (filter.isEmpty()) if (filter.isEmpty())
continue; continue;
if (ItemEquality.compareItems(stack, filter, types)) if (ItemEquality.compareItems(stack, filter, types))
@ -129,20 +118,35 @@ public class ItemFilter {
public void save() { public void save() {
if (this.modified) { if (this.modified) {
this.stack.set(Data.TYPE, new Data(this.content, this.isWhitelist)); this.stack.getOrCreateTag().put("filter", this.serializeNBT());
this.pipe.setChanged(); this.pipe.setChanged();
this.modified = false; this.modified = false;
} }
} }
public void load() { public void load() {
var content = this.stack.get(Data.TYPE); if (this.stack.hasTag())
if (content != null) { this.deserializeNBT(this.stack.getTag().getCompound("filter"));
this.content.setSize(content.items.getSlots());
for (var i = 0; i < this.content.getSlots(); i++)
this.content.setStackInSlot(i, content.items.getStackInSlot(i));
this.isWhitelist = content.whitelist;
} }
@Override
public CompoundTag serializeNBT() {
var nbt = super.serializeNBT();
if (this.canModifyWhitelist)
nbt.putBoolean("whitelist", this.isWhitelist);
return nbt;
}
@Override
public void deserializeNBT(CompoundTag nbt) {
super.deserializeNBT(nbt);
if (this.canModifyWhitelist)
this.isWhitelist = nbt.getBoolean("whitelist");
}
@Override
protected void onContentsChanged(int slot) {
this.modified = true;
} }
public static ItemEquality[] getEqualityTypes(PipeBlockEntity pipe) { public static ItemEquality[] getEqualityTypes(PipeBlockEntity pipe) {
@ -161,14 +165,4 @@ public class ItemFilter {
} }
public record Data(ItemStackHandler items, boolean whitelist) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("items").forGetter(f -> f.items),
Codec.BOOL.fieldOf("whitelist").forGetter(f -> f.whitelist)
).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
} }

View file

@ -1,7 +1,9 @@
package de.ellpeck.prettypipes.misc; package de.ellpeck.prettypipes.misc;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import net.minecraft.core.HolderLookup; import net.minecraft.core.RegistryAccess;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.*; import net.minecraft.world.item.crafting.*;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
@ -15,10 +17,9 @@ public class ModuleClearingRecipe extends CustomRecipe {
} }
@Override @Override
public boolean matches(CraftingInput container, Level level) { public boolean matches(CraftingContainer container, Level level) {
var foundModule = false; var foundModule = false;
for (var i = 0; i < container.size(); i++) { for (var stack : container.getItems()) {
var stack = container.getItem(i);
if (!foundModule && stack.getItem() instanceof IModule) { if (!foundModule && stack.getItem() instanceof IModule) {
foundModule = true; foundModule = true;
} else if (!stack.isEmpty()) { } else if (!stack.isEmpty()) {
@ -29,13 +30,11 @@ public class ModuleClearingRecipe extends CustomRecipe {
} }
@Override @Override
public ItemStack assemble(CraftingInput container, HolderLookup.Provider pRegistries) { public ItemStack assemble(CraftingContainer container, RegistryAccess access) {
for (var i = 0; i < container.size(); i++) { var module = container.getItems().stream().filter(i -> i.getItem() instanceof IModule).findFirst().orElse(ItemStack.EMPTY);
var stack = container.getItem(i); if (!module.isEmpty())
if (stack.getItem() instanceof IModule) module = new ItemStack(module.getItem());
return new ItemStack(stack.getItem()); return module;
}
return ItemStack.EMPTY;
} }
@Override @Override

View file

@ -50,5 +50,4 @@ public class PlayerPrefs {
var location = Minecraft.getInstance().gameDirectory; var location = Minecraft.getInstance().gameDirectory;
return new File(location, PrettyPipes.ID + "prefs"); return new File(location, PrettyPipes.ID + "prefs");
} }
} }

View file

@ -1,8 +1,6 @@
package de.ellpeck.prettypipes.network; package de.ellpeck.prettypipes.network;
import de.ellpeck.prettypipes.Utility;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
@ -20,20 +18,20 @@ public class NetworkEdge extends DefaultWeightedEdge implements INBTSerializable
public NetworkEdge() { public NetworkEdge() {
} }
public NetworkEdge(HolderLookup.Provider provider, CompoundTag nbt) { public NetworkEdge(CompoundTag nbt) {
this.deserializeNBT(provider, nbt); this.deserializeNBT(nbt);
} }
public BlockPos getStartPipe() { public BlockPos getStartPipe() {
return this.pipes.getFirst(); return this.pipes.get(0);
} }
public BlockPos getEndPipe() { public BlockPos getEndPipe() {
return this.pipes.getLast(); return this.pipes.get(this.pipes.size() - 1);
} }
@Override @Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) { public CompoundTag serializeNBT() {
var nbt = new CompoundTag(); var nbt = new CompoundTag();
var list = new ListTag(); var list = new ListTag();
for (var pos : this.pipes) for (var pos : this.pipes)
@ -43,11 +41,10 @@ public class NetworkEdge extends DefaultWeightedEdge implements INBTSerializable
} }
@Override @Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) { public void deserializeNBT(CompoundTag nbt) {
this.pipes.clear(); this.pipes.clear();
var list = nbt.getList("pipes", Tag.TAG_COMPOUND); var list = nbt.getList("pipes", Tag.TAG_COMPOUND);
for (var tag : list) for (var i = 0; i < list.size(); i++)
this.pipes.add(Utility.readBlockPos(tag)); this.pipes.add(NbtUtils.readBlockPos(list.getCompound(i)));
} }
} }

View file

@ -3,7 +3,6 @@ package de.ellpeck.prettypipes.network;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -29,8 +28,8 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
this.direction = direction; this.direction = direction;
} }
public NetworkLocation(HolderLookup.Provider provider, CompoundTag nbt) { public NetworkLocation(CompoundTag nbt) {
this.deserializeNBT(provider, nbt); this.deserializeNBT(nbt);
} }
public List<Integer> getStackSlots(Level world, ItemStack stack, ItemEquality... equalityTypes) { public List<Integer> getStackSlots(Level world, ItemStack stack, ItemEquality... equalityTypes) {
@ -92,7 +91,7 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
} }
@Override @Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) { public CompoundTag serializeNBT() {
var nbt = new CompoundTag(); var nbt = new CompoundTag();
nbt.put("pipe_pos", NbtUtils.writeBlockPos(this.pipePos)); nbt.put("pipe_pos", NbtUtils.writeBlockPos(this.pipePos));
nbt.putInt("direction", this.direction.ordinal()); nbt.putInt("direction", this.direction.ordinal());
@ -100,9 +99,8 @@ public class NetworkLocation implements INBTSerializable<CompoundTag> {
} }
@Override @Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) { public void deserializeNBT(CompoundTag nbt) {
this.pipePos = NbtUtils.readBlockPos(nbt, "pipe_pos").orElse(null); this.pipePos = NbtUtils.readBlockPos(nbt.getCompound("pipe_pos"));
this.direction = Direction.values()[nbt.getInt("direction")]; this.direction = Direction.values()[nbt.getInt("direction")];
} }
} }

View file

@ -1,6 +1,5 @@
package de.ellpeck.prettypipes.network; package de.ellpeck.prettypipes.network;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.common.util.INBTSerializable; import net.neoforged.neoforge.common.util.INBTSerializable;
@ -21,24 +20,24 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
this.stack = stack; this.stack = stack;
} }
public NetworkLock(HolderLookup.Provider provider, CompoundTag nbt) { public NetworkLock(CompoundTag nbt) {
this.deserializeNBT(provider, nbt); this.deserializeNBT(nbt);
} }
@Override @Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) { public CompoundTag serializeNBT() {
var nbt = new CompoundTag(); var nbt = new CompoundTag();
nbt.putUUID("id", this.lockId); nbt.putUUID("id", this.lockId);
nbt.put("location", this.location.serializeNBT(provider)); nbt.put("location", this.location.serializeNBT());
nbt.put("stack", this.stack.save(provider)); nbt.put("stack", this.stack.save(new CompoundTag()));
return nbt; return nbt;
} }
@Override @Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) { public void deserializeNBT(CompoundTag nbt) {
this.lockId = nbt.getUUID("id"); this.lockId = nbt.getUUID("id");
this.location = new NetworkLocation(provider, nbt.getCompound("location")); this.location = new NetworkLocation(nbt.getCompound("location"));
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack")); this.stack = ItemStack.of(nbt.getCompound("stack"));
} }
@Override @Override
@ -57,5 +56,4 @@ public class NetworkLock implements INBTSerializable<CompoundTag> {
public String toString() { public String toString() {
return "NetworkLock{" + "location=" + this.location.pipePos + ", stack=" + this.stack + '}'; return "NetworkLock{" + "location=" + this.location.pipePos + ", stack=" + this.stack + '}';
} }
} }

View file

@ -8,7 +8,6 @@ import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
@ -34,7 +33,7 @@ import java.util.function.Consumer;
public class PipeItem implements IPipeItem { public class PipeItem implements IPipeItem {
public static final ResourceLocation TYPE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "pipe_item"); public static final ResourceLocation TYPE = new ResourceLocation(PrettyPipes.ID, "pipe_item");
public ItemStack stack; public ItemStack stack;
public float speed; public float speed;
@ -64,10 +63,10 @@ public class PipeItem implements IPipeItem {
this(PipeItem.TYPE, stack, speed); this(PipeItem.TYPE, stack, speed);
} }
public PipeItem(HolderLookup.Provider provider, ResourceLocation type, CompoundTag nbt) { public PipeItem(ResourceLocation type, CompoundTag nbt) {
this.type = type; this.type = type;
this.path = new ArrayList<>(); this.path = new ArrayList<>();
this.deserializeNBT(provider, nbt); this.deserializeNBT(nbt);
} }
@Override @Override
@ -222,12 +221,12 @@ public class PipeItem implements IPipeItem {
} }
protected BlockPos getStartPipe() { protected BlockPos getStartPipe() {
return this.path.getFirst(); return this.path.get(0);
} }
@Override @Override
public BlockPos getDestPipe() { public BlockPos getDestPipe() {
return this.path.getLast(); return this.path.get(this.path.size() - 1);
} }
@Override @Override
@ -241,10 +240,10 @@ public class PipeItem implements IPipeItem {
} }
@Override @Override
public CompoundTag serializeNBT(HolderLookup.Provider provider) { public CompoundTag serializeNBT() {
var nbt = new CompoundTag(); var nbt = new CompoundTag();
nbt.putString("type", this.type.toString()); nbt.putString("type", this.type.toString());
nbt.put("stack", this.stack.save(provider)); nbt.put("stack", this.stack.save(new CompoundTag()));
nbt.putFloat("speed", this.speed); nbt.putFloat("speed", this.speed);
nbt.put("start_inv", NbtUtils.writeBlockPos(this.startInventory)); nbt.put("start_inv", NbtUtils.writeBlockPos(this.startInventory));
nbt.put("dest_inv", NbtUtils.writeBlockPos(this.destInventory)); nbt.put("dest_inv", NbtUtils.writeBlockPos(this.destInventory));
@ -262,12 +261,12 @@ public class PipeItem implements IPipeItem {
} }
@Override @Override
public void deserializeNBT(HolderLookup.Provider provider, CompoundTag nbt) { public void deserializeNBT(CompoundTag nbt) {
this.stack = ItemStack.parseOptional(provider, nbt.getCompound("stack")); this.stack = ItemStack.of(nbt.getCompound("stack"));
this.speed = nbt.getFloat("speed"); this.speed = nbt.getFloat("speed");
this.startInventory = NbtUtils.readBlockPos(nbt, "start_inv").orElse(null); this.startInventory = NbtUtils.readBlockPos(nbt.getCompound("start_inv"));
this.destInventory = NbtUtils.readBlockPos(nbt, "dest_inv").orElse(null); this.destInventory = NbtUtils.readBlockPos(nbt.getCompound("dest_inv"));
this.currGoalPos = NbtUtils.readBlockPos(nbt, "curr_goal").orElse(null); this.currGoalPos = NbtUtils.readBlockPos(nbt.getCompound("curr_goal"));
this.retryOnObstruction = nbt.getBoolean("drop_on_obstruction"); this.retryOnObstruction = nbt.getBoolean("drop_on_obstruction");
this.currentTile = nbt.getInt("tile"); this.currentTile = nbt.getInt("tile");
this.x = nbt.getFloat("x"); this.x = nbt.getFloat("x");
@ -275,8 +274,8 @@ public class PipeItem implements IPipeItem {
this.z = nbt.getFloat("z"); this.z = nbt.getFloat("z");
this.path.clear(); this.path.clear();
var list = nbt.getList("path", Tag.TAG_COMPOUND); var list = nbt.getList("path", Tag.TAG_COMPOUND);
for (var tag : list) for (var i = 0; i < list.size(); i++)
this.path.add(Utility.readBlockPos(tag)); this.path.add(NbtUtils.readBlockPos(list.getCompound(i)));
} }
@Override @Override
@ -345,7 +344,7 @@ public class PipeItem implements IPipeItem {
// add the single pipe twice if there's only one // add the single pipe twice if there's only one
// this is a dirty hack, but it works fine so eh // this is a dirty hack, but it works fine so eh
for (var i = 0; i < 2; i++) for (var i = 0; i < 2; i++)
ret.add(nodes.getFirst()); ret.add(nodes.get(0));
return ret; return ret;
} }
for (var i = 0; i < nodes.size() - 1; i++) { for (var i = 0; i < nodes.size() - 1; i++) {
@ -369,5 +368,4 @@ public class PipeItem implements IPipeItem {
} }
return ret; return ret;
} }
} }

View file

@ -12,14 +12,12 @@ import de.ellpeck.prettypipes.pipe.PipeBlock;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag; import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtUtils; import net.minecraft.nbt.NbtUtils;
import net.minecraft.nbt.Tag; import net.minecraft.nbt.Tag;
import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.saveddata.SavedData; import net.minecraft.world.level.saveddata.SavedData;
@ -62,17 +60,17 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
this.dijkstra = new DijkstraShortestPath<>(this.graph); this.dijkstra = new DijkstraShortestPath<>(this.graph);
} }
public PipeNetwork(CompoundTag nbt, HolderLookup.Provider provider) { public PipeNetwork(CompoundTag nbt) {
this(); this();
var nodes = nbt.getList("nodes", Tag.TAG_COMPOUND); var nodes = nbt.getList("nodes", Tag.TAG_COMPOUND);
for (var node : nodes) for (var i = 0; i < nodes.size(); i++)
this.graph.addVertex(Utility.readBlockPos(node)); this.graph.addVertex(NbtUtils.readBlockPos(nodes.getCompound(i)));
var edges = nbt.getList("edges", Tag.TAG_COMPOUND); var edges = nbt.getList("edges", Tag.TAG_COMPOUND);
for (var i = 0; i < edges.size(); i++) for (var i = 0; i < edges.size(); i++)
this.addEdge(new NetworkEdge(provider, edges.getCompound(i))); this.addEdge(new NetworkEdge(edges.getCompound(i)));
for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), i -> IPipeItem.load(provider, i))) for (var item : Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load))
this.pipeItems.put(item.getCurrentPipe(), item); this.pipeItems.put(item.getCurrentPipe(), item);
for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), t -> new NetworkLock(provider, t))) for (var lock : Utility.deserializeAll(nbt.getList("locks", Tag.TAG_COMPOUND), NetworkLock::new))
this.createNetworkLock(lock); this.createNetworkLock(lock);
} }
@ -110,17 +108,17 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
} }
@Override @Override
public CompoundTag save(CompoundTag nbt, HolderLookup.Provider provider) { public CompoundTag save(CompoundTag nbt) {
var nodes = new ListTag(); var nodes = new ListTag();
for (var node : this.graph.vertexSet()) for (var node : this.graph.vertexSet())
nodes.add(NbtUtils.writeBlockPos(node)); nodes.add(NbtUtils.writeBlockPos(node));
nbt.put("nodes", nodes); nbt.put("nodes", nodes);
var edges = new ListTag(); var edges = new ListTag();
for (var edge : this.graph.edgeSet()) for (var edge : this.graph.edgeSet())
edges.add(edge.serializeNBT(provider)); edges.add(edge.serializeNBT());
nbt.put("edges", edges); nbt.put("edges", edges);
nbt.put("items", Utility.serializeAll(provider, this.pipeItems.values())); nbt.put("items", Utility.serializeAll(this.pipeItems.values()));
nbt.put("locks", Utility.serializeAll(provider, this.networkLocks.values())); nbt.put("locks", Utility.serializeAll(this.networkLocks.values()));
return nbt; return nbt;
} }
@ -201,7 +199,7 @@ public class PipeNetwork extends SavedData implements GraphListener<BlockPos, Ne
var item = itemSupplier.apply(startPipe.getItemSpeed(stack)); var item = itemSupplier.apply(startPipe.getItemSpeed(stack));
item.setDestination(startInventory, destInventory, path); item.setDestination(startInventory, destInventory, path);
startPipe.addNewItem(item); startPipe.addNewItem(item);
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(startPipePos), new PacketItemEnterPipe(startPipePos, item.serializeNBT(this.level.registryAccess()))); PacketDistributor.TRACKING_CHUNK.with(this.level.getChunkAt(startPipePos)).send(new PacketItemEnterPipe(startPipePos, item));
return true; return true;
} }

View file

@ -13,10 +13,8 @@ import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.MenuProvider; import net.minecraft.world.MenuProvider;
@ -24,50 +22,64 @@ import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.neoforged.neoforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import org.apache.logging.log4j.util.TriConsumer; import org.apache.logging.log4j.util.TriConsumer;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import static de.ellpeck.prettypipes.misc.DirectionSelector.IDirectionContainer; import static de.ellpeck.prettypipes.misc.DirectionSelector.IDirectionContainer;
public record PacketButton(BlockPos pos, int result, List<Integer> data) implements CustomPacketPayload { public class PacketButton implements CustomPacketPayload {
public static final Type<PacketButton> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "button")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "button");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketButton> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketButton::pos,
ByteBufCodecs.INT, PacketButton::result,
ByteBufCodecs.collection(ArrayList::new, ByteBufCodecs.INT), PacketButton::data,
PacketButton::new);
public PacketButton(BlockPos pos, ButtonResult result, List<Integer> data) { private final BlockPos pos;
this(pos, result.ordinal(), data); private final ButtonResult result;
private final int[] data;
public PacketButton(BlockPos pos, ButtonResult result, int... data) {
this.pos = pos;
this.result = result;
this.data = data;
}
public PacketButton(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.result = ButtonResult.values()[buf.readByte()];
this.data = buf.readVarIntArray();
} }
@Override @Override
public Type<? extends CustomPacketPayload> type() { public void write(FriendlyByteBuf buf) {
return PacketButton.TYPE; buf.writeBlockPos(this.pos);
buf.writeByte(this.result.ordinal());
buf.writeVarIntArray(this.data);
} }
public static void onMessage(PacketButton message, IPayloadContext ctx) { @Override
var player = ctx.player(); public ResourceLocation id() {
ButtonResult.values()[message.result].action.accept(message.pos, message.data, player); return PacketButton.ID;
} }
public static void sendAndExecute(BlockPos pos, ButtonResult result, List<Integer> data) { public static void onMessage(PacketButton message, PlayPayloadContext ctx) {
PacketDistributor.sendToServer(new PacketButton(pos, result, data)); ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
message.result.action.accept(message.pos, message.data, player);
});
}
public static void sendAndExecute(BlockPos pos, ButtonResult result, int... data) {
PacketDistributor.SERVER.noArg().send(new PacketButton(pos, result, data));
result.action.accept(pos, data, Minecraft.getInstance().player); result.action.accept(pos, data, Minecraft.getInstance().player);
} }
public enum ButtonResult { public enum ButtonResult {
PIPE_TAB((pos, data, player) -> { PIPE_TAB((pos, data, player) -> {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level(), pos); var tile = Utility.getBlockEntity(PipeBlockEntity.class, player.level(), pos);
if (data.getFirst() < 0) { if (data[0] < 0) {
player.openMenu(tile, pos); player.openMenu(tile, pos);
} else { } else {
var stack = tile.modules.getStackInSlot(data.getFirst()); var stack = tile.modules.getStackInSlot(data[0]);
player.openMenu(new MenuProvider() { player.openMenu(new MenuProvider() {
@Override @Override
public Component getDisplayName() { public Component getDisplayName() {
@ -77,32 +89,30 @@ public record PacketButton(BlockPos pos, int result, List<Integer> data) impleme
@Nullable @Nullable
@Override @Override
public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) { public AbstractContainerMenu createMenu(int windowId, Inventory inv, Player player) {
return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data.getFirst()); return ((IModule) stack.getItem()).getContainer(stack, tile, windowId, inv, player, data[0]);
} }
}, buf -> { }, buf -> {
buf.writeBlockPos(pos); buf.writeBlockPos(pos);
buf.writeInt(data.getFirst()); buf.writeInt(data[0]);
}); });
} }
}), }),
FILTER_CHANGE((pos, data, player) -> { FILTER_CHANGE((pos, data, player) -> {
if (player.containerMenu instanceof IFilteredContainer filtered) if (player.containerMenu instanceof IFilteredContainer filtered)
filtered.getFilter().onButtonPacket(filtered, data.getFirst()); filtered.getFilter().onButtonPacket(filtered, data[0]);
}), }),
STACK_SIZE_MODULE_BUTTON((pos, data, player) -> { STACK_SIZE_MODULE_BUTTON((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu; var container = (AbstractPipeContainer<?>) player.containerMenu;
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT); StackSizeModuleItem.setLimitToMaxStackSize(container.moduleStack, !StackSizeModuleItem.getLimitToMaxStackSize(container.moduleStack));
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(moduleData.maxStackSize(), !moduleData.limitToMaxStackSize()));
}), }),
STACK_SIZE_AMOUNT((pos, data, player) -> { STACK_SIZE_AMOUNT((pos, data, player) -> {
var container = (AbstractPipeContainer<?>) player.containerMenu; var container = (AbstractPipeContainer<?>) player.containerMenu;
var moduleData = container.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT); StackSizeModuleItem.setMaxStackSize(container.moduleStack, data[0]);
container.moduleStack.set(StackSizeModuleItem.Data.TYPE, new StackSizeModuleItem.Data(data.getFirst(), moduleData.limitToMaxStackSize()));
}), }),
CRAFT_TERMINAL_REQUEST((pos, data, player) -> { CRAFT_TERMINAL_REQUEST((pos, data, player) -> {
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), pos); var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), pos);
tile.requestCraftingItems(player, data.getFirst(), data.get(1) > 0); tile.requestCraftingItems(player, data[0], data[1] > 0);
}), }),
CANCEL_CRAFTING((pos, data, player) -> { CANCEL_CRAFTING((pos, data, player) -> {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), pos); var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), pos);
@ -110,16 +120,16 @@ public record PacketButton(BlockPos pos, int result, List<Integer> data) impleme
}), }),
TAG_FILTER((pos, data, player) -> { TAG_FILTER((pos, data, player) -> {
var container = (FilterModifierModuleContainer) player.containerMenu; var container = (FilterModifierModuleContainer) player.containerMenu;
FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data.getFirst())); FilterModifierModuleItem.setFilterTag(container.moduleStack, container.getTags().get(data[0]));
}), }),
DIRECTION_SELECTOR((pos, data, player) -> { DIRECTION_SELECTOR((pos, data, player) -> {
if (player.containerMenu instanceof IDirectionContainer filtered) if (player.containerMenu instanceof IDirectionContainer filtered)
filtered.getSelector().onButtonPacket(); filtered.getSelector().onButtonPacket();
}); });
public final TriConsumer<BlockPos, List<Integer>, Player> action; public final TriConsumer<BlockPos, int[], Player> action;
ButtonResult(TriConsumer<BlockPos, List<Integer>, Player> action) { ButtonResult(TriConsumer<BlockPos, int[], Player> action) {
this.action = action; this.action = action;
} }
} }

View file

@ -2,40 +2,63 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer; import de.ellpeck.prettypipes.pipe.modules.craft.CraftingModuleContainer;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.items.ItemHandlerHelper; import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.ItemStackHandler;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public record PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) implements CustomPacketPayload { public class PacketCraftingModuleTransfer implements CustomPacketPayload {
public static final Type<PacketCraftingModuleTransfer> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "crafting_module_transfer")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "crafting_module_transfer");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketCraftingModuleTransfer> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::inputs,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketCraftingModuleTransfer::outputs,
PacketCraftingModuleTransfer::new);
@Override private final List<ItemStack> inputs;
public Type<? extends CustomPacketPayload> type() { private final List<ItemStack> outputs;
return PacketCraftingModuleTransfer.TYPE;
public PacketCraftingModuleTransfer(List<ItemStack> inputs, List<ItemStack> outputs) {
this.inputs = inputs;
this.outputs = outputs;
} }
public static void onMessage(PacketCraftingModuleTransfer message, IPayloadContext ctx) { public PacketCraftingModuleTransfer(FriendlyByteBuf buf) {
var player = ctx.player(); this.inputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.inputs.add(buf.readItem());
this.outputs = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.outputs.add(buf.readItem());
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeInt(this.inputs.size());
for (var stack : this.inputs)
buf.writeItem(stack);
buf.writeInt(this.outputs.size());
for (var stack : this.outputs)
buf.writeItem(stack);
}
@Override
public ResourceLocation id() {
return PacketCraftingModuleTransfer.ID;
}
public static void onMessage(PacketCraftingModuleTransfer message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
if (player.containerMenu instanceof CraftingModuleContainer container) { if (player.containerMenu instanceof CraftingModuleContainer container) {
PacketCraftingModuleTransfer.copy(container.input, message.inputs); PacketCraftingModuleTransfer.copy(container.input, message.inputs);
PacketCraftingModuleTransfer.copy(container.output, message.outputs); PacketCraftingModuleTransfer.copy(container.output, message.outputs);
container.modified = true; container.modified = true;
container.broadcastChanges(); container.broadcastChanges();
} }
});
} }
private static void copy(ItemStackHandler container, List<ItemStack> contents) { private static void copy(ItemStackHandler container, List<ItemStack> contents) {

View file

@ -7,9 +7,7 @@ import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity; import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.tags.TagKey; import net.minecraft.tags.TagKey;
@ -17,45 +15,78 @@ import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items; import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements CustomPacketPayload { public class PacketGhostSlot implements CustomPacketPayload {
public static final Type<PacketGhostSlot> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "ghost_slot")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "ghost_slot");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketGhostSlot> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketGhostSlot::pos,
ByteBufCodecs.collection(ArrayList::new, Entry.CODEC), PacketGhostSlot::stacks,
PacketGhostSlot::new);
@Override private final BlockPos pos;
public Type<? extends CustomPacketPayload> type() { private final List<Entry> stacks;
return PacketGhostSlot.TYPE;
public PacketGhostSlot(BlockPos pos, List<Entry> stacks) {
this.pos = pos;
this.stacks = stacks;
} }
public static void onMessage(PacketGhostSlot message, IPayloadContext ctx) { public PacketGhostSlot(FriendlyByteBuf buf) {
var player = ctx.player(); this.pos = buf.readBlockPos();
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(new Entry(buf));
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.pos);
buf.writeInt(this.stacks.size());
for (var entry : this.stacks)
entry.write(buf);
}
@Override
public ResourceLocation id() {
return PacketGhostSlot.ID;
}
public static void onMessage(PacketGhostSlot message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var player = ctx.player().orElseThrow();
var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), message.pos); var tile = Utility.getBlockEntity(CraftingTerminalBlockEntity.class, player.level(), message.pos);
if (tile != null) if (tile != null)
tile.setGhostItems(message.stacks); tile.setGhostItems(message.stacks);
});
} }
public record Entry(List<ItemStack> stacks, TagKey<Item> tag) { public static class Entry {
public static final StreamCodec<RegistryFriendlyByteBuf, Entry> CODEC = StreamCodec.composite( private final List<ItemStack> stacks;
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), Entry::stacks, private final TagKey<Item> tag;
ByteBufCodecs.fromCodec(TagKey.codec(Registries.ITEM)), Entry::tag,
Entry::new);
public static Entry fromStacks(Level level, List<ItemStack> stacks) { public Entry(Level level, List<ItemStack> stacks) {
var tag = Entry.getTagForStacks(level, stacks); var tag = Entry.getTagForStacks(level, stacks);
if (tag != null) { if (tag != null) {
return new Entry(null, tag); this.stacks = null;
this.tag = tag;
} else { } else {
return new Entry(stacks, null); this.stacks = stacks;
this.tag = null;
}
}
public Entry(FriendlyByteBuf buf) {
if (buf.readBoolean()) {
this.tag = null;
this.stacks = new ArrayList<>();
for (var i = buf.readInt(); i > 0; i--)
this.stacks.add(buf.readItem());
} else {
this.stacks = null;
this.tag = TagKey.create(Registries.ITEM, new ResourceLocation(buf.readUtf()));
} }
} }
@ -67,6 +98,18 @@ public record PacketGhostSlot(BlockPos pos, List<Entry> stacks) implements Custo
.map(h -> new ItemStack(h.value())).collect(Collectors.toList()); .map(h -> new ItemStack(h.value())).collect(Collectors.toList());
} }
public void write(FriendlyByteBuf buf) {
if (this.stacks != null) {
buf.writeBoolean(true);
buf.writeInt(this.stacks.size());
for (var stack : this.stacks)
buf.writeItem(stack);
} else {
buf.writeBoolean(false);
buf.writeUtf(this.tag.location().toString());
}
}
private static TagKey<Item> getTagForStacks(Level level, List<ItemStack> stacks) { private static TagKey<Item> getTagForStacks(Level level, List<ItemStack> stacks) {
return level.registryAccess().registry(Registries.ITEM).orElseThrow().getTags().filter(e -> { return level.registryAccess().registry(Registries.ITEM).orElseThrow().getTags().filter(e -> {
var tag = e.getSecond(); var tag = e.getSecond();

View file

@ -7,34 +7,49 @@ import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
public record PacketItemEnterPipe(BlockPos tilePos, CompoundTag item) implements CustomPacketPayload { public class PacketItemEnterPipe implements CustomPacketPayload {
public static final Type<PacketItemEnterPipe> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "item_enter_pipe")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "item_enter_pipe");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketItemEnterPipe> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketItemEnterPipe::tilePos,
ByteBufCodecs.COMPOUND_TAG, PacketItemEnterPipe::item,
PacketItemEnterPipe::new);
@Override private final BlockPos tilePos;
public Type<? extends CustomPacketPayload> type() { private final CompoundTag item;
return PacketItemEnterPipe.TYPE;
public PacketItemEnterPipe(BlockPos tilePos, IPipeItem item) {
this.tilePos = tilePos;
this.item = item.serializeNBT();
} }
public static void onMessage(PacketItemEnterPipe message, IPayloadContext ctx) { public PacketItemEnterPipe(FriendlyByteBuf buf) {
this.tilePos = buf.readBlockPos();
this.item = buf.readNbt();
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeBlockPos(this.tilePos);
buf.writeNbt(this.item);
}
@Override
public ResourceLocation id() {
return PacketItemEnterPipe.ID;
}
public static void onMessage(PacketItemEnterPipe message, PlayPayloadContext ctx) {
ctx.workHandler().execute(() -> {
var mc = Minecraft.getInstance(); var mc = Minecraft.getInstance();
if (mc.level == null) if (mc.level == null)
return; return;
var item = IPipeItem.load(mc.level.registryAccess(), message.item); var item = IPipeItem.load(message.item);
var pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos); var pipe = Utility.getBlockEntity(PipeBlockEntity.class, mc.level, message.tilePos);
if (pipe != null) if (pipe != null)
pipe.getItems().add(item); pipe.getItems().add(item);
});
} }
} }

View file

@ -3,35 +3,76 @@ package de.ellpeck.prettypipes.packets;
import de.ellpeck.prettypipes.PrettyPipes; import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui; import de.ellpeck.prettypipes.terminal.containers.ItemTerminalGui;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public record PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) implements CustomPacketPayload { public class PacketNetworkItems implements CustomPacketPayload {
public static final Type<PacketNetworkItems> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "network_items")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "network_items");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketNetworkItems> CODEC = StreamCodec.composite(
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::items,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::craftables,
ByteBufCodecs.collection(ArrayList::new, ItemStack.STREAM_CODEC), PacketNetworkItems::currentlyCrafting,
PacketNetworkItems::new);
@Override private final List<ItemStack> items;
public Type<? extends CustomPacketPayload> type() { private final List<ItemStack> craftables;
return PacketNetworkItems.TYPE; private final List<ItemStack> currentlyCrafting;
public PacketNetworkItems(List<ItemStack> items, List<ItemStack> craftables, List<ItemStack> currentlyCrafting) {
this.items = items;
this.craftables = craftables;
this.currentlyCrafting = currentlyCrafting;
} }
public static void onMessage(PacketNetworkItems message, IPayloadContext ctx) { public PacketNetworkItems(FriendlyByteBuf buf) {
this.items = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--) {
var stack = buf.readItem();
stack.setCount(buf.readVarInt());
this.items.add(stack);
}
this.craftables = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.craftables.add(buf.readItem());
this.currentlyCrafting = new ArrayList<>();
for (var i = buf.readVarInt(); i > 0; i--)
this.currentlyCrafting.add(buf.readItem());
}
@Override
public void write(FriendlyByteBuf buf) {
buf.writeVarInt(this.items.size());
for (var stack : this.items) {
var copy = stack.copy();
copy.setCount(1);
buf.writeItem(copy);
buf.writeVarInt(stack.getCount());
}
buf.writeVarInt(this.craftables.size());
for (var stack : this.craftables)
buf.writeItem(stack);
buf.writeVarInt(this.currentlyCrafting.size());
for (var stack : this.currentlyCrafting)
buf.writeItem(stack);
}
@Override
public ResourceLocation id() {
return PacketNetworkItems.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketNetworkItems message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
var mc = Minecraft.getInstance(); var mc = Minecraft.getInstance();
if (mc.screen instanceof ItemTerminalGui terminal) if (mc.screen instanceof ItemTerminalGui terminal)
terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting); terminal.updateItemList(message.items, message.craftables, message.currentlyCrafting);
} }
});
}
} }

View file

@ -4,39 +4,59 @@ import de.ellpeck.prettypipes.PrettyPipes;
import de.ellpeck.prettypipes.Utility; import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.network.RegistryFriendlyByteBuf; import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload; import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.handling.IPayloadContext; import net.neoforged.neoforge.network.handling.PlayPayloadContext;
public record PacketRequest(BlockPos pos, ItemStack stack, int componentsHash, int amount) implements CustomPacketPayload { public class PacketRequest implements CustomPacketPayload {
public static final Type<PacketRequest> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "request")); public static final ResourceLocation ID = new ResourceLocation(PrettyPipes.ID, "request");
public static final StreamCodec<RegistryFriendlyByteBuf, PacketRequest> CODEC = StreamCodec.composite(
BlockPos.STREAM_CODEC, PacketRequest::pos, private final BlockPos pos;
ItemStack.STREAM_CODEC, PacketRequest::stack, private final ItemStack stack;
ByteBufCodecs.INT, PacketRequest::componentsHash, private final int nbtHash;
ByteBufCodecs.INT, PacketRequest::amount, private final int amount;
PacketRequest::new);
public PacketRequest(BlockPos pos, ItemStack stack, int amount) { public PacketRequest(BlockPos pos, ItemStack stack, int amount) {
this(pos, stack, !stack.isComponentsPatchEmpty() ? stack.getComponents().hashCode() : 0, amount); this.pos = pos;
this.stack = stack;
this.nbtHash = stack.hasTag() ? stack.getTag().hashCode() : 0;
this.amount = amount;
}
public PacketRequest(FriendlyByteBuf buf) {
this.pos = buf.readBlockPos();
this.stack = buf.readItem();
this.nbtHash = buf.readVarInt();
this.amount = buf.readVarInt();
} }
@Override @Override
public Type<? extends CustomPacketPayload> type() { public void write(FriendlyByteBuf buf) {
return PacketRequest.TYPE; buf.writeBlockPos(this.pos);
buf.writeItem(this.stack);
buf.writeVarInt(this.nbtHash);
buf.writeVarInt(this.amount);
} }
public static void onMessage(PacketRequest message, IPayloadContext ctx) { @Override
var player = ctx.player(); public ResourceLocation id() {
return PacketRequest.ID;
}
@SuppressWarnings("Convert2Lambda")
public static void onMessage(PacketRequest message, PlayPayloadContext ctx) {
ctx.workHandler().execute(new Runnable() {
@Override
public void run() {
var player = ctx.player().orElseThrow();
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), message.pos); var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, player.level(), message.pos);
message.stack.setCount(message.amount); message.stack.setCount(message.amount);
tile.requestItem(player, message.stack, message.componentsHash); tile.requestItem(player, message.stack, message.nbtHash);
}
});
} }
} }

View file

@ -5,7 +5,6 @@ import de.ellpeck.prettypipes.network.NetworkEdge;
import de.ellpeck.prettypipes.network.PipeItem; import de.ellpeck.prettypipes.network.PipeItem;
import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -13,17 +12,17 @@ import net.minecraft.world.level.Level;
import net.neoforged.api.distmarker.Dist; import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn; import net.neoforged.api.distmarker.OnlyIn;
import net.neoforged.neoforge.common.util.INBTSerializable; import net.neoforged.neoforge.common.util.INBTSerializable;
import org.apache.commons.lang3.function.TriFunction;
import org.jgrapht.GraphPath; import org.jgrapht.GraphPath;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.function.BiFunction;
public interface IPipeItem extends INBTSerializable<CompoundTag> { public interface IPipeItem extends INBTSerializable<CompoundTag> {
Map<ResourceLocation, TriFunction<HolderLookup.Provider, ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>( Map<ResourceLocation, BiFunction<ResourceLocation, CompoundTag, IPipeItem>> TYPES = new HashMap<>(
Collections.singletonMap(PipeItem.TYPE, PipeItem::new)); Collections.singletonMap(PipeItem.TYPE, PipeItem::new));
ItemStack getContent(); ItemStack getContent();
@ -45,10 +44,9 @@ public interface IPipeItem extends INBTSerializable<CompoundTag> {
@OnlyIn(Dist.CLIENT) @OnlyIn(Dist.CLIENT)
void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay, MultiBufferSource source); void render(PipeBlockEntity tile, PoseStack matrixStack, Random random, float partialTicks, int light, int overlay, MultiBufferSource source);
static IPipeItem load(HolderLookup.Provider provider, CompoundTag nbt) { static IPipeItem load(CompoundTag nbt) {
var type = ResourceLocation.parse(nbt.getString("type")); var type = new ResourceLocation(nbt.getString("type"));
var func = IPipeItem.TYPES.get(type); var func = IPipeItem.TYPES.get(type);
return func != null ? func.apply(provider, type, nbt) : null; return func != null ? func.apply(type, nbt) : null;
} }
} }

View file

@ -10,7 +10,7 @@ import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.tags.FluidTags; import net.minecraft.tags.FluidTags;
import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionHand;
import net.minecraft.world.ItemInteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -77,12 +77,12 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
} }
@Override @Override
public ItemInteractionResult useItemOn(ItemStack pStack, BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) { public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos); var tile = Utility.getBlockEntity(PipeBlockEntity.class, worldIn, pos);
if (tile == null) if (tile == null)
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; return InteractionResult.PASS;
if (!tile.canHaveModules()) if (!tile.canHaveModules())
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; return InteractionResult.PASS;
var stack = player.getItemInHand(handIn); var stack = player.getItemInHand(handIn);
if (stack.getItem() instanceof IModule) { if (stack.getItem() instanceof IModule) {
var copy = stack.copy(); var copy = stack.copy();
@ -90,14 +90,14 @@ public class PipeBlock extends BaseEntityBlock implements SimpleWaterloggedBlock
var remain = ItemHandlerHelper.insertItem(tile.modules, copy, false); var remain = ItemHandlerHelper.insertItem(tile.modules, copy, false);
if (remain.isEmpty()) { if (remain.isEmpty()) {
stack.shrink(1); stack.shrink(1);
return ItemInteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
} else if (handIn == InteractionHand.MAIN_HAND && stack.isEmpty()) { } else if (handIn == InteractionHand.MAIN_HAND && stack.isEmpty()) {
if (!worldIn.isClientSide) if (!worldIn.isClientSide)
player.openMenu(tile, pos); player.openMenu(tile, pos);
return ItemInteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
return ItemInteractionResult.PASS_TO_DEFAULT_BLOCK_INTERACTION; return InteractionResult.PASS;
} }
@Override @Override

View file

@ -11,7 +11,6 @@ import de.ellpeck.prettypipes.pipe.containers.MainPipeContainer;
import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity; import de.ellpeck.prettypipes.pressurizer.PressurizerBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
@ -93,60 +92,60 @@ public class PipeBlockEntity extends BlockEntity implements MenuProvider, IPipeC
} }
@Override @Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) { public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound, provider); super.saveAdditional(compound);
compound.put("modules", this.modules.serializeNBT(provider)); compound.put("modules", this.modules.serializeNBT());
compound.putInt("module_drop_check", this.moduleDropCheck); compound.putInt("module_drop_check", this.moduleDropCheck);
compound.put("requests", Utility.serializeAll(provider, this.craftIngredientRequests)); compound.put("requests", Utility.serializeAll(this.craftIngredientRequests));
if (this.cover != null) if (this.cover != null)
compound.put("cover", NbtUtils.writeBlockState(this.cover)); compound.put("cover", NbtUtils.writeBlockState(this.cover));
var results = new ListTag(); var results = new ListTag();
for (var triple : this.craftResultRequests) { for (var triple : this.craftResultRequests) {
var nbt = new CompoundTag(); var nbt = new CompoundTag();
nbt.putLong("dest_pipe", triple.getLeft().asLong()); nbt.putLong("dest_pipe", triple.getLeft().asLong());
nbt.put("item", triple.getRight().save(provider)); nbt.put("item", triple.getRight().save(new CompoundTag()));
results.add(nbt); results.add(nbt);
} }
compound.put("craft_results", results); compound.put("craft_results", results);
} }
@Override @Override
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) { public void load(CompoundTag compound) {
this.modules.deserializeNBT(provider, compound.getCompound("modules")); this.modules.deserializeNBT(compound.getCompound("modules"));
this.moduleDropCheck = compound.getInt("module_drop_check"); this.moduleDropCheck = compound.getInt("module_drop_check");
this.cover = compound.contains("cover") ? NbtUtils.readBlockState(this.level != null ? this.level.holderLookup(Registries.BLOCK) : BuiltInRegistries.BLOCK.asLookup(), compound.getCompound("cover")) : null; this.cover = compound.contains("cover") ? NbtUtils.readBlockState(this.level != null ? this.level.holderLookup(Registries.BLOCK) : BuiltInRegistries.BLOCK.asLookup(), compound.getCompound("cover")) : null;
this.craftIngredientRequests.clear(); this.craftIngredientRequests.clear();
this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(provider, l))); this.craftIngredientRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new));
this.craftResultRequests.clear(); this.craftResultRequests.clear();
var results = compound.getList("craft_results", Tag.TAG_COMPOUND); var results = compound.getList("craft_results", Tag.TAG_COMPOUND);
for (var i = 0; i < results.size(); i++) { for (var i = 0; i < results.size(); i++) {
var nbt = results.getCompound(i); var nbt = results.getCompound(i);
this.craftResultRequests.add(Pair.of( this.craftResultRequests.add(Pair.of(
BlockPos.of(nbt.getLong("dest_pipe")), BlockPos.of(nbt.getLong("dest_pipe")),
ItemStack.parseOptional(provider, nbt.getCompound("item")))); ItemStack.of(nbt.getCompound("item"))));
} }
super.loadAdditional(compound, provider); super.load(compound);
} }
@Override @Override
public CompoundTag getUpdateTag(HolderLookup.Provider provider) { public CompoundTag getUpdateTag() {
// sync pipe items on load // sync pipe items on load
var nbt = this.saveWithoutMetadata(provider); var nbt = this.saveWithoutMetadata();
nbt.put("items", Utility.serializeAll(provider, this.getItems())); nbt.put("items", Utility.serializeAll(this.getItems()));
return nbt; return nbt;
} }
@Override @Override
public void handleUpdateTag(CompoundTag nbt, HolderLookup.Provider provider) { public void handleUpdateTag(CompoundTag nbt) {
this.loadWithComponents(nbt, provider); this.load(nbt);
var items = this.getItems(); var items = this.getItems();
items.clear(); items.clear();
items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), d -> IPipeItem.load(provider, d))); items.addAll(Utility.deserializeAll(nbt.getList("items", Tag.TAG_COMPOUND), IPipeItem::load));
} }
@Override @Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) { public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.loadWithComponents(pkt.getTag(), provider); this.load(pkt.getTag());
} }
public List<IPipeItem> getItems() { public List<IPipeItem> getItems() {

View file

@ -20,7 +20,7 @@ import java.util.List;
public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extends AbstractContainerScreen<T> { public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extends AbstractContainerScreen<T> {
protected static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/pipe.png"); protected static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pipe.png");
private final List<Tab> tabs = new ArrayList<>(); private final List<Tab> tabs = new ArrayList<>();
private final ItemStack[] lastItems = new ItemStack[this.menu.tile.modules.getSlots()]; private final ItemStack[] lastItems = new ItemStack[this.menu.tile.modules.getSlots()];
@ -144,7 +144,7 @@ public abstract class AbstractPipeGui<T extends AbstractPipeContainer<?>> extend
return false; return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32) if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 28 || mouseY >= this.y + 32)
return false; return false;
PacketDistributor.sendToServer(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, List.of(this.index))); PacketDistributor.SERVER.noArg().send(new PacketButton(AbstractPipeGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.PIPE_TAB, this.index));
AbstractPipeGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1)); AbstractPipeGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true; return true;
} }

View file

@ -11,7 +11,7 @@ public class HighPriorityModuleItem extends ModuleItem {
private final int priority; private final int priority;
public HighPriorityModuleItem(String name, ModuleTier tier) { public HighPriorityModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.priority = tier.forTier(50, 100, 200); this.priority = tier.forTier(50, 100, 200);
} }

View file

@ -11,7 +11,7 @@ public class LowPriorityModuleItem extends ModuleItem {
private final int priority; private final int priority;
public LowPriorityModuleItem(String name, ModuleTier tier) { public LowPriorityModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.priority = tier.forTier(-50, -100, -200); this.priority = tier.forTier(-50, -100, -200);
} }

View file

@ -8,7 +8,7 @@ import net.minecraft.world.item.ItemStack;
public class RedstoneModuleItem extends ModuleItem { public class RedstoneModuleItem extends ModuleItem {
public RedstoneModuleItem() { public RedstoneModuleItem() {
super("redstone_module", new Properties()); super("redstone_module");
} }
@Override @Override
@ -25,5 +25,4 @@ public class RedstoneModuleItem extends ModuleItem {
public boolean hasContainer(ItemStack module, PipeBlockEntity tile) { public boolean hasContainer(ItemStack module, PipeBlockEntity tile) {
return false; return false;
} }
} }

View file

@ -1,12 +1,9 @@
package de.ellpeck.prettypipes.pipe.modules; package de.ellpeck.prettypipes.pipe.modules;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import java.util.List; import java.util.List;
@ -16,7 +13,7 @@ public class SortingModuleItem extends ModuleItem {
private final Type type; private final Type type;
public SortingModuleItem(String name, Type type) { public SortingModuleItem(String name, Type type) {
super(name, new Properties()); super(name);
this.type = type; this.type = type;
} }
@ -35,9 +32,8 @@ public class SortingModuleItem extends ModuleItem {
switch (this.type) { switch (this.type) {
case ROUND_ROBIN: case ROUND_ROBIN:
// store an ever-increasing index and choose destinations based on that // store an ever-increasing index and choose destinations based on that
var prevData = module.get(Data.TYPE); var next = module.hasTag() ? module.getTag().getInt("last") + 1 : 0;
var next = prevData != null ? prevData.last + 1 : 0; module.getOrCreateTag().putInt("last", next);
module.set(Data.TYPE, new Data(next));
return next % nodes.size(); return next % nodes.size();
case RANDOM: case RANDOM:
return tile.getLevel().random.nextInt(nodes.size()); return tile.getLevel().random.nextInt(nodes.size());
@ -49,12 +45,4 @@ public class SortingModuleItem extends ModuleItem {
ROUND_ROBIN, ROUND_ROBIN,
RANDOM RANDOM
} }
public record Data(int last) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(Codec.INT.fieldOf("last").forGetter(f -> f.last)).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
} }

View file

@ -11,7 +11,7 @@ public class SpeedModuleItem extends ModuleItem {
private final float speedIncrease; private final float speedIncrease;
public SpeedModuleItem(String name, ModuleTier tier) { public SpeedModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.speedIncrease = tier.forTier(0.05F, 0.1F, 0.2F); this.speedIncrease = tier.forTier(0.05F, 0.1F, 0.2F);
} }
@ -29,5 +29,4 @@ public class SpeedModuleItem extends ModuleItem {
public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) { public float getItemSpeedIncrease(ItemStack module, PipeBlockEntity tile) {
return this.speedIncrease; return this.speedIncrease;
} }
} }

View file

@ -19,10 +19,9 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
@Override @Override
protected void addSlots() { protected void addSlots() {
var contents = this.moduleStack.get(CraftingModuleItem.Contents.TYPE); this.input = this.module.getInput(this.moduleStack);
this.input = contents.input();
for (var i = 0; i < this.input.getSlots(); i++) { for (var i = 0; i < this.input.getSlots(); i++) {
this.addSlot(new FilterSlot(this.input, i, (176 - this.input.getSlots() * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) { this.addSlot(new FilterSlot(this.input, i, (176 - this.module.inputSlots * 18) / 2 + 1 + i % 9 * 18, 17 + 32 + i / 9 * 18, false) {
@Override @Override
public void setChanged() { public void setChanged() {
super.setChanged(); super.setChanged();
@ -32,9 +31,9 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
}); });
} }
this.output = contents.output(); this.output = this.module.getOutput(this.moduleStack);
for (var i = 0; i < this.output.getSlots(); i++) { for (var i = 0; i < this.output.getSlots(); i++) {
this.addSlot(new FilterSlot(this.output, i, (176 - this.output.getSlots() * 18) / 2 + 1 + i % 9 * 18, 85 + i / 9 * 18, false) { this.addSlot(new FilterSlot(this.output, i, (176 - this.module.outputSlots * 18) / 2 + 1 + i % 9 * 18, 85 + i / 9 * 18, false) {
@Override @Override
public void setChanged() { public void setChanged() {
super.setChanged(); super.setChanged();
@ -48,7 +47,6 @@ public class CraftingModuleContainer extends AbstractPipeContainer<CraftingModul
public void removed(Player playerIn) { public void removed(Player playerIn) {
super.removed(playerIn); super.removed(playerIn);
if (this.modified) if (this.modified)
this.moduleStack.set(CraftingModuleItem.Contents.TYPE, new CraftingModuleItem.Contents(this.input, this.output)); this.module.save(this.input, this.output, this.moduleStack);
} }
} }

View file

@ -1,9 +1,6 @@
package de.ellpeck.prettypipes.pipe.modules.craft; package de.ellpeck.prettypipes.pipe.modules.craft;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.Utility;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.items.ModuleTier; import de.ellpeck.prettypipes.items.ModuleTier;
@ -17,7 +14,6 @@ import de.ellpeck.prettypipes.terminal.CraftingTerminalBlockEntity;
import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity; import de.ellpeck.prettypipes.terminal.ItemTerminalBlockEntity;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
@ -33,10 +29,14 @@ import java.util.function.Consumer;
public class CraftingModuleItem extends ModuleItem { public class CraftingModuleItem extends ModuleItem {
public final int inputSlots;
public final int outputSlots;
private final int speed; private final int speed;
public CraftingModuleItem(String name, ModuleTier tier) { public CraftingModuleItem(String name, ModuleTier tier) {
super(name, new Properties().component(Contents.TYPE, new Contents(new ItemStackHandler(tier.forTier(1, 4, 9)), new ItemStackHandler(tier.forTier(1, 2, 4))))); super(name);
this.inputSlots = tier.forTier(1, 4, 9);
this.outputSlots = tier.forTier(1, 2, 4);
this.speed = tier.forTier(20, 10, 5); this.speed = tier.forTier(20, 10, 5);
} }
@ -127,7 +127,7 @@ public class CraftingModuleItem extends ModuleItem {
@Override @Override
public List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile) { public List<ItemStack> getAllCraftables(ItemStack module, PipeBlockEntity tile) {
List<ItemStack> ret = new ArrayList<>(); List<ItemStack> ret = new ArrayList<>();
var output = module.get(Contents.TYPE).output; var output = this.getOutput(module);
for (var i = 0; i < output.getSlots(); i++) { for (var i = 0; i < output.getSlots(); i++) {
var stack = output.getStackInSlot(i); var stack = output.getStackInSlot(i);
if (!stack.isEmpty()) if (!stack.isEmpty())
@ -141,14 +141,15 @@ public class CraftingModuleItem extends ModuleItem {
var network = PipeNetwork.get(tile.getLevel()); var network = PipeNetwork.get(tile.getLevel());
var items = network.getOrderedNetworkItems(tile.getBlockPos()); var items = network.getOrderedNetworkItems(tile.getBlockPos());
var equalityTypes = ItemFilter.getEqualityTypes(tile); var equalityTypes = ItemFilter.getEqualityTypes(tile);
var content = module.get(Contents.TYPE); var input = this.getInput(module);
var craftable = 0; var craftable = 0;
for (var i = 0; i < content.output.getSlots(); i++) { var output = this.getOutput(module);
var out = content.output.getStackInSlot(i); for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i);
if (!out.isEmpty() && ItemEquality.compareItems(out, stack, equalityTypes)) { if (!out.isEmpty() && ItemEquality.compareItems(out, stack, equalityTypes)) {
// figure out how many crafting operations we can actually do with the input items we have in the network // figure out how many crafting operations we can actually do with the input items we have in the network
var availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, content.input.getSlots(), content.input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes); var availableCrafts = CraftingTerminalBlockEntity.getAvailableCrafts(tile, input.getSlots(), input::getStackInSlot, k -> true, s -> items, unavailableConsumer, CraftingModuleItem.addDependency(dependencyChain, module), equalityTypes);
if (availableCrafts > 0) if (availableCrafts > 0)
craftable += out.getCount() * availableCrafts; craftable += out.getCount() * availableCrafts;
} }
@ -173,7 +174,7 @@ public class CraftingModuleItem extends ModuleItem {
var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount); var craftableCrafts = Mth.ceil(craftableAmount / (float) resultAmount);
var toCraft = Math.min(craftableCrafts, requiredCrafts); var toCraft = Math.min(craftableCrafts, requiredCrafts);
var input = module.get(Contents.TYPE).input; var input = this.getInput(module);
for (var i = 0; i < input.getSlots(); i++) { for (var i = 0; i < input.getSlots(); i++) {
var in = input.getStackInSlot(i); var in = input.getStackInSlot(i);
if (in.isEmpty()) if (in.isEmpty())
@ -194,8 +195,30 @@ public class CraftingModuleItem extends ModuleItem {
return remain; return remain;
} }
public ItemStackHandler getInput(ItemStack module) {
var handler = new ItemStackHandler(this.inputSlots);
if (module.hasTag())
handler.deserializeNBT(module.getTag().getCompound("input"));
return handler;
}
public ItemStackHandler getOutput(ItemStack module) {
var handler = new ItemStackHandler(this.outputSlots);
if (module.hasTag())
handler.deserializeNBT(module.getTag().getCompound("output"));
return handler;
}
public void save(ItemStackHandler input, ItemStackHandler output, ItemStack module) {
var tag = module.getOrCreateTag();
if (input != null)
tag.put("input", input.serializeNBT());
if (output != null)
tag.put("output", output.serializeNBT());
}
private int getResultAmountPerCraft(ItemStack module, ItemStack stack, ItemEquality... equalityTypes) { private int getResultAmountPerCraft(ItemStack module, ItemStack stack, ItemEquality... equalityTypes) {
var output = module.get(Contents.TYPE).output; var output = this.getOutput(module);
var resultAmount = 0; var resultAmount = 0;
for (var i = 0; i < output.getSlots(); i++) { for (var i = 0; i < output.getSlots(); i++) {
var out = output.getStackInSlot(i); var out = output.getStackInSlot(i);
@ -210,15 +233,4 @@ public class CraftingModuleItem extends ModuleItem {
deps.push(module); deps.push(module);
return deps; return deps;
} }
public record Contents(ItemStackHandler input, ItemStackHandler output) {
public static final Codec<Contents> CODEC = RecordCodecBuilder.create(i -> i.group(
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("input").forGetter(d -> d.input),
Utility.ITEM_STACK_HANDLER_CODEC.fieldOf("output").forGetter(d -> d.output)
).apply(i, Contents::new));
public static final DataComponentType<Contents> TYPE = DataComponentType.<Contents>builder().persistent(Contents.CODEC).cacheEncoding().build();
}
} }

View file

@ -23,7 +23,7 @@ public class ExtractionModuleItem extends ModuleItem {
public final int filterSlots; public final int filterSlots;
public ExtractionModuleItem(String name, ModuleTier tier) { public ExtractionModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.maxExtraction = tier.forTier(1, 8, 64); this.maxExtraction = tier.forTier(1, 8, 64);
this.speed = tier.forTier(20, 15, 10); this.speed = tier.forTier(20, 15, 10);
this.filterSlots = tier.forTier(3, 6, 9); this.filterSlots = tier.forTier(3, 6, 9);

View file

@ -13,7 +13,7 @@ import net.minecraft.world.item.ItemStack;
public class FilterIncreaseModuleItem extends ModuleItem { public class FilterIncreaseModuleItem extends ModuleItem {
public FilterIncreaseModuleItem() { public FilterIncreaseModuleItem() {
super("filter_increase_modifier", new Properties()); super("filter_increase_modifier");
} }
@Override @Override

View file

@ -14,7 +14,7 @@ public class FilterModuleGui extends AbstractPipeGui<FilterModuleContainer> {
@Override @Override
protected void init() { protected void init() {
super.init(); super.init();
var buttonsY = this.topPos + 17 + 32 + 18 * Mth.ceil(this.menu.filter.content.getSlots() / 9F) + 2; var buttonsY = this.topPos + 17 + 32 + 18 * Mth.ceil(this.menu.filter.getSlots() / 9F) + 2;
for (var widget : this.menu.filter.getButtons(this, this.leftPos + this.imageWidth - 7, buttonsY, true)) for (var widget : this.menu.filter.getButtons(this, this.leftPos + this.imageWidth - 7, buttonsY, true))
this.addRenderableWidget(widget); this.addRenderableWidget(widget);
this.addRenderableWidget(this.menu.directionSelector.getButton(this.leftPos + 7, buttonsY)); this.addRenderableWidget(this.menu.directionSelector.getButton(this.leftPos + 7, buttonsY));

View file

@ -20,7 +20,7 @@ public class FilterModuleItem extends ModuleItem {
private final boolean canPopulateFromInventories; private final boolean canPopulateFromInventories;
public FilterModuleItem(String name, ModuleTier tier) { public FilterModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.filterSlots = tier.forTier(5, 9, 18); this.filterSlots = tier.forTier(5, 9, 18);
this.canPopulateFromInventories = tier.forTier(false, false, true); this.canPopulateFromInventories = tier.forTier(false, false, true);
} }

View file

@ -21,8 +21,8 @@ public class FilterModifierModuleContainer extends AbstractPipeContainer<FilterM
public List<ResourceLocation> getTags() { public List<ResourceLocation> getTags() {
Set<ResourceLocation> unsortedTags = new HashSet<>(); Set<ResourceLocation> unsortedTags = new HashSet<>();
for (var filter : this.tile.getFilters(null)) { for (var filter : this.tile.getFilters(null)) {
for (var i = 0; i < filter.content.getSlots(); i++) { for (var i = 0; i < filter.getSlots(); i++) {
var stack = filter.content.getStackInSlot(i); var stack = filter.getStackInSlot(i);
stack.getTags().forEach(t -> unsortedTags.add(t.location())); stack.getTags().forEach(t -> unsortedTags.add(t.location()));
} }
} }

View file

@ -134,7 +134,7 @@ public class FilterModifierModuleGui extends AbstractPipeGui<FilterModifierModul
return false; return false;
if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 140 || mouseY >= this.y + 12) if (mouseX < this.x || mouseY < this.y || mouseX >= this.x + 140 || mouseY >= this.y + 12)
return false; return false;
PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, List.of(FilterModifierModuleGui.this.tags.indexOf(this.tag))); PacketButton.sendAndExecute(FilterModifierModuleGui.this.menu.tile.getBlockPos(), PacketButton.ButtonResult.TAG_FILTER, FilterModifierModuleGui.this.tags.indexOf(this.tag));
FilterModifierModuleGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1)); FilterModifierModuleGui.this.getMinecraft().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1));
return true; return true;
} }

View file

@ -1,14 +1,12 @@
package de.ellpeck.prettypipes.pipe.modules.modifier; package de.ellpeck.prettypipes.pipe.modules.modifier;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
import de.ellpeck.prettypipes.misc.ItemEquality; import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.core.component.DataComponentType; import joptsimple.internal.Strings;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
@ -19,7 +17,7 @@ public class FilterModifierModuleItem extends ModuleItem {
public final ItemEquality.Type type; public final ItemEquality.Type type;
public FilterModifierModuleItem(String name, ItemEquality.Type type) { public FilterModifierModuleItem(String name, ItemEquality.Type type) {
super(name, new Properties()); super(name);
this.type = type; this.type = type;
} }
@ -47,21 +45,15 @@ public class FilterModifierModuleItem extends ModuleItem {
} }
public static ResourceLocation getFilterTag(ItemStack stack) { public static ResourceLocation getFilterTag(ItemStack stack) {
var data = stack.get(Data.TYPE); if (!stack.hasTag())
return data != null && data.filterTag != null ? ResourceLocation.parse(data.filterTag) : null; return null;
var tag = stack.getTag().getString("filter_tag");
if (Strings.isNullOrEmpty(tag))
return null;
return new ResourceLocation(tag);
} }
public static void setFilterTag(ItemStack stack, ResourceLocation tag) { public static void setFilterTag(ItemStack stack, ResourceLocation tag) {
stack.set(Data.TYPE, new Data(tag.toString())); stack.getOrCreateTag().putString("filter_tag", tag.toString());
} }
public record Data(String filterTag) {
public static final Codec<Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.STRING.fieldOf("filter_tag").forGetter(f -> f.filterTag)
).apply(i, Data::new));
public static final DataComponentType<Data> TYPE = DataComponentType.<Data>builder().persistent(Data.CODEC).cacheEncoding().build();
}
} }

View file

@ -25,7 +25,7 @@ public class RetrievalModuleItem extends ModuleItem {
public final int filterSlots; public final int filterSlots;
public RetrievalModuleItem(String name, ModuleTier tier) { public RetrievalModuleItem(String name, ModuleTier tier) {
super(name, new Properties()); super(name);
this.maxExtraction = tier.forTier(1, 8, 16); this.maxExtraction = tier.forTier(1, 8, 16);
this.speed = tier.forTier(40, 20, 10); this.speed = tier.forTier(40, 20, 10);
this.filterSlots = tier.forTier(3, 6, 9); this.filterSlots = tier.forTier(3, 6, 9);
@ -41,8 +41,8 @@ public class RetrievalModuleItem extends ModuleItem {
var equalityTypes = ItemFilter.getEqualityTypes(tile); var equalityTypes = ItemFilter.getEqualityTypes(tile);
// loop through filters to see which items to pull // loop through filters to see which items to pull
Arrays.stream(directions).flatMap(d -> tile.getFilters(d).stream()).distinct().forEach(f -> { Arrays.stream(directions).flatMap(d -> tile.getFilters(d).stream()).distinct().forEach(f -> {
for (var i = 0; i < f.content.getSlots(); i++) { for (var i = 0; i < f.getSlots(); i++) {
var filtered = f.content.getStackInSlot(i); var filtered = f.getStackInSlot(i);
if (filtered.isEmpty()) if (filtered.isEmpty())
continue; continue;
var copy = filtered.copy(); var copy = filtered.copy();

View file

@ -11,7 +11,6 @@ import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import java.util.List;
import java.util.function.Supplier; import java.util.function.Supplier;
public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer> { public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer> {
@ -35,18 +34,17 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
} }
}); });
var data = this.menu.moduleStack.getOrDefault(StackSizeModuleItem.Data.TYPE, StackSizeModuleItem.Data.DEFAULT); textField.setValue(String.valueOf(StackSizeModuleItem.getMaxStackSizeForModule(this.menu.moduleStack)));
textField.setValue(String.valueOf(data.maxStackSize()));
textField.setMaxLength(4); textField.setMaxLength(4);
textField.setResponder(s -> { textField.setResponder(s -> {
if (s.isEmpty()) if (s.isEmpty())
return; return;
var amount = Integer.parseInt(s); var amount = Integer.parseInt(s);
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, List.of(amount)); PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_AMOUNT, amount);
}); });
Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (data.limitToMaxStackSize() ? "on" : "off")); Supplier<Component> buttonText = () -> Component.translatable("info." + PrettyPipes.ID + ".limit_to_max_" + (StackSizeModuleItem.getLimitToMaxStackSize(this.menu.moduleStack) ? "on" : "off"));
this.addRenderableWidget(Button.builder(buttonText.get(), b -> { this.addRenderableWidget(Button.builder(buttonText.get(), b -> {
PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON, List.of()); PacketButton.sendAndExecute(this.menu.tile.getBlockPos(), ButtonResult.STACK_SIZE_MODULE_BUTTON);
b.setMessage(buttonText.get()); b.setMessage(buttonText.get());
}).bounds(this.leftPos + 7, this.topPos + 17 + 32 + 10 + 22, 120, 20).build()); }).bounds(this.leftPos + 7, this.topPos + 17 + 32 + 10 + 22, 120, 20).build());
} }
@ -57,5 +55,4 @@ public class StackSizeModuleGui extends AbstractPipeGui<StackSizeModuleContainer
graphics.drawString(this.font, I18n.get("info." + PrettyPipes.ID + ".max_stack_size") + ":", 7, 17 + 32, 4210752, false); graphics.drawString(this.font, I18n.get("info." + PrettyPipes.ID + ".max_stack_size") + ":", 7, 17 + 32, 4210752, false);
} }
} }

View file

@ -1,7 +1,5 @@
package de.ellpeck.prettypipes.pipe.modules.stacksize; package de.ellpeck.prettypipes.pipe.modules.stacksize;
import com.mojang.serialization.Codec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import de.ellpeck.prettypipes.Registry; import de.ellpeck.prettypipes.Registry;
import de.ellpeck.prettypipes.items.IModule; import de.ellpeck.prettypipes.items.IModule;
import de.ellpeck.prettypipes.items.ModuleItem; import de.ellpeck.prettypipes.items.ModuleItem;
@ -9,7 +7,6 @@ import de.ellpeck.prettypipes.misc.ItemEquality;
import de.ellpeck.prettypipes.misc.ItemFilter; import de.ellpeck.prettypipes.misc.ItemFilter;
import de.ellpeck.prettypipes.pipe.PipeBlockEntity; import de.ellpeck.prettypipes.pipe.PipeBlockEntity;
import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer; import de.ellpeck.prettypipes.pipe.containers.AbstractPipeContainer;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
@ -18,15 +15,37 @@ import net.neoforged.neoforge.items.IItemHandler;
public class StackSizeModuleItem extends ModuleItem { public class StackSizeModuleItem extends ModuleItem {
public StackSizeModuleItem() { public StackSizeModuleItem() {
super("stack_size_module", new Properties()); super("stack_size_module");
}
public static int getMaxStackSizeForModule(ItemStack module) {
if (module.hasTag()) {
var amount = module.getTag().getInt("max_stack_size");
if (amount > 0)
return amount;
}
return 64;
}
public static void setMaxStackSize(ItemStack module, int amount) {
module.getOrCreateTag().putInt("max_stack_size", amount);
}
public static boolean getLimitToMaxStackSize(ItemStack module) {
if (module.hasTag())
return module.getTag().getBoolean("limit_to_max_stack_size");
return false;
}
public static void setLimitToMaxStackSize(ItemStack module, boolean yes) {
module.getOrCreateTag().putBoolean("limit_to_max_stack_size", yes);
} }
@Override @Override
public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) { public int getMaxInsertionAmount(ItemStack module, PipeBlockEntity tile, ItemStack stack, IItemHandler destination) {
var types = ItemFilter.getEqualityTypes(tile); var types = ItemFilter.getEqualityTypes(tile);
var data = module.getOrDefault(Data.TYPE, Data.DEFAULT); var max = StackSizeModuleItem.getMaxStackSizeForModule(module);
var max = data.maxStackSize; if (StackSizeModuleItem.getLimitToMaxStackSize(module))
if (data.limitToMaxStackSize)
max = Math.min(max, stack.getMaxStackSize()); max = Math.min(max, stack.getMaxStackSize());
var amount = 0; var amount = 0;
for (var i = 0; i < destination.getSlots(); i++) { for (var i = 0; i < destination.getSlots(); i++) {
@ -57,16 +76,4 @@ public class StackSizeModuleItem extends ModuleItem {
return new StackSizeModuleContainer(Registry.stackSizeModuleContainer, windowId, player, tile.getBlockPos(), moduleIndex); return new StackSizeModuleContainer(Registry.stackSizeModuleContainer, windowId, player, tile.getBlockPos(), moduleIndex);
} }
public record Data(int maxStackSize, boolean limitToMaxStackSize) {
public static final Data DEFAULT = new Data(64, false);
public static final Codec<StackSizeModuleItem.Data> CODEC = RecordCodecBuilder.create(i -> i.group(
Codec.INT.fieldOf("max_stack_size").forGetter(f -> f.maxStackSize),
Codec.BOOL.fieldOf("limit_to_max_stack_size").forGetter(f -> f.limitToMaxStackSize)
).apply(i, StackSizeModuleItem.Data::new));
public static final DataComponentType<StackSizeModuleItem.Data> TYPE = DataComponentType.<StackSizeModuleItem.Data>builder().persistent(StackSizeModuleItem.Data.CODEC).cacheEncoding().build();
}
} }

View file

@ -6,11 +6,12 @@ import de.ellpeck.prettypipes.Utility;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
@ -21,6 +22,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
public class PressurizerBlock extends BaseEntityBlock { public class PressurizerBlock extends BaseEntityBlock {
@ -37,7 +39,7 @@ public class PressurizerBlock extends BaseEntityBlock {
} }
@Override @Override
public InteractionResult useWithoutItem(BlockState state, Level worldIn, BlockPos pos, Player player, BlockHitResult result) { public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(PressurizerBlockEntity.class, worldIn, pos); var tile = Utility.getBlockEntity(PressurizerBlockEntity.class, worldIn, pos);
if (tile == null) if (tile == null)
return InteractionResult.PASS; return InteractionResult.PASS;
@ -58,8 +60,8 @@ public class PressurizerBlock extends BaseEntityBlock {
} }
@Override @Override
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) { public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents); Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
} }
@org.jetbrains.annotations.Nullable @org.jetbrains.annotations.Nullable

View file

@ -8,7 +8,6 @@ import de.ellpeck.prettypipes.pipe.ConnectionType;
import de.ellpeck.prettypipes.pipe.IPipeConnectable; import de.ellpeck.prettypipes.pipe.IPipeConnectable;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.Connection; import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@ -52,30 +51,30 @@ public class PressurizerBlockEntity extends BlockEntity implements MenuProvider,
} }
@Override @Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) { public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound, provider); super.saveAdditional(compound);
compound.putInt("energy", this.getEnergy()); compound.putInt("energy", this.getEnergy());
} }
@Override @Override
public void loadAdditional(CompoundTag nbt, HolderLookup.Provider provider) { public void load(CompoundTag nbt) {
this.storage.setEnergyStored(nbt.getInt("energy")); this.storage.setEnergyStored(nbt.getInt("energy"));
super.loadAdditional(nbt, provider); super.load(nbt);
} }
@Override @Override
public CompoundTag getUpdateTag(HolderLookup.Provider provider) { public CompoundTag getUpdateTag() {
return this.saveWithoutMetadata(provider); return this.saveWithoutMetadata();
} }
@Override @Override
public void handleUpdateTag(CompoundTag tag, HolderLookup.Provider provider) { public void handleUpdateTag(CompoundTag tag) {
this.loadWithComponents(tag, provider); this.load(tag);
} }
@Override @Override
public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt, HolderLookup.Provider provider) { public void onDataPacket(Connection net, ClientboundBlockEntityDataPacket pkt) {
this.loadWithComponents(pkt.getTag(), provider); this.load(pkt.getTag());
} }
@Override @Override

View file

@ -9,7 +9,7 @@ import net.minecraft.world.entity.player.Inventory;
public class PressurizerGui extends AbstractContainerScreen<PressurizerContainer> { public class PressurizerGui extends AbstractContainerScreen<PressurizerContainer> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/pressurizer.png"); private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/pressurizer.png");
public PressurizerGui(PressurizerContainer screenContainer, Inventory inv, Component titleIn) { public PressurizerGui(PressurizerContainer screenContainer, Inventory inv, Component titleIn) {
super(screenContainer, inv, titleIn); super(screenContainer, inv, titleIn);

View file

@ -13,16 +13,13 @@ import de.ellpeck.prettypipes.terminal.containers.CraftingTerminalContainer;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style; import net.minecraft.network.chat.Style;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ChunkPos;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.neoforged.neoforge.items.ItemHandlerHelper; import net.neoforged.neoforge.items.ItemHandlerHelper;
import net.neoforged.neoforge.items.ItemStackHandler; import net.neoforged.neoforge.items.ItemStackHandler;
@ -100,8 +97,8 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
if (!this.level.isClientSide) { if (!this.level.isClientSide) {
List<PacketGhostSlot.Entry> clients = new ArrayList<>(); List<PacketGhostSlot.Entry> clients = new ArrayList<>();
for (var i = 0; i < this.ghostItems.getSlots(); i++) for (var i = 0; i < this.ghostItems.getSlots(); i++)
clients.add(PacketGhostSlot.Entry.fromStacks(this.level, List.of(this.ghostItems.getStackInSlot(i)))); clients.add(new PacketGhostSlot.Entry(this.level, Collections.singletonList(this.ghostItems.getStackInSlot(i))));
PacketDistributor.sendToPlayersTrackingChunk((ServerLevel) this.level, new ChunkPos(this.getBlockPos()), new PacketGhostSlot(this.getBlockPos(), clients)); PacketDistributor.TRACKING_CHUNK.with(this.level.getChunkAt(this.getBlockPos())).send(new PacketGhostSlot(this.getBlockPos(), clients));
} }
} }
@ -113,7 +110,7 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
network.startProfile("terminal_request_crafting"); network.startProfile("terminal_request_crafting");
this.updateItems(); this.updateItems();
// get the amount of crafts that we can do // get the amount of crafts that we can do
var lowestAvailable = CraftingTerminalBlockEntity.getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> this.getRequestedCraftItem(i).copyWithCount(1), this::isGhostItem, s -> { var lowestAvailable = CraftingTerminalBlockEntity.getAvailableCrafts(pipe, this.craftItems.getSlots(), i -> ItemHandlerHelper.copyStackWithSize(this.getRequestedCraftItem(i), 1), this::isGhostItem, s -> {
var item = this.networkItems.get(s); var item = this.networkItems.get(s);
return item != null ? item.getLocations() : Collections.emptyList(); return item != null ? item.getLocations() : Collections.emptyList();
}, ItemTerminalBlockEntity.onItemUnavailable(player, force), new Stack<>(), ItemEquality.NBT); }, ItemTerminalBlockEntity.onItemUnavailable(player, force), new Stack<>(), ItemEquality.NBT);
@ -140,15 +137,15 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
} }
@Override @Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider provider) { public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound, provider); super.saveAdditional(compound);
compound.put("craft_items", this.craftItems.serializeNBT(provider)); compound.put("craft_items", this.craftItems.serializeNBT());
} }
@Override @Override
public void loadAdditional(CompoundTag compound, HolderLookup.Provider provider) { public void load(CompoundTag compound) {
this.craftItems.deserializeNBT(provider, compound.getCompound("craft_items")); this.craftItems.deserializeNBT(compound.getCompound("craft_items"));
super.loadAdditional(compound, provider); super.load(compound);
} }
@Override @Override
@ -173,7 +170,7 @@ public class CraftingTerminalBlockEntity extends ItemTerminalBlockEntity {
for (var i = 0; i < tile.craftItems.getSlots(); i++) { for (var i = 0; i < tile.craftItems.getSlots(); i++) {
var stack = tile.getRequestedCraftItem(i); var stack = tile.getRequestedCraftItem(i);
var count = tile.isGhostItem(i) ? 0 : stack.getCount(); var count = tile.isGhostItem(i) ? 0 : stack.getCount();
if (!ItemStack.isSameItemSameComponents(stack, remain)) if (!ItemHandlerHelper.canItemStacksStack(stack, remain))
continue; continue;
// ensure that a single non-stackable item can still enter a ghost slot // ensure that a single non-stackable item can still enter a ghost slot
if (!stack.isStackable() && count >= 1) if (!stack.isStackable() && count >= 1)

View file

@ -7,11 +7,12 @@ import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level; import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.BaseEntityBlock; import net.minecraft.world.level.block.BaseEntityBlock;
import net.minecraft.world.level.block.RenderShape; import net.minecraft.world.level.block.RenderShape;
@ -22,6 +23,7 @@ import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.BlockHitResult;
import javax.annotation.Nullable;
import java.util.List; import java.util.List;
public class ItemTerminalBlock extends BaseEntityBlock { public class ItemTerminalBlock extends BaseEntityBlock {
@ -38,19 +40,19 @@ public class ItemTerminalBlock extends BaseEntityBlock {
} }
@Override @Override
protected InteractionResult useWithoutItem(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, BlockHitResult pHitResult) { public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult result) {
var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, pLevel, pPos); var tile = Utility.getBlockEntity(ItemTerminalBlockEntity.class, worldIn, pos);
if (tile == null) if (tile == null)
return InteractionResult.PASS; return InteractionResult.PASS;
var reason = tile.getInvalidTerminalReason(); var reason = tile.getInvalidTerminalReason();
if (reason != null) { if (reason != null) {
if (!pLevel.isClientSide) if (!worldIn.isClientSide)
pPlayer.sendSystemMessage(Component.translatable(reason).withStyle(ChatFormatting.RED)); player.sendSystemMessage(Component.translatable(reason).withStyle(ChatFormatting.RED));
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
if (!pLevel.isClientSide) { if (!worldIn.isClientSide) {
pPlayer.openMenu(tile, pPos); player.openMenu(tile, pos);
tile.updateItems(pPlayer); tile.updateItems(player);
} }
return InteractionResult.SUCCESS; return InteractionResult.SUCCESS;
} }
@ -77,8 +79,8 @@ public class ItemTerminalBlock extends BaseEntityBlock {
} }
@Override @Override
public void appendHoverText(ItemStack pStack, Item.TooltipContext pContext, List<Component> pTooltipComponents, TooltipFlag pTooltipFlag) { public void appendHoverText(ItemStack stack, @Nullable BlockGetter worldIn, List<Component> tooltip, TooltipFlag flagIn) {
Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), pTooltipComponents); Utility.addTooltip(BuiltInRegistries.BLOCK.getKey(this).getPath(), tooltip);
} }
@org.jetbrains.annotations.Nullable @org.jetbrains.annotations.Nullable

View file

@ -17,7 +17,6 @@ import de.ellpeck.prettypipes.terminal.containers.ItemTerminalContainer;
import net.minecraft.ChatFormatting; import net.minecraft.ChatFormatting;
import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction; import net.minecraft.core.Direction;
import net.minecraft.core.HolderLookup;
import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.Tag; import net.minecraft.nbt.Tag;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
@ -147,16 +146,16 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
} }
} }
public void requestItem(Player player, ItemStack stack, int componentsHash) { public void requestItem(Player player, ItemStack stack, int nbtHash) {
var network = PipeNetwork.get(this.level); var network = PipeNetwork.get(this.level);
network.startProfile("terminal_request_item"); network.startProfile("terminal_request_item");
this.updateItems(); this.updateItems();
if (componentsHash != 0) { if (nbtHash != 0) {
var filter = stack; var filter = stack;
stack = this.networkItems.values().stream() stack = this.networkItems.values().stream()
.map(NetworkItem::asStack) .map(NetworkItem::asStack)
// don't compare with nbt equality here or the data hashing thing is pointless // don't compare with nbt equality here or the whole hashing thing is pointless
.filter(s -> ItemEquality.compareItems(s, filter) && !s.isComponentsPatchEmpty() && s.getComponents().hashCode() == componentsHash) .filter(s -> ItemEquality.compareItems(s, filter) && s.hasTag() && s.getTag().hashCode() == nbtHash)
.findFirst().orElse(filter); .findFirst().orElse(filter);
stack.setCount(filter.getCount()); stack.setCount(filter.getCount());
} }
@ -229,18 +228,18 @@ public class ItemTerminalBlockEntity extends BlockEntity implements IPipeConnect
} }
@Override @Override
public void saveAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) { public void saveAdditional(CompoundTag compound) {
super.saveAdditional(compound, pRegistries); super.saveAdditional(compound);
compound.put("items", this.items.serializeNBT(pRegistries)); compound.put("items", this.items.serializeNBT());
compound.put("requests", Utility.serializeAll(pRegistries, this.existingRequests)); compound.put("requests", Utility.serializeAll(this.existingRequests));
} }
@Override @Override
protected void loadAdditional(CompoundTag compound, HolderLookup.Provider pRegistries) { public void load(CompoundTag compound) {
this.items.deserializeNBT(pRegistries, compound.getCompound("items")); this.items.deserializeNBT(compound.getCompound("items"));
this.existingRequests.clear(); this.existingRequests.clear();
this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), l -> new NetworkLock(pRegistries, l))); this.existingRequests.addAll(Utility.deserializeAll(compound.getList("requests", Tag.TAG_COMPOUND), NetworkLock::new));
super.loadAdditional(compound, pRegistries); super.load(compound);
} }
@Override @Override

View file

@ -48,9 +48,9 @@ public class CraftingTerminalContainer extends ItemTerminalContainer {
super.slotsChanged(inventoryIn); super.slotsChanged(inventoryIn);
if (!this.player.level().isClientSide) { if (!this.player.level().isClientSide) {
var ret = ItemStack.EMPTY; var ret = ItemStack.EMPTY;
var optional = this.player.level().getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftInventory.asCraftInput(), this.player.level()); var optional = this.player.level().getServer().getRecipeManager().getRecipeFor(RecipeType.CRAFTING, this.craftInventory, this.player.level());
if (optional.isPresent()) if (optional.isPresent())
ret = optional.get().value().assemble(this.craftInventory.asCraftInput(), this.player.level().registryAccess()); ret = optional.get().value().assemble(this.craftInventory, this.player.level().registryAccess());
this.craftResult.setItem(0, ret); this.craftResult.setItem(0, ret);
((ServerPlayer) this.player).connection.send(new ClientboundContainerSetSlotPacket(this.containerId, 0, 0, ret)); ((ServerPlayer) this.player).connection.send(new ClientboundContainerSetSlotPacket(this.containerId, 0, 0, ret));
} }

View file

@ -11,11 +11,9 @@ import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.neoforged.neoforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
import java.util.Arrays;
public class CraftingTerminalGui extends ItemTerminalGui { public class CraftingTerminalGui extends ItemTerminalGui {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/crafting_terminal.png"); private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/crafting_terminal.png");
private Button requestButton; private Button requestButton;
public CraftingTerminalGui(ItemTerminalContainer screenContainer, Inventory inv, Component titleIn) { public CraftingTerminalGui(ItemTerminalContainer screenContainer, Inventory inv, Component titleIn) {
@ -30,7 +28,7 @@ public class CraftingTerminalGui extends ItemTerminalGui {
var amount = ItemTerminalGui.requestModifier(); var amount = ItemTerminalGui.requestModifier();
// also allow holding backspace instead of alt for people whose alt key is inaccessible (linux?) // also allow holding backspace instead of alt for people whose alt key is inaccessible (linux?)
var force = Screen.hasAltDown() || InputConstants.isKeyDown(this.minecraft.getWindow().getWindow(), 259) ? 1 : 0; var force = Screen.hasAltDown() || InputConstants.isKeyDown(this.minecraft.getWindow().getWindow(), 259) ? 1 : 0;
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, Arrays.asList(amount, force))); PacketDistributor.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CRAFT_TERMINAL_REQUEST, amount, force));
}).bounds(this.leftPos + 8, this.topPos + 100, 50, 20).build()); }).bounds(this.leftPos + 8, this.topPos + 100, 50, 20).build());
this.tick(); this.tick();
} }

View file

@ -20,7 +20,6 @@ import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation; import net.minecraft.resources.ResourceLocation;
import net.minecraft.util.Mth; import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.TooltipFlag;
import net.neoforged.neoforge.network.PacketDistributor; import net.neoforged.neoforge.network.PacketDistributor;
@ -30,10 +29,9 @@ import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@SuppressWarnings("ALL")
public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContainer> { public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContainer> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath(PrettyPipes.ID, "textures/gui/item_terminal.png"); private static final ResourceLocation TEXTURE = new ResourceLocation(PrettyPipes.ID, "textures/gui/item_terminal.png");
public List<ItemStack> currentlyCrafting; public List<ItemStack> currentlyCrafting;
public EditBox search; public EditBox search;
@ -93,7 +91,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
return; return;
var stack = widget.get().stack.copy(); var stack = widget.get().stack.copy();
stack.setCount(1); stack.setCount(1);
PacketDistributor.sendToServer(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount)); PacketDistributor.SERVER.noArg().send(new PacketRequest(this.menu.tile.getBlockPos(), stack, this.requestAmount));
this.requestAmount = 1; this.requestAmount = 1;
}).bounds(this.leftPos + this.getXOffset() + 95 - 7 - 25, this.topPos + 115, 50, 20).build()); }).bounds(this.leftPos + this.getXOffset() + 95 - 7 - 25, this.topPos + 115, 50, 20).build());
this.requestButton.active = false; this.requestButton.active = false;
@ -161,7 +159,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
// and vanilla buttons are activated when the click starts, so we'll always invoke jei accidentally by default // and vanilla buttons are activated when the click starts, so we'll always invoke jei accidentally by default
if (button == 0 && this.cancelCraftingButton.visible && this.cancelCraftingButton.isHovered()) { if (button == 0 && this.cancelCraftingButton.visible && this.cancelCraftingButton.isHovered()) {
if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) { if (this.currentlyCrafting != null && !this.currentlyCrafting.isEmpty()) {
PacketDistributor.sendToServer(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING, List.of())); PacketDistributor.SERVER.noArg().send(new PacketButton(this.menu.tile.getBlockPos(), PacketButton.ButtonResult.CANCEL_CRAFTING));
return true; return true;
} }
} }
@ -234,7 +232,7 @@ public class ItemTerminalGui extends AbstractContainerScreen<ItemTerminalContain
search = search.substring(1); search = search.substring(1);
} else if (search.startsWith("#")) { } else if (search.startsWith("#")) {
// search item description // search item description
var hoverText = s.getLeft().getTooltipLines(Item.TooltipContext.of(this.minecraft.level), this.minecraft.player, var hoverText = s.getLeft().getTooltipLines(this.minecraft.player,
this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL); this.minecraft.options.advancedItemTooltips ? TooltipFlag.Default.ADVANCED : TooltipFlag.Default.NORMAL);
toCompare = hoverText.stream().map(Component::getString).collect(Collectors.joining("\n")); toCompare = hoverText.stream().map(Component::getString).collect(Collectors.joining("\n"));
search = search.substring(1); search = search.substring(1);