From a033dbdd3910df539bca5a073d30ebd9b28b3ae4 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 28 Aug 2023 18:18:54 +0200 Subject: [PATCH 01/11] refactor: allow the API to attach energy storage capabilities --- CHANGELOG.md | 5 + .../impl/energy/EnergyStorageImpl.java | 10 +- .../energy/CompositeEnergyStorageTest.java | 20 ---- .../impl/energy/EnergyStorageImplTest.java | 95 ++++++++++++------- .../platform/api/PlatformApi.java | 9 ++ .../platform/api/PlatformApiProxy.java | 20 ++++ .../api/blockentity/EnergyBlockEntity.java | 14 +++ .../platform/api/item/AbstractEnergyItem.java | 68 +++++++++++++ .../platform/api/item/EnergyItem.java | 17 ++++ .../platform/common/Config.java | 2 - .../platform/common/Platform.java | 7 +- .../platform/common/PlatformApiImpl.java | 22 +++++ .../platform/common/PlatformProxy.java | 16 +--- .../entity/BlockEntityEnergyStorage.java | 20 ++++ .../block/entity/ControllerBlockEntity.java | 21 +++- .../slot/PlayerSlotReference.java | 5 + .../common/content/CreativeModeTabItems.java | 5 +- .../energy/CreativeEnergyStorage.java | 9 +- .../internal/energy/ItemEnergyStorage.java | 51 ++++++++++ .../internal/{ => energy}/package-info.java | 2 +- .../common/item/AbstractNetworkBoundItem.java | 42 +------- .../item/CreativeItemEnergyProvider.java | 38 -------- .../common/item/ItemEnergyProvider.java | 18 ---- .../common/item/NetworkBoundItemContext.java | 16 ++-- .../common/item/WirelessGridItem.java | 22 ++++- .../item/block/ControllerBlockItem.java | 2 + .../platform/fabric/ConfigImpl.java | 7 -- .../platform/fabric/ModInitializerImpl.java | 62 +++++++----- .../platform/fabric/PlatformImpl.java | 31 +++--- .../energy/ControllerTeamRebornEnergy.java | 69 -------------- .../TeamRebornEnergyItemEnergyProvider.java | 65 ------------- .../internal/energy/EnergyStorageAdapter.java | 58 +++++++++++ .../fabric/internal}/energy/package-info.java | 2 +- .../platform/forge/ConfigImpl.java | 6 -- .../platform/forge/ModInitializer.java | 60 +++++++----- .../platform/forge/PlatformImpl.java | 27 ++---- .../energy/ControllerForgeEnergy.java | 69 -------------- .../energy/ForgeEnergyCapabilityProvider.java | 29 ------ .../energy/ForgeEnergyItemEnergyProvider.java | 47 --------- .../integration/energy/ItemEnergyStorage.java | 37 -------- .../internal/energy/EnergyStorageAdapter.java | 48 ++++++++++ .../forge/internal}/energy/package-info.java | 2 +- 42 files changed, 572 insertions(+), 603 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/EnergyBlockEntity.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItem.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/BlockEntityEnergyStorage.java rename refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/InfiniteEnergyStorage.java => refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/CreativeEnergyStorage.java (66%) create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/ItemEnergyStorage.java rename refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/{ => energy}/package-info.java (96%) delete mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/CreativeItemEnergyProvider.java delete mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/ItemEnergyProvider.java delete mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/ControllerTeamRebornEnergy.java delete mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/TeamRebornEnergyItemEnergyProvider.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/EnergyStorageAdapter.java rename {refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration => refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal}/energy/package-info.java (73%) delete mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ControllerForgeEnergy.java delete mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyCapabilityProvider.java delete mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyItemEnergyProvider.java delete mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ItemEnergyStorage.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/EnergyStorageAdapter.java rename {refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration => refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal}/energy/package-info.java (73%) diff --git a/CHANGELOG.md b/CHANGELOG.md index cae95591e..d55e9adfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Removed + +- The `useEnergy` config option for the Wireless Grid. If you do not wish to use energy, use the + Creative Wireless Grid. + ## [2.0.0-milestone.3.0] - 2023-08-27 ### Added diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImpl.java b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImpl.java index 1a8283cc2..829e6eae2 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImpl.java +++ b/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImpl.java @@ -30,8 +30,9 @@ public long getCapacity() { public long receive(final long amount, final Action action) { final long spaceRemaining = capacity - stored; final long maxReceive = Math.min(amount, spaceRemaining); - if (action == Action.EXECUTE) { + if (maxReceive > 0 && action == Action.EXECUTE) { stored += maxReceive; + changed(); } return maxReceive; } @@ -39,9 +40,14 @@ public long receive(final long amount, final Action action) { @Override public long extract(final long amount, final Action action) { final long maxExtract = Math.min(stored, amount); - if (action == Action.EXECUTE) { + if (maxExtract > 0 && action == Action.EXECUTE) { stored -= maxExtract; + changed(); } return maxExtract; } + + protected void changed() { + // no op + } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/CompositeEnergyStorageTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/CompositeEnergyStorageTest.java index 024331e44..f26aa3d39 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/CompositeEnergyStorageTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/CompositeEnergyStorageTest.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -341,23 +340,4 @@ void shouldExtractFromMultipleSourcesCompletelyMoreThanIsAvailable(final Action assertThat(sut.getCapacity()).isEqualTo(15); } - - @Test - void shouldNotOverflowStoredAndCapacityCountOnInfiniteEnergyStoragesStoredInComposite() { - // Arrange - final EnergyStorage a = new InfiniteEnergyStorage(); - final EnergyStorage b = new InfiniteEnergyStorage(); - - final CompositeEnergyStorage sut = new CompositeEnergyStorage(); - sut.addSource(a); - sut.addSource(b); - - // Act - final long stored = sut.getStored(); - final long capacity = sut.getCapacity(); - - // Assert - assertThat(stored).isEqualTo(Long.MAX_VALUE); - assertThat(capacity).isEqualTo(Long.MAX_VALUE); - } } diff --git a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImplTest.java b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImplTest.java index 1a0d3e56e..fa043eb9b 100644 --- a/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImplTest.java +++ b/refinedstorage2-network/src/test/java/com/refinedmods/refinedstorage2/api/network/impl/energy/EnergyStorageImplTest.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; @@ -12,6 +13,21 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class EnergyStorageImplTest { + EnergyStorage sut; + int changeCount; + + @BeforeEach + void setUp() { + changeCount = 0; + sut = new EnergyStorageImpl(100) { + @Override + protected void changed() { + super.changed(); + changeCount++; + } + }; + } + @Test void testInvalidCapacity() { // Act @@ -25,70 +41,74 @@ void testInvalidCapacity() { @EnumSource(Action.class) void shouldNotReceiveEnergyOnZeroCapacityStorage(final Action action) { // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(0); + final EnergyStorage zeroCapacitySut = new EnergyStorageImpl(0) { + @Override + protected void changed() { + super.changed(); + changeCount++; + } + }; // Act - final long inserted = energyStorage.receive(1, action); + final long inserted = zeroCapacitySut.receive(1, action); // Assert assertThat(inserted).isZero(); - assertThat(energyStorage.getStored()).isZero(); + assertThat(changeCount).isZero(); + assertThat(zeroCapacitySut.getStored()).isZero(); } @ParameterizedTest @EnumSource(Action.class) void shouldReceiveEnergy(final Action action) { - // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - // Act - final long inserted = energyStorage.receive(50, action); + final long inserted = sut.receive(50, action); // Assert assertThat(inserted).isEqualTo(50); if (action == Action.EXECUTE) { - assertThat(energyStorage.getStored()).isEqualTo(50); + assertThat(sut.getStored()).isEqualTo(50); + assertThat(changeCount).isEqualTo(1); } else { - assertThat(energyStorage.getStored()).isZero(); + assertThat(sut.getStored()).isZero(); + assertThat(changeCount).isZero(); } } @ParameterizedTest @EnumSource(Action.class) void shouldReceiveEnergyAndReachCapacity(final Action action) { - // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - // Act - final long inserted = energyStorage.receive(100, action); + final long inserted = sut.receive(100, action); // Assert assertThat(inserted).isEqualTo(100); if (action == Action.EXECUTE) { - assertThat(energyStorage.getStored()).isEqualTo(100); + assertThat(sut.getStored()).isEqualTo(100); + assertThat(changeCount).isEqualTo(1); } else { - assertThat(energyStorage.getStored()).isZero(); + assertThat(sut.getStored()).isZero(); + assertThat(changeCount).isZero(); } } @ParameterizedTest @EnumSource(Action.class) void shouldReceiveEnergyAndExceedCapacity(final Action action) { - // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - // Act - final long inserted = energyStorage.receive(101, action); + final long inserted = sut.receive(101, action); // Assert assertThat(inserted).isEqualTo(100); if (action == Action.EXECUTE) { - assertThat(energyStorage.getStored()).isEqualTo(100); + assertThat(sut.getStored()).isEqualTo(100); + assertThat(changeCount).isEqualTo(1); } else { - assertThat(energyStorage.getStored()).isZero(); + assertThat(sut.getStored()).isZero(); + assertThat(changeCount).isZero(); } } @@ -96,34 +116,37 @@ void shouldReceiveEnergyAndExceedCapacity(final Action action) { @EnumSource(Action.class) void shouldNotReceiveEnergyWhenFull(final Action action) { // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - energyStorage.receive(100, Action.EXECUTE); + sut.receive(100, Action.EXECUTE); + changeCount = 0; // Act - final long inserted = energyStorage.receive(100, action); + final long inserted = sut.receive(100, action); // Assert assertThat(inserted).isZero(); - assertThat(energyStorage.getStored()).isEqualTo(100); + assertThat(changeCount).isZero(); + assertThat(sut.getStored()).isEqualTo(100); } @ParameterizedTest @EnumSource(Action.class) void shouldExtractEnergyPartly(final Action action) { // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - energyStorage.receive(100, Action.EXECUTE); + sut.receive(100, Action.EXECUTE); + changeCount = 0; // Act - final long extracted = energyStorage.extract(99, action); + final long extracted = sut.extract(99, action); // Assert assertThat(extracted).isEqualTo(99); if (action == Action.EXECUTE) { - assertThat(energyStorage.getStored()).isEqualTo(1); + assertThat(sut.getStored()).isEqualTo(1); + assertThat(changeCount).isEqualTo(1); } else { - assertThat(energyStorage.getStored()).isEqualTo(100); + assertThat(sut.getStored()).isEqualTo(100); + assertThat(changeCount).isZero(); } } @@ -131,19 +154,21 @@ void shouldExtractEnergyPartly(final Action action) { @EnumSource(Action.class) void shouldExtractEnergyCompletely(final Action action) { // Arrange - final EnergyStorage energyStorage = new EnergyStorageImpl(100); - energyStorage.receive(50, Action.EXECUTE); + sut.receive(50, Action.EXECUTE); + changeCount = 0; // Act - final long extracted = energyStorage.extract(51, action); + final long extracted = sut.extract(51, action); // Assert assertThat(extracted).isEqualTo(50); if (action == Action.EXECUTE) { - assertThat(energyStorage.getStored()).isZero(); + assertThat(sut.getStored()).isZero(); + assertThat(changeCount).isEqualTo(1); } else { - assertThat(energyStorage.getStored()).isEqualTo(50); + assertThat(sut.getStored()).isEqualTo(50); + assertThat(changeCount).isZero(); } } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index f47607570..b874ce9cc 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; @@ -34,11 +35,13 @@ import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import java.util.Collection; +import java.util.Optional; import java.util.Set; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.apiguardian.api.API; @@ -72,6 +75,8 @@ public interface PlatformApi { MutableComponent createTranslation(String category, String value, Object... args); + MutableComponent createStoredWithCapacityTranslation(long stored, long capacity, double pct); + ComponentMapFactory getNetworkComponentMapFactory(); PlatformRegistry getGridSynchronizerRegistry(); @@ -135,4 +140,8 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe void addWirelessTransmitterRangeModifier(WirelessTransmitterRangeModifier rangeModifier); WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier(); + + Optional getEnergyStorage(ItemStack stack); + + EnergyStorage asItemEnergyStorage(EnergyStorage energyStorage, ItemStack stack); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index a379d5b8e..ac6613efe 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; @@ -34,12 +35,14 @@ import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import java.util.Collection; +import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import net.minecraft.network.chat.MutableComponent; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; public class PlatformApiProxy implements PlatformApi { @@ -118,6 +121,13 @@ public MutableComponent createTranslation(final String category, final String va return ensureLoaded().createTranslation(category, value, args); } + @Override + public MutableComponent createStoredWithCapacityTranslation(final long stored, + final long capacity, + final double pct) { + return ensureLoaded().createStoredWithCapacityTranslation(stored, capacity, pct); + } + @Override public ComponentMapFactory getNetworkComponentMapFactory() { return ensureLoaded().getNetworkComponentMapFactory(); @@ -271,6 +281,16 @@ public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { return ensureLoaded().getWirelessTransmitterRangeModifier(); } + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return ensureLoaded().getEnergyStorage(stack); + } + + @Override + public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { + return ensureLoaded().asItemEnergyStorage(energyStorage, stack); + } + private PlatformApi ensureLoaded() { if (delegate == null) { throw new IllegalStateException("Platform API not loaded yet"); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/EnergyBlockEntity.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/EnergyBlockEntity.java new file mode 100644 index 000000000..a95e857de --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/EnergyBlockEntity.java @@ -0,0 +1,14 @@ +package com.refinedmods.refinedstorage2.platform.api.blockentity; + +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; + +import org.apiguardian.api.API; + +/** + * Implement this on block entities that can contain energy. + * At runtime, Refined Storage will attach an energy storage adapter for the platform. + */ +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface EnergyBlockEntity { + EnergyStorage getEnergyStorage(); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java new file mode 100644 index 000000000..9295c068c --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java @@ -0,0 +1,68 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; + +import java.util.List; +import javax.annotation.Nullable; + +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; + +public abstract class AbstractEnergyItem extends Item implements EnergyItem { + protected AbstractEnergyItem(final Properties properties) { + super(properties); + } + + @Override + public void appendHoverText( + final ItemStack stack, + @Nullable final Level level, + final List lines, + final TooltipFlag flag + ) { + super.appendHoverText(stack, level, lines, flag); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> { + final long stored = energyStorage.getStored(); + final long capacity = energyStorage.getCapacity(); + final double pct = stored / (double) capacity; + lines.add(PlatformApi.INSTANCE.createStoredWithCapacityTranslation(stored, capacity, pct) + .withStyle(ChatFormatting.GRAY)); + }); + } + + @Override + public boolean isBarVisible(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).isPresent(); + } + + @Override + public int getBarWidth(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> (int) Math.round( + (energyStorage.getStored() / (double) energyStorage.getCapacity()) * 13D + )).orElse(0); + } + + @Override + public int getBarColor(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> Mth.hsvToRgb( + Math.max(0.0F, (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) / 3.0F, + 1.0F, + 1.0F + )).orElse(0); + } + + public ItemStack createAtEnergyCapacity() { + final ItemStack stack = new ItemStack(this); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> energyStorage.receive( + energyStorage.getCapacity(), + Action.EXECUTE + )); + return stack; + } +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItem.java new file mode 100644 index 000000000..fb7b3c7d8 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItem.java @@ -0,0 +1,17 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; + +import java.util.Optional; + +import net.minecraft.world.item.ItemStack; +import org.apiguardian.api.API; + +/** + * Implement this on items that can contain energy. + * At runtime, Refined Storage will attach an energy storage adapter for the platform on the given {@link ItemStack}. + */ +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface EnergyItem { + Optional createEnergyStorage(ItemStack stack); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java index 865bbf8d0..70523581c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java @@ -149,8 +149,6 @@ interface UpgradeEntry { } interface WirelessGridEntry { - boolean getUseEnergy(); - long getEnergyCapacity(); long getOpenEnergyUsage(); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java index 591671f0b..79ca84bb4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java @@ -7,7 +7,6 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.menu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.packet.ClientToServerCommunications; @@ -81,10 +80,6 @@ public interface Platform { Optional convertToBucket(FluidResource fluidResource); - EnergyStorage createEnergyStorage(ControllerType controllerType, Runnable listener); - - void setEnergy(EnergyStorage energyStorage, long stored); - TransferManager createTransferManager(AbstractContainerMenu containerMenu); long insertIntoContainer(Container container, ItemResource itemResource, long amount, Action action); @@ -123,4 +118,6 @@ List processTooltipComponents( ); void renderTooltip(GuiGraphics graphics, List components, int x, int y); + + Optional getEnergyStorage(ItemStack stack); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 2a61e639c..13f827d08 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.NetworkBuilder; import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.impl.NetworkBuilderImpl; import com.refinedmods.refinedstorage2.api.network.impl.NetworkFactory; import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; @@ -38,6 +39,7 @@ import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.CompositeWirelessTransmitterRangeModifier; import com.refinedmods.refinedstorage2.platform.common.integration.recipemod.CompositeIngredientConverter; +import com.refinedmods.refinedstorage2.platform.common.internal.energy.ItemEnergyStorage; import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; @@ -67,6 +69,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; @@ -76,6 +79,7 @@ import net.minecraft.server.level.ServerLevel; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; @@ -213,6 +217,13 @@ public MutableComponent createTranslation(final String category, final String va return IdentifierUtil.createTranslation(category, value, args); } + @Override + public MutableComponent createStoredWithCapacityTranslation(final long stored, + final long capacity, + final double pct) { + return IdentifierUtil.createStoredWithCapacityTranslation(stored, capacity, pct); + } + @Override public ComponentMapFactory getNetworkComponentMapFactory() { return networkComponentMapFactory; @@ -391,4 +402,15 @@ public void addWirelessTransmitterRangeModifier(final WirelessTransmitterRangeMo public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { return wirelessTransmitterRangeModifier; } + + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return Platform.INSTANCE.getEnergyStorage(stack); + } + + @Override + public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, + final ItemStack stack) { + return new ItemEnergyStorage(stack, energyStorage); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java index 21d6f0639..cc86cbe36 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java @@ -7,7 +7,6 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.menu.MenuOpener; import com.refinedmods.refinedstorage2.platform.common.packet.ClientToServerCommunications; @@ -137,16 +136,6 @@ public Optional convertToBucket(final FluidResource fluidResource) { return ensureLoaded().convertToBucket(fluidResource); } - @Override - public EnergyStorage createEnergyStorage(final ControllerType controllerType, final Runnable listener) { - return ensureLoaded().createEnergyStorage(controllerType, listener); - } - - @Override - public void setEnergy(final EnergyStorage energyStorage, final long stored) { - ensureLoaded().setEnergy(energyStorage, stored); - } - @Override public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { return ensureLoaded().createTransferManager(containerMenu); @@ -240,6 +229,11 @@ public void renderTooltip(final GuiGraphics graphics, ensureLoaded().renderTooltip(graphics, components, x, y); } + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return ensureLoaded().getEnergyStorage(stack); + } + private Platform ensureLoaded() { if (platform == null) { throw new IllegalStateException("Platform not loaded yet"); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/BlockEntityEnergyStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/BlockEntityEnergyStorage.java new file mode 100644 index 000000000..ddae1cef8 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/BlockEntityEnergyStorage.java @@ -0,0 +1,20 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity; + +import com.refinedmods.refinedstorage2.api.network.impl.energy.EnergyStorageImpl; + +import net.minecraft.world.level.block.entity.BlockEntity; + +public class BlockEntityEnergyStorage extends EnergyStorageImpl { + private final BlockEntity blockEntity; + + public BlockEntityEnergyStorage(final long capacity, final BlockEntity blockEntity) { + super(capacity); + this.blockEntity = blockEntity; + } + + @Override + protected void changed() { + super.changed(); + blockEntity.setChanged(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index 609795f5d..be60d8805 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -1,13 +1,16 @@ package com.refinedmods.refinedstorage2.platform.common.block.entity; +import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.api.network.impl.node.controller.ControllerNetworkNode; +import com.refinedmods.refinedstorage2.platform.api.blockentity.EnergyBlockEntity; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.block.ControllerBlock; import com.refinedmods.refinedstorage2.platform.common.block.ControllerEnergyType; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.ControllerContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.internal.energy.CreativeEnergyStorage; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; import javax.annotation.Nullable; @@ -21,6 +24,7 @@ import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.slf4j.Logger; @@ -29,7 +33,7 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; public class ControllerBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity - implements ExtendedMenuProvider { + implements ExtendedMenuProvider, EnergyBlockEntity { private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBlockEntity.class); private static final String TAG_STORED = "stored"; @@ -42,10 +46,20 @@ public class ControllerBlockEntity extends AbstractInternalNetworkNodeContainerB public ControllerBlockEntity(final ControllerType type, final BlockPos pos, final BlockState state) { super(getBlockEntityType(type), pos, state, new ControllerNetworkNode()); this.type = type; - this.energyStorage = Platform.INSTANCE.createEnergyStorage(type, this::setChanged); + this.energyStorage = createEnergyStorage(type, this); this.getNode().setEnergyStorage(energyStorage); } + private static EnergyStorage createEnergyStorage(final ControllerType type, final BlockEntity blockEntity) { + if (type == ControllerType.CREATIVE) { + return CreativeEnergyStorage.INSTANCE; + } + return new BlockEntityEnergyStorage( + Platform.INSTANCE.getConfig().getController().getEnergyCapacity(), + blockEntity + ); + } + private static BlockEntityType getBlockEntityType(final ControllerType type) { return type == ControllerType.CREATIVE ? BlockEntities.INSTANCE.getCreativeController() @@ -108,7 +122,7 @@ private void saveRenderingInfo(final CompoundTag tag) { public void load(final CompoundTag tag) { super.load(tag); if (tag.contains(TAG_STORED)) { - Platform.INSTANCE.setEnergy(energyStorage, tag.getLong(TAG_STORED)); + energyStorage.receive(tag.getLong(TAG_STORED), Action.EXECUTE); } } @@ -139,6 +153,7 @@ public long getActualCapacity() { return getNode().getActualCapacity(); } + @Override public EnergyStorage getEnergyStorage() { return energyStorage; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java index 35d6b7634..79624d01b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java @@ -4,6 +4,7 @@ import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; public final class PlayerSlotReference { private final int slotIndex; @@ -12,6 +13,10 @@ private PlayerSlotReference(final int slotIndex) { this.slotIndex = slotIndex; } + public ItemStack resolve(final Player player) { + return player.getInventory().getItem(slotIndex); + } + public int getSlotIndex() { return slotIndex; } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java index 44508cd5b..0fb395830 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java @@ -1,6 +1,5 @@ package com.refinedmods.refinedstorage2.platform.common.content; -import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.item.ProcessorItem; @@ -93,9 +92,7 @@ private static void appendItems(final Consumer consumer) { itemConsumer.accept(Items.INSTANCE.getRangeUpgrade()); itemConsumer.accept(Items.INSTANCE.getCreativeRangeUpgrade()); itemConsumer.accept(Items.INSTANCE.getWirelessGrid()); - if (Platform.INSTANCE.getConfig().getWirelessGrid().getUseEnergy()) { - consumer.accept(Items.INSTANCE.getWirelessGrid().getAtCapacity()); - } + consumer.accept(Items.INSTANCE.getWirelessGrid().createAtEnergyCapacity()); itemConsumer.accept(Items.INSTANCE.getCreativeWirelessGrid()); } } diff --git a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/InfiniteEnergyStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/CreativeEnergyStorage.java similarity index 66% rename from refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/InfiniteEnergyStorage.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/CreativeEnergyStorage.java index cd8320d9d..b9e409319 100644 --- a/refinedstorage2-network/src/main/java/com/refinedmods/refinedstorage2/api/network/impl/energy/InfiniteEnergyStorage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/CreativeEnergyStorage.java @@ -1,9 +1,14 @@ -package com.refinedmods.refinedstorage2.api.network.impl.energy; +package com.refinedmods.refinedstorage2.platform.common.internal.energy; import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -public class InfiniteEnergyStorage implements EnergyStorage { +public class CreativeEnergyStorage implements EnergyStorage { + public static final EnergyStorage INSTANCE = new CreativeEnergyStorage(); + + private CreativeEnergyStorage() { + } + @Override public long getStored() { return Long.MAX_VALUE; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/ItemEnergyStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/ItemEnergyStorage.java new file mode 100644 index 000000000..a3e8db2ed --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/ItemEnergyStorage.java @@ -0,0 +1,51 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.energy; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.world.item.ItemStack; + +public class ItemEnergyStorage implements EnergyStorage { + private static final String TAG_STORED = "stored"; + + private final ItemStack stack; + private final EnergyStorage delegate; + + public ItemEnergyStorage(final ItemStack stack, final EnergyStorage delegate) { + this.stack = stack; + this.delegate = delegate; + final CompoundTag tag = stack.getTag(); + if (tag != null && tag.contains(TAG_STORED)) { + delegate.receive(tag.getLong(TAG_STORED), Action.EXECUTE); + } + } + + @Override + public long getStored() { + return delegate.getStored(); + } + + @Override + public long getCapacity() { + return delegate.getCapacity(); + } + + @Override + public long receive(final long amount, final Action action) { + final long received = delegate.receive(amount, action); + if (received > 0 && action == Action.EXECUTE) { + stack.getOrCreateTag().putLong(TAG_STORED, getStored()); + } + return received; + } + + @Override + public long extract(final long amount, final Action action) { + final long extracted = delegate.extract(amount, action); + if (extracted > 0 && action == Action.EXECUTE) { + stack.getOrCreateTag().putLong(TAG_STORED, getStored()); + } + return extracted; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/package-info.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/package-info.java similarity index 96% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/package-info.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/package-info.java index b0c2beed0..bac26d372 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/package-info.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/energy/package-info.java @@ -1,6 +1,6 @@ @ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault -package com.refinedmods.refinedstorage2.platform.common.internal; +package com.refinedmods.refinedstorage2.platform.common.internal.energy; import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java index 414c04959..b6e85b60f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.item; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyItem; import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; @@ -19,20 +20,17 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.Mth; import net.minecraft.world.InteractionResult; import net.minecraft.world.inventory.tooltip.TooltipComponent; -import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createStoredWithCapacityTranslation; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -public abstract class AbstractNetworkBoundItem extends Item { +public abstract class AbstractNetworkBoundItem extends AbstractEnergyItem { private static final MutableComponent UNBOUND = createTranslation("item", "network_item.unbound") .withStyle(ChatFormatting.RED); private static final Component UNBOUND_HELP = createTranslation("item", "network_item.unbound.help"); @@ -42,11 +40,8 @@ public abstract class AbstractNetworkBoundItem extends Item { private static final String TAG_Z = "z"; private static final String TAG_DIMENSION = "dim"; - private final ItemEnergyProvider energyProvider; - - protected AbstractNetworkBoundItem(final Properties properties, final ItemEnergyProvider energyProvider) { + protected AbstractNetworkBoundItem(final Properties properties) { super(properties); - this.energyProvider = energyProvider; } public boolean isBound(final ItemStack stack) { @@ -82,7 +77,6 @@ protected void tryUse( contextConsumer.accept(new NetworkBoundItemContext( player, slotReference, - energyProvider, networkReference.orElse(null) )); } @@ -121,36 +115,6 @@ public void appendHoverText(final ItemStack stack, ).withStyle(ChatFormatting.GRAY)), () -> tooltip.add(UNBOUND) ); - if (!energyProvider.isEnabled()) { - return; - } - final long stored = energyProvider.getStored(stack); - final long capacity = energyProvider.getCapacity(stack); - final double pct = stored / (double) capacity; - tooltip.add(createStoredWithCapacityTranslation(stored, capacity, pct).withStyle(ChatFormatting.GRAY)); - } - - @Override - public boolean isBarVisible(final ItemStack stack) { - return energyProvider.isEnabled(); - } - - @Override - public int getBarWidth(final ItemStack stack) { - return (int) Math.round((energyProvider.getStored(stack) / (double) energyProvider.getCapacity(stack)) * 13D); - } - - @Override - public int getBarColor(final ItemStack stack) { - return Mth.hsvToRgb( - Math.max(0.0F, (float) energyProvider.getStored(stack) / (float) energyProvider.getCapacity(stack)) / 3.0F, - 1.0F, - 1.0F - ); - } - - public ItemStack getAtCapacity() { - return energyProvider.getAtCapacity(new ItemStack(this)); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/CreativeItemEnergyProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/CreativeItemEnergyProvider.java deleted file mode 100644 index 9ae378966..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/CreativeItemEnergyProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.item; - -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -public class CreativeItemEnergyProvider implements ItemEnergyProvider { - public static final ItemEnergyProvider INSTANCE = new CreativeItemEnergyProvider(); - - private CreativeItemEnergyProvider() { - } - - @Override - public boolean isEnabled() { - return false; - } - - @Override - public long getStored(final ItemStack stack) { - return 0; - } - - @Override - public long getCapacity(final ItemStack stack) { - return 0; - } - - @Override - public void drain(final Player player, final PlayerSlotReference slotReference, final long amount) { - // no op - } - - @Override - public ItemStack getAtCapacity(final ItemStack stack) { - return stack.copy(); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/ItemEnergyProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/ItemEnergyProvider.java deleted file mode 100644 index ee89f47c6..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/ItemEnergyProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.item; - -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -public interface ItemEnergyProvider { - boolean isEnabled(); - - long getStored(ItemStack stack); - - long getCapacity(ItemStack stack); - - void drain(Player player, PlayerSlotReference slotReference, long amount); - - ItemStack getAtCapacity(ItemStack stack); -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java index 3e5a5749e..e5064def1 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java @@ -1,5 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.item; +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import javax.annotation.Nullable; @@ -14,14 +16,12 @@ public class NetworkBoundItemContext { private final Player player; private final Vec3 playerPosition; private final PlayerSlotReference playerSlotReference; - private final ItemEnergyProvider energyProvider; @Nullable private final NetworkReference networkReference; public NetworkBoundItemContext( final Player player, final PlayerSlotReference playerSlotReference, - final ItemEnergyProvider energyProvider, @Nullable final NetworkReference networkReference ) { this.player = player; @@ -31,7 +31,6 @@ public NetworkBoundItemContext( // be removed after it was added). this.playerPosition = new Vec3(player.position().x, player.position().y, player.position().z); this.playerSlotReference = playerSlotReference; - this.energyProvider = energyProvider; this.networkReference = networkReference; } @@ -44,14 +43,15 @@ public ResourceKey getPlayerLevel() { } public boolean isActive() { - if (!energyProvider.isEnabled()) { - return true; - } - return energyProvider.getStored(player.getInventory().getItem(playerSlotReference.getSlotIndex())) > 0; + return Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)) + .map(energyStorage -> energyStorage.getStored() > 0) + .orElse(true); } public void drain(final long amount) { - energyProvider.drain(player, playerSlotReference, amount); + Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)).ifPresent( + energyStorage -> energyStorage.extract(amount, Action.EXECUTE) + ); } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java index 9377db11e..15fd00057 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java @@ -1,5 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.item; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import com.refinedmods.refinedstorage2.api.network.impl.energy.EnergyStorageImpl; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.common.Platform; @@ -7,6 +9,8 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.WirelessGrid; import com.refinedmods.refinedstorage2.platform.common.menu.WirelessGridExtendedMenuProvider; +import java.util.Optional; + import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; @@ -17,8 +21,11 @@ import net.minecraft.world.level.Level; public class WirelessGridItem extends AbstractNetworkBoundItem { - public WirelessGridItem(final ItemEnergyProvider energyProvider) { - super(new Item.Properties().stacksTo(1), energyProvider); + private final boolean creative; + + public WirelessGridItem(final boolean creative) { + super(new Item.Properties().stacksTo(1)); + this.creative = creative; } @Override @@ -50,4 +57,15 @@ private void open( slotReference )); } + + @Override + public Optional createEnergyStorage(final ItemStack stack) { + if (creative) { + return Optional.empty(); + } + final EnergyStorage energyStorage = new EnergyStorageImpl( + Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity() + ); + return Optional.of(PlatformApi.INSTANCE.asItemEnergyStorage(energyStorage, stack)); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java index 25e4f4e15..fbd16b44f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java @@ -25,6 +25,8 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createStoredWithCapacityTranslation; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; +// TODO: Use cap here. +// TODO: Make network bound item api accessible. public class ControllerBlockItem extends CreativeControllerBlockItem { public ControllerBlockItem(final Block block, final Component displayName) { super(block, displayName); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java index 58fa9635b..b65a123ac 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java @@ -504,8 +504,6 @@ public int getRangeUpgradeRange() { } private static class WirelessGridEntryImpl implements WirelessGridEntry { - private boolean useEnergy = true; - private long energyCapacity = DefaultEnergyUsage.WIRELESS_GRID_CAPACITY; private long openEnergyUsage = DefaultEnergyUsage.WIRELESS_GRID_OPEN; @@ -514,11 +512,6 @@ private static class WirelessGridEntryImpl implements WirelessGridEntry { private long extractEnergyUsage = DefaultEnergyUsage.WIRELESS_GRID_EXTRACT; - @Override - public boolean getUseEnergy() { - return useEnergy; - } - @Override public long getEnergyCapacity() { return energyCapacity; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index b84cf1172..e08a7f6e4 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.fabric; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.blockentity.EnergyBlockEntity; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItem; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractModInitializer; -import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.block.AbstractBaseBlock; import com.refinedmods.refinedstorage2.platform.common.block.entity.diskdrive.AbstractDiskDriveBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.iface.InterfaceBlockEntity; @@ -13,17 +14,14 @@ import com.refinedmods.refinedstorage2.platform.common.content.Blocks; import com.refinedmods.refinedstorage2.platform.common.content.CreativeModeTabItems; import com.refinedmods.refinedstorage2.platform.common.content.DirectRegistryCallback; -import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.MenuTypeFactory; import com.refinedmods.refinedstorage2.platform.common.internal.network.node.iface.externalstorage.InterfacePlatformExternalStorageProviderFactory; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; -import com.refinedmods.refinedstorage2.platform.common.item.CreativeItemEnergyProvider; import com.refinedmods.refinedstorage2.platform.common.item.RegulatorUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.item.WirelessGridItem; import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; import com.refinedmods.refinedstorage2.platform.fabric.block.entity.FabricDiskDriveBlockEntity; -import com.refinedmods.refinedstorage2.platform.fabric.integration.energy.ControllerTeamRebornEnergy; -import com.refinedmods.refinedstorage2.platform.fabric.integration.energy.TeamRebornEnergyItemEnergyProvider; +import com.refinedmods.refinedstorage2.platform.fabric.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.FluidGridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.FluidGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.ItemGridExtractionStrategy; @@ -51,18 +49,24 @@ import java.util.Optional; import java.util.function.Function; import java.util.function.Predicate; +import javax.annotation.Nullable; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.serializer.Toml4jConfigSerializer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; import net.fabricmc.fabric.api.event.player.UseBlockCallback; +import net.fabricmc.fabric.api.lookup.v1.block.BlockApiLookup; +import net.fabricmc.fabric.api.lookup.v1.item.ItemApiLookup; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.fabricmc.fabric.api.screenhandler.v1.ExtendedScreenHandlerType; +import net.fabricmc.fabric.api.transfer.v1.context.ContainerItemContext; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidConstants; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidStorage; import net.fabricmc.fabric.api.transfer.v1.item.InventoryStorage; import net.fabricmc.fabric.api.transfer.v1.item.ItemStorage; +import net.minecraft.core.BlockPos; +import net.minecraft.core.Direction; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.world.Container; @@ -73,6 +77,7 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; @@ -80,7 +85,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import team.reborn.energy.api.EnergyStorage; -import team.reborn.energy.api.base.SimpleEnergyItem; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; @@ -203,7 +207,7 @@ public boolean allowNbtUpdateAnimation(final Player player, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(new TeamRebornEnergyItemEnergyProvider()) { + () -> new WirelessGridItem(false) { @Override public boolean allowNbtUpdateAnimation(final Player player, final InteractionHand hand, @@ -212,7 +216,7 @@ public boolean allowNbtUpdateAnimation(final Player player, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(CreativeItemEnergyProvider.INSTANCE) { + () -> new WirelessGridItem(true) { @Override public boolean allowNbtUpdateAnimation(final Player player, final InteractionHand hand, @@ -300,8 +304,8 @@ private void registerSidedHandlers() { (blockEntity, context) -> new ResourceContainerFluidStorageAdapter(blockEntity.getExportedResources()), BlockEntities.INSTANCE.getInterface() ); - registerControllerEnergy(); - registerWirelessGridEnergy(); + registerEnergyBlockEntityProviders(); + registerEnergyItemProviders(); } private void registerItemStorage(final Predicate test, @@ -317,20 +321,34 @@ private void registerItemStorage(final Predicate ((ControllerTeamRebornEnergy) be.getEnergyStorage()).getExposedStorage(), - BlockEntities.INSTANCE.getController() - ); + private void registerEnergyBlockEntityProviders() { + EnergyStorage.SIDED.registerFallback(new BlockApiLookup.BlockApiProvider<>() { + @Override + @Nullable + public EnergyStorage find(final Level world, + final BlockPos pos, + final BlockState state, + @Nullable final BlockEntity blockEntity, + final Direction context) { + if (blockEntity instanceof EnergyBlockEntity energyBlockEntity) { + return new EnergyStorageAdapter(energyBlockEntity.getEnergyStorage()); + } + return null; + } + }); } - private void registerWirelessGridEnergy() { - EnergyStorage.ITEM.registerForItems((stack, context) -> SimpleEnergyItem.createStorage( - context, - Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity(), - Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity(), - Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity() - ), Items.INSTANCE.getWirelessGrid()); + private void registerEnergyItemProviders() { + EnergyStorage.ITEM.registerFallback(new ItemApiLookup.ItemApiProvider<>() { + @Override + @Nullable + public EnergyStorage find(final ItemStack itemStack, final ContainerItemContext context) { + if (itemStack.getItem() instanceof EnergyItem energyItem) { + return energyItem.createEnergyStorage(itemStack).map(EnergyStorageAdapter::new).orElse(null); + } + return null; + } + }); } private void registerTickHandler() { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java index c7d9993d0..877849b91 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java @@ -3,18 +3,16 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.network.impl.energy.InfiniteEnergyStorage; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; -import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketAmountFormatting; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; import com.refinedmods.refinedstorage2.platform.fabric.containermenu.ContainerTransferDestination; -import com.refinedmods.refinedstorage2.platform.fabric.integration.energy.ControllerTeamRebornEnergy; +import com.refinedmods.refinedstorage2.platform.fabric.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.ItemGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.view.FabricFluidGridResourceFactory; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.view.FabricItemGridResourceFactory; @@ -195,21 +193,6 @@ private Optional> convertNonEmptyToFluid(final Ite )); } - @Override - public EnergyStorage createEnergyStorage(final ControllerType controllerType, final Runnable listener) { - return switch (controllerType) { - case NORMAL -> new ControllerTeamRebornEnergy(listener); - case CREATIVE -> new InfiniteEnergyStorage(); - }; - } - - @Override - public void setEnergy(final EnergyStorage energyStorage, final long stored) { - if (energyStorage instanceof ControllerTeamRebornEnergy controllerTeamRebornEnergy) { - controllerTeamRebornEnergy.setStoredSilently(stored); - } - } - @Override public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { return new TransferManager(containerMenu, ContainerTransferDestination::new); @@ -389,4 +372,16 @@ public void renderTooltip(final GuiGraphics graphics, DefaultTooltipPositioner.INSTANCE ); } + + @Override + public Optional getEnergyStorage(final ItemStack stack) { + final ConstantContainerItemContext ctx = new ConstantContainerItemContext( + ItemVariant.of(stack), + stack.getCount() + ); + return Optional.ofNullable(team.reborn.energy.api.EnergyStorage.ITEM.find(stack, ctx)) + .filter(EnergyStorageAdapter.class::isInstance) + .map(EnergyStorageAdapter.class::cast) + .map(EnergyStorageAdapter::getEnergyStorage); + } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/ControllerTeamRebornEnergy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/ControllerTeamRebornEnergy.java deleted file mode 100644 index f72c9cb01..000000000 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/ControllerTeamRebornEnergy.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.fabric.integration.energy; - -import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.platform.common.Platform; - -import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction; -import team.reborn.energy.api.base.LimitingEnergyStorage; -import team.reborn.energy.api.base.SimpleEnergyStorage; - -public class ControllerTeamRebornEnergy extends SimpleEnergyStorage implements EnergyStorage { - private final Runnable listener; - private final LimitingEnergyStorage exposedStorage; - - public ControllerTeamRebornEnergy(final Runnable listener) { - super( - Platform.INSTANCE.getConfig().getController().getEnergyCapacity(), - Platform.INSTANCE.getConfig().getController().getEnergyCapacity(), - Platform.INSTANCE.getConfig().getController().getEnergyCapacity() - ); - this.listener = listener; - this.exposedStorage = new LimitingEnergyStorage( - this, - maxInsert, - 0 - ); - } - - public LimitingEnergyStorage getExposedStorage() { - return exposedStorage; - } - - public void setStoredSilently(final long stored) { - this.amount = stored; - } - - @Override - protected void onFinalCommit() { - super.onFinalCommit(); - listener.run(); - } - - @Override - public long getStored() { - return getAmount(); - } - - @Override - public long receive(final long amount, final Action action) { - try (Transaction tx = Transaction.openOuter()) { - final long received = this.insert(amount, tx); - if (received > 0 && action == Action.EXECUTE) { - tx.commit(); - } - return received; - } - } - - @Override - public long extract(final long amount, final Action action) { - try (Transaction tx = Transaction.openOuter()) { - final long extracted = this.extract(amount, tx); - if (extracted > 0 && action == Action.EXECUTE) { - tx.commit(); - } - return extracted; - } - } -} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/TeamRebornEnergyItemEnergyProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/TeamRebornEnergyItemEnergyProvider.java deleted file mode 100644 index 0c0fdda4e..000000000 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/TeamRebornEnergyItemEnergyProvider.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.fabric.integration.energy; - -import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; -import com.refinedmods.refinedstorage2.platform.common.item.ItemEnergyProvider; - -import net.fabricmc.fabric.api.transfer.v1.context.ContainerItemContext; -import net.fabricmc.fabric.api.transfer.v1.item.PlayerInventoryStorage; -import net.fabricmc.fabric.api.transfer.v1.transaction.Transaction; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import team.reborn.energy.api.EnergyStorage; -import team.reborn.energy.api.base.SimpleEnergyItem; - -public class TeamRebornEnergyItemEnergyProvider implements ItemEnergyProvider { - @Override - public boolean isEnabled() { - return Platform.INSTANCE.getConfig().getWirelessGrid().getUseEnergy(); - } - - @Override - public long getStored(final ItemStack stack) { - final EnergyStorage energyStorage = EnergyStorage.ITEM.find(stack, ContainerItemContext.withConstant(stack)); - if (energyStorage == null) { - return 0; - } - return energyStorage.getAmount(); - } - - @Override - public long getCapacity(final ItemStack stack) { - final EnergyStorage energyStorage = EnergyStorage.ITEM.find(stack, ContainerItemContext.withConstant(stack)); - if (energyStorage == null) { - return 0; - } - return energyStorage.getCapacity(); - } - - @Override - public void drain(final Player player, final PlayerSlotReference slotReference, final long amount) { - if (!isEnabled()) { - return; - } - final PlayerInventoryStorage inventoryStorage = PlayerInventoryStorage.of(player); - final ContainerItemContext ctx = ContainerItemContext.ofPlayerSlot( - player, - inventoryStorage.getSlot(slotReference.getSlotIndex()) - ); - final EnergyStorage energyStorage = EnergyStorage.ITEM.find(ctx.getItemVariant().toStack(), ctx); - if (energyStorage == null) { - return; - } - try (Transaction tx = Transaction.openOuter()) { - energyStorage.extract(amount, tx); - tx.commit(); - } - } - - @Override - public ItemStack getAtCapacity(final ItemStack stack) { - final ItemStack copied = stack.copy(); - SimpleEnergyItem.setStoredEnergyUnchecked(copied, getCapacity(copied)); - return copied; - } -} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/EnergyStorageAdapter.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/EnergyStorageAdapter.java new file mode 100644 index 000000000..4441d5559 --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/EnergyStorageAdapter.java @@ -0,0 +1,58 @@ +package com.refinedmods.refinedstorage2.platform.fabric.internal.energy; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; + +import net.fabricmc.fabric.api.transfer.v1.transaction.TransactionContext; +import net.fabricmc.fabric.api.transfer.v1.transaction.base.SnapshotParticipant; + +public class EnergyStorageAdapter extends SnapshotParticipant implements team.reborn.energy.api.EnergyStorage { + private final EnergyStorage energyStorage; + + public EnergyStorageAdapter(final EnergyStorage energyStorage) { + this.energyStorage = energyStorage; + } + + public EnergyStorage getEnergyStorage() { + return energyStorage; + } + + @Override + public long insert(final long maxAmount, final TransactionContext transaction) { + final long insertedSimulated = energyStorage.receive(maxAmount, Action.SIMULATE); + if (insertedSimulated > 0) { + updateSnapshots(transaction); + } + return energyStorage.receive(maxAmount, Action.EXECUTE); + } + + @Override + public long extract(final long maxAmount, final TransactionContext transaction) { + final long extractedSimulated = energyStorage.extract(maxAmount, Action.SIMULATE); + if (extractedSimulated > 0) { + updateSnapshots(transaction); + } + return energyStorage.extract(maxAmount, Action.EXECUTE); + } + + @Override + public long getAmount() { + return energyStorage.getStored(); + } + + @Override + public long getCapacity() { + return energyStorage.getCapacity(); + } + + @Override + protected Long createSnapshot() { + return energyStorage.getStored(); + } + + @Override + protected void readSnapshot(final Long snapshot) { + energyStorage.extract(Long.MAX_VALUE, Action.EXECUTE); + energyStorage.receive(snapshot, Action.EXECUTE); + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/package-info.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/package-info.java similarity index 73% rename from refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/package-info.java rename to refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/package-info.java index eefd34368..2aeaa6802 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/package-info.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/energy/package-info.java @@ -1,6 +1,6 @@ @ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault -package com.refinedmods.refinedstorage2.platform.forge.integration.energy; +package com.refinedmods.refinedstorage2.platform.fabric.internal.energy; import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java index 06e681ee8..e249e5ae6 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java @@ -639,7 +639,6 @@ public int getRangeUpgradeRange() { } private class WirelessGridEntryImpl implements WirelessGridEntry { - private final ForgeConfigSpec.BooleanValue useEnergy; private final ForgeConfigSpec.LongValue energyCapacity; private final ForgeConfigSpec.LongValue openEnergyUsage; private final ForgeConfigSpec.LongValue extractEnergyUsage; @@ -647,7 +646,6 @@ private class WirelessGridEntryImpl implements WirelessGridEntry { WirelessGridEntryImpl() { builder.push("wirelessGrid"); - useEnergy = builder.comment("Whether the Wireless Grid uses energy").define("useEnergy", true); energyCapacity = builder.comment("The energy capacity of the Wireless Grid") .defineInRange("energyCapacity", DefaultEnergyUsage.WIRELESS_GRID_CAPACITY, 0, Long.MAX_VALUE); openEnergyUsage = builder.comment("The energy used by the Wireless Grid to open") @@ -659,10 +657,6 @@ private class WirelessGridEntryImpl implements WirelessGridEntry { builder.pop(); } - public boolean getUseEnergy() { - return useEnergy.get(); - } - public long getEnergyCapacity() { return energyCapacity.get(); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index 95056229a..1d68050dd 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -1,10 +1,11 @@ package com.refinedmods.refinedstorage2.platform.forge; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.blockentity.EnergyBlockEntity; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItem; import com.refinedmods.refinedstorage2.platform.common.AbstractModInitializer; -import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.block.AbstractBaseBlock; -import com.refinedmods.refinedstorage2.platform.common.block.entity.ControllerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.diskdrive.AbstractDiskDriveBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.iface.InterfaceBlockEntity; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntityTypeFactory; @@ -14,14 +15,12 @@ import com.refinedmods.refinedstorage2.platform.common.content.MenuTypeFactory; import com.refinedmods.refinedstorage2.platform.common.content.RegistryCallback; import com.refinedmods.refinedstorage2.platform.common.internal.network.node.iface.externalstorage.InterfacePlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.common.item.CreativeItemEnergyProvider; import com.refinedmods.refinedstorage2.platform.common.item.RegulatorUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.item.WirelessGridItem; import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; import com.refinedmods.refinedstorage2.platform.forge.block.entity.ForgeDiskDriveBlockEntity; -import com.refinedmods.refinedstorage2.platform.forge.integration.energy.ForgeEnergyCapabilityProvider; -import com.refinedmods.refinedstorage2.platform.forge.integration.energy.ForgeEnergyItemEnergyProvider; +import com.refinedmods.refinedstorage2.platform.forge.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.FluidGridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.FluidGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.ItemGridExtractionStrategy; @@ -37,6 +36,7 @@ import java.util.Arrays; import java.util.HashSet; +import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import javax.annotation.Nonnull; @@ -45,7 +45,6 @@ import net.minecraft.core.Direction; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.core.registries.Registries; -import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.Container; @@ -127,6 +126,7 @@ public ModInitializer() { FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onRegister); MinecraftForge.EVENT_BUS.addListener(this::registerWrenchingEvent); MinecraftForge.EVENT_BUS.addGenericListener(BlockEntity.class, this::registerBlockEntityCapabilities); + MinecraftForge.EVENT_BUS.addGenericListener(ItemStack.class, this::registerItemStackCapabilities); } private void registerAdditionalGridInsertionStrategyFactories() { @@ -194,23 +194,15 @@ public boolean shouldCauseReequipAnimation(final ItemStack oldStack, return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } }, - () -> new WirelessGridItem(new ForgeEnergyItemEnergyProvider()) { + () -> new WirelessGridItem(false) { @Override public boolean shouldCauseReequipAnimation(final ItemStack oldStack, final ItemStack newStack, final boolean slotChanged) { return AbstractModInitializer.allowNbtUpdateAnimation(oldStack, newStack); } - - @Override - public ICapabilityProvider initCapabilities(final ItemStack stack, @Nullable final CompoundTag tag) { - return new ForgeEnergyCapabilityProvider( - stack, - (int) Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity() - ); - } }, - () -> new WirelessGridItem(CreativeItemEnergyProvider.INSTANCE) { + () -> new WirelessGridItem(true) { @Override public boolean shouldCauseReequipAnimation(final ItemStack oldStack, final ItemStack newStack, @@ -302,8 +294,8 @@ public void registerWrenchingEvent(final PlayerInteractEvent.RightClickBlock e) @SubscribeEvent public void registerBlockEntityCapabilities(final AttachCapabilitiesEvent e) { - if (e.getObject() instanceof ControllerBlockEntity controllerBlockEntity) { - registerControllerEnergy(e, controllerBlockEntity); + if (e.getObject() instanceof EnergyBlockEntity energyBlockEntity) { + registerEnergyBlockEntity(e, energyBlockEntity); } if (e.getObject() instanceof AbstractDiskDriveBlockEntity diskDriveBlockEntity) { registerItemHandler(e, diskDriveBlockEntity, AbstractDiskDriveBlockEntity::getDiskInventory); @@ -352,17 +344,17 @@ public LazyOptional getCapability(final Capability cap, @Nullable fina }); } - private void registerControllerEnergy(final AttachCapabilitiesEvent e, - final ControllerBlockEntity controllerBlockEntity) { - final LazyOptional capability = LazyOptional - .of(() -> (IEnergyStorage) controllerBlockEntity.getEnergyStorage()); + private void registerEnergyBlockEntity(final AttachCapabilitiesEvent e, + final EnergyBlockEntity energyBlockEntity) { + final LazyOptional capability = LazyOptional.of( + () -> new EnergyStorageAdapter(energyBlockEntity.getEnergyStorage()) + ); e.addCapability(createIdentifier("energy"), new ICapabilityProvider() { @Override @Nonnull public LazyOptional getCapability(final Capability cap, @Nullable final Direction side) { - if (cap == ForgeCapabilities.ENERGY - && controllerBlockEntity.getEnergyStorage() instanceof IEnergyStorage) { + if (cap == ForgeCapabilities.ENERGY) { return capability.cast(); } return LazyOptional.empty(); @@ -370,6 +362,26 @@ public LazyOptional getCapability(final Capability cap, }); } + @SubscribeEvent + public void registerItemStackCapabilities(final AttachCapabilitiesEvent e) { + if (e.getObject().getItem() instanceof EnergyItem energyItem) { + final Optional energyStorage = energyItem.createEnergyStorage(e.getObject()); + final LazyOptional forgeEnergyStorage = energyStorage.map( + storage -> LazyOptional.of(() -> (IEnergyStorage) new EnergyStorageAdapter(storage)) + ).orElse(LazyOptional.empty()); + e.addCapability(createIdentifier("energy"), new ICapabilityProvider() { + @Override + public LazyOptional getCapability(final Capability cap, + @Nullable final Direction side) { + if (cap == ForgeCapabilities.ENERGY) { + return forgeEnergyStorage.cast(); + } + return LazyOptional.empty(); + } + }); + } + } + @SubscribeEvent public void onServerTick(final TickEvent.ServerTickEvent e) { if (e.phase == TickEvent.Phase.START) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java index af8d41bb1..56ea8b0f1 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java @@ -3,18 +3,16 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.network.impl.energy.InfiniteEnergyStorage; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; -import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketAmountFormatting; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; import com.refinedmods.refinedstorage2.platform.forge.containermenu.ContainerTransferDestination; -import com.refinedmods.refinedstorage2.platform.forge.integration.energy.ControllerForgeEnergy; +import com.refinedmods.refinedstorage2.platform.forge.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.ItemGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.view.ForgeFluidGridResourceFactory; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.view.ForgeItemGridResourceFactory; @@ -173,21 +171,6 @@ public Optional convertToBucket(final FluidResource fluidResource) { }); } - @Override - public EnergyStorage createEnergyStorage(final ControllerType controllerType, final Runnable listener) { - return switch (controllerType) { - case NORMAL -> new ControllerForgeEnergy(listener); - case CREATIVE -> new InfiniteEnergyStorage(); - }; - } - - @Override - public void setEnergy(final EnergyStorage energyStorage, final long stored) { - if (energyStorage instanceof ControllerForgeEnergy controllerForgeEnergy) { - controllerForgeEnergy.setSilently(stored); - } - } - @Override public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { return new TransferManager(containerMenu, ContainerTransferDestination::new); @@ -337,4 +320,12 @@ public void renderTooltip(final GuiGraphics graphics, DefaultTooltipPositioner.INSTANCE ); } + + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return stack.getCapability(ForgeCapabilities.ENERGY) + .filter(EnergyStorageAdapter.class::isInstance) + .map(EnergyStorageAdapter.class::cast) + .map(EnergyStorageAdapter::getEnergyStorage); + } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ControllerForgeEnergy.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ControllerForgeEnergy.java deleted file mode 100644 index 8dcdc92ee..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ControllerForgeEnergy.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.integration.energy; - -import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.api.network.impl.energy.EnergyStorageImpl; -import com.refinedmods.refinedstorage2.platform.common.Platform; - -import net.minecraftforge.energy.IEnergyStorage; - -public class ControllerForgeEnergy extends EnergyStorageImpl implements IEnergyStorage { - private final Runnable listener; - - public ControllerForgeEnergy(final Runnable listener) { - super((int) Platform.INSTANCE.getConfig().getController().getEnergyCapacity()); - this.listener = listener; - } - - public void setSilently(final long amount) { - this.extract(Long.MAX_VALUE, Action.EXECUTE); - this.receive(amount, Action.EXECUTE); - } - - @Override - public long receive(final long amount, final Action action) { - final long received = super.receive(amount, action); - if (received > 0 && action == Action.EXECUTE) { - listener.run(); - } - return received; - } - - @Override - public long extract(final long amount, final Action action) { - final long extracted = super.extract(amount, action); - if (extracted > 0 && action == Action.EXECUTE) { - listener.run(); - } - return extracted; - } - - @Override - public int receiveEnergy(final int maxReceive, final boolean simulate) { - return (int) receive(maxReceive, simulate ? Action.SIMULATE : Action.EXECUTE); - } - - @Override - public int extractEnergy(final int maxExtract, final boolean simulate) { - return 0; - } - - @Override - public int getEnergyStored() { - return (int) getStored(); - } - - @Override - public int getMaxEnergyStored() { - return (int) getCapacity(); - } - - @Override - public boolean canExtract() { - return false; - } - - @Override - public boolean canReceive() { - return true; - } -} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyCapabilityProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyCapabilityProvider.java deleted file mode 100644 index 7c72772d0..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyCapabilityProvider.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.integration.energy; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.capabilities.Capability; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.common.capabilities.ICapabilityProvider; -import net.minecraftforge.common.util.LazyOptional; -import net.minecraftforge.energy.IEnergyStorage; - -public class ForgeEnergyCapabilityProvider implements ICapabilityProvider { - private final LazyOptional capability; - - public ForgeEnergyCapabilityProvider(final ItemStack stack, final int energyCapacity) { - this.capability = LazyOptional.of(() -> new ItemEnergyStorage(stack, energyCapacity)); - } - - @Nonnull - @Override - public LazyOptional getCapability(@Nonnull final Capability cap, @Nullable final Direction direction) { - if (cap == ForgeCapabilities.ENERGY) { - return capability.cast(); - } - return LazyOptional.empty(); - } -} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyItemEnergyProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyItemEnergyProvider.java deleted file mode 100644 index ed0e2c866..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ForgeEnergyItemEnergyProvider.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.integration.energy; - -import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; -import com.refinedmods.refinedstorage2.platform.common.item.ItemEnergyProvider; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.common.capabilities.ForgeCapabilities; -import net.minecraftforge.energy.IEnergyStorage; - -public class ForgeEnergyItemEnergyProvider implements ItemEnergyProvider { - @Override - public boolean isEnabled() { - return Platform.INSTANCE.getConfig().getWirelessGrid().getUseEnergy(); - } - - @Override - public long getStored(final ItemStack stack) { - return stack.getCapability(ForgeCapabilities.ENERGY).map(IEnergyStorage::getEnergyStored).orElse(0); - } - - @Override - public long getCapacity(final ItemStack stack) { - return stack.getCapability(ForgeCapabilities.ENERGY).map(IEnergyStorage::getMaxEnergyStored).orElse(0); - } - - @Override - public void drain(final Player player, final PlayerSlotReference slotReference, final long amount) { - if (!isEnabled()) { - return; - } - final ItemStack stack = player.getInventory().getItem(slotReference.getSlotIndex()); - stack.getCapability(ForgeCapabilities.ENERGY).ifPresent( - energyStorage -> energyStorage.extractEnergy((int) amount, false) - ); - } - - @Override - public ItemStack getAtCapacity(final ItemStack stack) { - final ItemStack copied = stack.copy(); - copied.getCapability(ForgeCapabilities.ENERGY).ifPresent( - energyStorage -> energyStorage.receiveEnergy(energyStorage.getMaxEnergyStored(), false) - ); - return copied; - } -} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ItemEnergyStorage.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ItemEnergyStorage.java deleted file mode 100644 index 21396b5de..000000000 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/energy/ItemEnergyStorage.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.forge.integration.energy; - -import net.minecraft.world.item.ItemStack; -import net.minecraftforge.energy.EnergyStorage; - -public class ItemEnergyStorage extends EnergyStorage { - private static final String TAG_ENERGY = "energy"; - - private final ItemStack stack; - - public ItemEnergyStorage(final ItemStack stack, final int capacity) { - super(capacity, capacity, capacity); - this.stack = stack; - if (stack.getTag() != null) { - this.energy = stack.getTag().getInt(TAG_ENERGY); - } - } - - @Override - public int receiveEnergy(final int maxReceive, final boolean simulate) { - final int received = super.receiveEnergy(maxReceive, simulate); - if (received > 0 && !simulate) { - stack.getOrCreateTag().putInt(TAG_ENERGY, getEnergyStored()); - } - return received; - } - - @Override - public int extractEnergy(final int maxExtract, final boolean simulate) { - final int extracted = super.extractEnergy(maxExtract, simulate); - if (extracted > 0 && !simulate) { - stack.getOrCreateTag().putInt(TAG_ENERGY, getEnergyStored()); - } - return extracted; - } -} - diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/EnergyStorageAdapter.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/EnergyStorageAdapter.java new file mode 100644 index 000000000..77edd7796 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/EnergyStorageAdapter.java @@ -0,0 +1,48 @@ +package com.refinedmods.refinedstorage2.platform.forge.internal.energy; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; + +import net.minecraftforge.energy.IEnergyStorage; + +public class EnergyStorageAdapter implements IEnergyStorage { + private final EnergyStorage energyStorage; + + public EnergyStorageAdapter(final EnergyStorage energyStorage) { + this.energyStorage = energyStorage; + } + + public EnergyStorage getEnergyStorage() { + return energyStorage; + } + + @Override + public int receiveEnergy(final int maxReceive, final boolean simulate) { + return (int) energyStorage.receive(maxReceive, simulate ? Action.SIMULATE : Action.EXECUTE); + } + + @Override + public int extractEnergy(final int maxExtract, final boolean simulate) { + return (int) energyStorage.extract(maxExtract, simulate ? Action.SIMULATE : Action.EXECUTE); + } + + @Override + public int getEnergyStored() { + return (int) energyStorage.getStored(); + } + + @Override + public int getMaxEnergyStored() { + return (int) energyStorage.getCapacity(); + } + + @Override + public boolean canExtract() { + return false; + } + + @Override + public boolean canReceive() { + return true; + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/package-info.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/package-info.java similarity index 73% rename from refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/package-info.java rename to refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/package-info.java index 01c3b3607..372ae8fb0 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/energy/package-info.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/internal/energy/package-info.java @@ -1,6 +1,6 @@ @ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault -package com.refinedmods.refinedstorage2.platform.fabric.integration.energy; +package com.refinedmods.refinedstorage2.platform.forge.internal.energy; import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; From fad45e01e907fb3ac7da58b5c7b59e368a3539f4 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Tue, 29 Aug 2023 22:39:05 +0200 Subject: [PATCH 02/11] refactor: bind energy storage to controller item Previously, item energy used to be shoehorned in by checking the block entity nbt. However, we want to be able to actually recharge the controller item, so expose an energy capability. --- CHANGELOG.md | 4 + .../api/item/AbstractEnergyBlockItem.java | 78 ++++++++++++++ .../loot_tables/blocks/black_controller.json | 5 + .../loot_tables/blocks/blue_controller.json | 5 + .../loot_tables/blocks/brown_controller.json | 5 + .../loot_tables/blocks/controller.json | 5 + .../loot_tables/blocks/cyan_controller.json | 5 + .../loot_tables/blocks/gray_controller.json | 5 + .../loot_tables/blocks/green_controller.json | 5 + .../blocks/light_gray_controller.json | 5 + .../loot_tables/blocks/lime_controller.json | 5 + .../blocks/magenta_controller.json | 5 + .../loot_tables/blocks/orange_controller.json | 5 + .../loot_tables/blocks/pink_controller.json | 5 + .../loot_tables/blocks/purple_controller.json | 5 + .../loot_tables/blocks/red_controller.json | 5 + .../loot_tables/blocks/white_controller.json | 5 + .../loot_tables/blocks/yellow_controller.json | 5 + .../common/AbstractModInitializer.java | 9 +- .../common/block/AbstractStorageBlock.java | 60 +---------- .../block/entity/ControllerBlockEntity.java | 28 +---- .../common/content/CreativeModeTabItems.java | 4 +- .../common/content/LootFunctions.java | 14 ++- .../item/block/ControllerBlockItem.java | 100 +++++++----------- .../block/CreativeControllerBlockItem.java | 13 +-- .../common/loot/EnergyLootItemFunction.java | 32 ++++++ .../EnergyLootItemFunctionSerializer.java | 22 ++++ .../loot/StorageBlockLootItemFunction.java | 44 ++++++++ ...torageBlockLootItemFunctionSerializer.java | 22 ++++ .../platform/common/loot/package-info.java | 7 ++ .../ControllerModelPredicateProvider.java | 9 +- .../platform/fabric/ModInitializerImpl.java | 2 +- .../rei/RefinedStorageREIClientPlugin.java | 5 +- .../forge/datagen/loot/BlockDropProvider.java | 6 +- .../rei/RefinedStorageREIClientPlugin.java | 14 ++- 35 files changed, 382 insertions(+), 171 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunction.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunctionSerializer.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunction.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunctionSerializer.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/package-info.java diff --git a/CHANGELOG.md b/CHANGELOG.md index d55e9adfc..5888ad433 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Changed + +- You can now recharge the Controller in item form. + ### Removed - The `useEnergy` config option for the Wireless Grid. If you do not wish to use energy, use the diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java new file mode 100644 index 000000000..4323d7e85 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java @@ -0,0 +1,78 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; +import javax.annotation.Nullable; + +import net.minecraft.ChatFormatting; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; + +public abstract class AbstractEnergyBlockItem extends BlockItem implements EnergyItem { + protected AbstractEnergyBlockItem(final Block block, final Properties properties) { + super(block, properties); + } + + @Override + public void appendHoverText( + final ItemStack stack, + @Nullable final Level level, + final List lines, + final TooltipFlag flag + ) { + super.appendHoverText(stack, level, lines, flag); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> { + final long stored = energyStorage.getStored(); + final long capacity = energyStorage.getCapacity(); + final double pct = stored / (double) capacity; + lines.add(PlatformApi.INSTANCE.createStoredWithCapacityTranslation(stored, capacity, pct) + .withStyle(ChatFormatting.GRAY)); + }); + } + + @Override + public boolean isBarVisible(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).isPresent(); + } + + @Override + public int getBarWidth(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> (int) Math.round( + (energyStorage.getStored() / (double) energyStorage.getCapacity()) * 13D + )).orElse(0); + } + + @Override + public int getBarColor(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> Mth.hsvToRgb( + Math.max(0.0F, (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) / 3.0F, + 1.0F, + 1.0F + )).orElse(0); + } + + public ItemStack createAtEnergyCapacity() { + final ItemStack stack = new ItemStack(this); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> energyStorage.receive( + energyStorage.getCapacity(), + Action.EXECUTE + )); + return stack; + } + + public static Stream createAllAtEnergyCapacity(final List> items) { + return items.stream().map(Supplier::get) + .filter(AbstractEnergyBlockItem.class::isInstance) + .map(AbstractEnergyBlockItem.class::cast) + .map(AbstractEnergyBlockItem::createAtEnergyCapacity); + } +} diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/black_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/black_controller.json index 70807a0ef..c3b8bf3b0 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/black_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/black_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/blue_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/blue_controller.json index 7d8afedaf..0bbd4161a 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/blue_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/blue_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/brown_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/brown_controller.json index db36bcd78..6f7131de0 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/brown_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/brown_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/controller.json index 7abe99bcd..af54b8c3a 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/cyan_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/cyan_controller.json index 821fe25c8..d892078dc 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/cyan_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/cyan_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/gray_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/gray_controller.json index 67db61c04..56b7bec33 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/gray_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/gray_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/green_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/green_controller.json index 82c2ac254..c09b4bceb 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/green_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/green_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/light_gray_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/light_gray_controller.json index 76b2e54cd..516f38265 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/light_gray_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/light_gray_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/lime_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/lime_controller.json index a69db2087..5a14808ad 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/lime_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/lime_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/magenta_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/magenta_controller.json index 880a638e1..1e6f015e8 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/magenta_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/magenta_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/orange_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/orange_controller.json index 05afcdd44..af69c7994 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/orange_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/orange_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/pink_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/pink_controller.json index 20cb20772..4b750c25b 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/pink_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/pink_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/purple_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/purple_controller.json index 57978bd76..cca450e42 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/purple_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/purple_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/red_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/red_controller.json index 57ae4b5b2..bdd81d2d7 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/red_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/red_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/white_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/white_controller.json index d165a7996..682dd8150 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/white_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/white_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/yellow_controller.json b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/yellow_controller.json index dccfa872c..3497684bf 100644 --- a/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/yellow_controller.json +++ b/refinedstorage2-platform-common/src/generated/resources/data/refinedstorage2/loot_tables/blocks/yellow_controller.json @@ -1,4 +1,9 @@ { + "functions": [ + { + "function": "refinedstorage2:energy" + } + ], "pools": [ { "bonus_rolls": 0.0, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index 56e152038..d8eb8065c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -7,7 +7,6 @@ import com.refinedmods.refinedstorage2.api.network.impl.component.StorageNetworkComponentImpl; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.PlatformApiProxy; -import com.refinedmods.refinedstorage2.platform.common.block.AbstractStorageBlock; import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.block.DiskDriveBlock; import com.refinedmods.refinedstorage2.platform.common.block.FluidStorageBlock; @@ -84,6 +83,8 @@ import com.refinedmods.refinedstorage2.platform.common.item.block.FluidStorageBlockBlockItem; import com.refinedmods.refinedstorage2.platform.common.item.block.ItemStorageBlockBlockItem; import com.refinedmods.refinedstorage2.platform.common.item.block.SimpleBlockItem; +import com.refinedmods.refinedstorage2.platform.common.loot.EnergyLootItemFunctionSerializer; +import com.refinedmods.refinedstorage2.platform.common.loot.StorageBlockLootItemFunctionSerializer; import com.refinedmods.refinedstorage2.platform.common.recipe.UpgradeWithEnchantedBookRecipeSerializer; import java.util.Optional; @@ -603,7 +604,11 @@ protected final void registerMenus(final RegistryCallback> callback, protected final void registerLootFunctions(final RegistryCallback callback) { LootFunctions.INSTANCE.setStorageBlock(callback.register( STORAGE_BLOCK, - () -> new LootItemFunctionType(new AbstractStorageBlock.StorageBlockLootItemFunctionSerializer()) + () -> new LootItemFunctionType(new StorageBlockLootItemFunctionSerializer()) + )); + LootFunctions.INSTANCE.setEnergy(callback.register( + createIdentifier("energy"), + () -> new LootItemFunctionType(new EnergyLootItemFunctionSerializer()) )); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractStorageBlock.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractStorageBlock.java index 7bf6b4629..9f7aed88c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractStorageBlock.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/AbstractStorageBlock.java @@ -1,36 +1,19 @@ package com.refinedmods.refinedstorage2.platform.common.block; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.AbstractStorageBlockBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.ticker.AbstractBlockEntityTicker; -import com.refinedmods.refinedstorage2.platform.common.content.LootFunctions; -import java.util.UUID; import javax.annotation.Nullable; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonObject; -import com.google.gson.JsonSerializationContext; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.EntityBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityTicker; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.Serializer; -import net.minecraft.world.level.storage.loot.functions.LootItemFunction; -import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public abstract class AbstractStorageBlock> - extends AbstractBaseBlock +public abstract class AbstractStorageBlock> extends AbstractBaseBlock implements EntityBlock { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractStorageBlock.class); - private final AbstractBlockEntityTicker ticker; protected AbstractStorageBlock(final Properties properties, final AbstractBlockEntityTicker ticker) { @@ -45,45 +28,4 @@ public BlockEntityTicker getTicker(final Level level, final BlockEntityType type) { return ticker.get(level, type); } - - public static class StorageBlockLootItemFunction implements LootItemFunction { - @Override - public LootItemFunctionType getType() { - return LootFunctions.INSTANCE.getStorageBlock(); - } - - @Override - public ItemStack apply(final ItemStack stack, final LootContext lootContext) { - final BlockEntity blockEntity = lootContext.getParam(LootContextParams.BLOCK_ENTITY); - if (blockEntity instanceof AbstractStorageBlockBlockEntity storageBlockEntity) { - apply(stack, storageBlockEntity); - } - return stack; - } - - private void apply(final ItemStack stack, final AbstractStorageBlockBlockEntity storageBlockEntity) { - final UUID storageId = storageBlockEntity.getStorageId(); - if (storageId != null) { - LOGGER.debug("Transferred storage {} at {} to stack", storageId, storageBlockEntity.getBlockPos()); - PlatformApi.INSTANCE.getStorageContainerItemHelper().setId(stack, storageId); - } else { - LOGGER.warn("Storage block {} has no associated storage ID!", storageBlockEntity.getBlockPos()); - } - } - } - - public static class StorageBlockLootItemFunctionSerializer implements Serializer { - @Override - public void serialize(final JsonObject jsonObject, - final LootItemFunction lootItemFunction, - final JsonSerializationContext jsonSerializationContext) { - // nothing to do - } - - @Override - public LootItemFunction deserialize(final JsonObject jsonObject, - final JsonDeserializationContext jsonDeserializationContext) { - return new StorageBlockLootItemFunction(); - } - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index be60d8805..5f760ea06 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -13,8 +13,6 @@ import com.refinedmods.refinedstorage2.platform.common.internal.energy.CreativeEnergyStorage; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; -import javax.annotation.Nullable; - import com.google.common.util.concurrent.RateLimiter; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; @@ -66,26 +64,6 @@ private static BlockEntityType getBlockEntityType(final C : BlockEntities.INSTANCE.getController(); } - public static long getStored(final CompoundTag tag) { - return tag.contains(TAG_STORED) ? tag.getLong(TAG_STORED) : 0; - } - - public static void setStored(final CompoundTag tag, final long stored) { - tag.putLong(TAG_STORED, stored); - } - - public static long getCapacity(final CompoundTag tag) { - return tag.contains(TAG_CAPACITY) ? tag.getLong(TAG_CAPACITY) : 0; - } - - public static void setCapacity(final CompoundTag tag, final long capacity) { - tag.putLong(TAG_CAPACITY, capacity); - } - - public static boolean hasEnergy(@Nullable final CompoundTag tag) { - return tag != null && tag.contains(TAG_STORED) && tag.contains(TAG_CAPACITY); - } - public void updateEnergyTypeInLevel(final BlockState state) { final ControllerEnergyType currentEnergyType = ControllerEnergyType.ofState(getNode().getState()); final ControllerEnergyType inLevelEnergyType = state.getValue(ControllerBlock.ENERGY_TYPE); @@ -122,7 +100,7 @@ private void saveRenderingInfo(final CompoundTag tag) { public void load(final CompoundTag tag) { super.load(tag); if (tag.contains(TAG_STORED)) { - energyStorage.receive(tag.getLong(TAG_STORED), Action.EXECUTE); + loadEnergy(tag.getLong(TAG_STORED)); } } @@ -157,4 +135,8 @@ public long getActualCapacity() { public EnergyStorage getEnergyStorage() { return energyStorage; } + + public void loadEnergy(final long stored) { + energyStorage.receive(stored, Action.EXECUTE); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java index 0fb395830..0fe1369f1 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java @@ -1,9 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.content; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.item.ProcessorItem; -import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; import java.util.Arrays; import java.util.function.Consumer; @@ -24,7 +24,7 @@ public static void append(final Consumer consumer) { private static void appendBlocks(final Consumer consumer) { final Consumer itemConsumer = item -> consumer.accept(new ItemStack(item)); Items.INSTANCE.getControllers().stream().map(Supplier::get).forEach(itemConsumer); - ControllerBlockItem.getAllAtCapacity().forEach(consumer); + AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()).forEach(consumer); Items.INSTANCE.getCreativeControllers().stream().map(Supplier::get).forEach(itemConsumer); Items.INSTANCE.getCables().stream().map(Supplier::get).forEach(itemConsumer); Items.INSTANCE.getImporters().stream().map(Supplier::get).forEach(itemConsumer); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/LootFunctions.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/LootFunctions.java index feb7c61ac..c89eedec0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/LootFunctions.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/LootFunctions.java @@ -11,6 +11,8 @@ public final class LootFunctions { @Nullable private Supplier storageBlock; + @Nullable + private Supplier energy; private LootFunctions() { } @@ -19,7 +21,15 @@ public LootItemFunctionType getStorageBlock() { return Objects.requireNonNull(storageBlock).get(); } - public void setStorageBlock(final Supplier storageBlockSupplier) { - this.storageBlock = storageBlockSupplier; + public void setStorageBlock(final Supplier supplier) { + this.storageBlock = supplier; + } + + public LootItemFunctionType getEnergy() { + return Objects.requireNonNull(energy).get(); + } + + public void setEnergy(final Supplier supplier) { + this.energy = supplier; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java index fbd16b44f..b52ab71d8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java @@ -1,100 +1,74 @@ package com.refinedmods.refinedstorage2.platform.common.item.block; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import com.refinedmods.refinedstorage2.api.network.impl.energy.EnergyStorageImpl; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.block.entity.ControllerBlockEntity; -import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; -import com.refinedmods.refinedstorage2.platform.common.content.Items; -import java.util.List; import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Stream; import javax.annotation.Nullable; -import net.minecraft.ChatFormatting; -import net.minecraft.nbt.CompoundTag; +import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; -import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createStoredWithCapacityTranslation; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -// TODO: Use cap here. // TODO: Make network bound item api accessible. -public class ControllerBlockItem extends CreativeControllerBlockItem { - public ControllerBlockItem(final Block block, final Component displayName) { - super(block, displayName); - } - - public static float getPercentFull(final ItemStack stack) { - final CompoundTag tag = getBlockEntityData(stack); - if (tag == null) { - return 1; - } - final long stored = ControllerBlockEntity.getStored(tag); - final long capacity = ControllerBlockEntity.getCapacity(tag); - if (capacity == 0) { - return 1; - } - return (float) stored / (float) capacity; - } +public class ControllerBlockItem extends AbstractEnergyBlockItem { + private final Component name; - public ItemStack getAtCapacity() { - final long capacity = Platform.INSTANCE.getConfig().getController().getEnergyCapacity(); - final ItemStack result = new ItemStack(this); - final CompoundTag blockEntityData = new CompoundTag(); - ControllerBlockEntity.setStored(blockEntityData, capacity); - ControllerBlockEntity.setCapacity(blockEntityData, capacity); - setBlockEntityData(result, BlockEntities.INSTANCE.getController(), blockEntityData); - return result; - } - - public static Stream getAllAtCapacity() { - return Items.INSTANCE.getControllers().stream() - .map(Supplier::get) - .filter(ControllerBlockItem.class::isInstance) - .map(ControllerBlockItem.class::cast) - .map(ControllerBlockItem::getAtCapacity); + public ControllerBlockItem(final Block block, final Component displayName) { + super(block, new Item.Properties().stacksTo(1)); + this.name = displayName; } @Override - public Optional getTooltipImage(final ItemStack stack) { - return Optional.of(new HelpTooltipComponent(createTranslation("item", "controller.help"))); + public Component getDescription() { + return name; } @Override - public boolean isBarVisible(final ItemStack stack) { - return ControllerBlockEntity.hasEnergy(getBlockEntityData(stack)); + public Component getName(final ItemStack stack) { + return name; } @Override - public int getBarWidth(final ItemStack stack) { - return Math.round(getPercentFull(stack) * 13F); + public Optional getTooltipImage(final ItemStack stack) { + return Optional.of(new HelpTooltipComponent(createTranslation("item", "controller.help"))); } @Override - public int getBarColor(final ItemStack stack) { - return Mth.hsvToRgb(Math.max(0.0F, getPercentFull(stack)) / 3.0F, 1.0F, 1.0F); + public Optional createEnergyStorage(final ItemStack stack) { + final EnergyStorage energyStorage = new EnergyStorageImpl( + Platform.INSTANCE.getConfig().getController().getEnergyCapacity() + ); + return Optional.of(PlatformApi.INSTANCE.asItemEnergyStorage(energyStorage, stack)); } @Override - public void appendHoverText(final ItemStack stack, - @Nullable final Level level, - final List tooltip, - final TooltipFlag context) { - super.appendHoverText(stack, level, tooltip, context); - final CompoundTag data = getBlockEntityData(stack); - if (ControllerBlockEntity.hasEnergy(data)) { - final long stored = ControllerBlockEntity.getStored(data); - final long capacity = ControllerBlockEntity.getCapacity(data); - tooltip.add(createStoredWithCapacityTranslation(stored, capacity, getPercentFull(stack)) - .withStyle(ChatFormatting.GRAY)); + protected boolean updateCustomBlockEntityTag( + final BlockPos pos, + final Level level, + @Nullable final Player player, + final ItemStack stack, + final BlockState blockState + ) { + final boolean result = super.updateCustomBlockEntityTag(pos, level, player, stack, blockState); + if (!level.isClientSide() && level.getBlockEntity(pos) instanceof ControllerBlockEntity controllerBlockEntity) { + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent( + energyStorage -> controllerBlockEntity.loadEnergy(energyStorage.getStored()) + ); } + return result; } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/CreativeControllerBlockItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/CreativeControllerBlockItem.java index 4366e69c7..5277f6c32 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/CreativeControllerBlockItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/CreativeControllerBlockItem.java @@ -1,24 +1,13 @@ package com.refinedmods.refinedstorage2.platform.common.item.block; -import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; - -import java.util.Optional; - import net.minecraft.network.chat.Component; -import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; public class CreativeControllerBlockItem extends NamedBlockItem { public CreativeControllerBlockItem(final Block block, final Component name) { - super(block, new Item.Properties().stacksTo(1), name); - } - - @Override - public Optional getTooltipImage(final ItemStack stack) { - return Optional.of(new HelpTooltipComponent(createTranslation("item", "creative_controller.help"))); + super(block, new Item.Properties().stacksTo(1), name, createTranslation("item", "creative_controller.help")); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunction.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunction.java new file mode 100644 index 000000000..823c84a73 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunction.java @@ -0,0 +1,32 @@ +package com.refinedmods.refinedstorage2.platform.common.loot; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.blockentity.EnergyBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.content.LootFunctions; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.functions.LootItemFunction; +import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; + +public class EnergyLootItemFunction implements LootItemFunction { + @Override + public LootItemFunctionType getType() { + return LootFunctions.INSTANCE.getEnergy(); + } + + @Override + public ItemStack apply(final ItemStack stack, final LootContext lootContext) { + final BlockEntity blockEntity = lootContext.getParam(LootContextParams.BLOCK_ENTITY); + if (blockEntity instanceof EnergyBlockEntity energyBlockEntity) { + final long stored = energyBlockEntity.getEnergyStorage().getStored(); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent( + energyStorage -> energyStorage.receive(stored, Action.EXECUTE) + ); + } + return stack; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunctionSerializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunctionSerializer.java new file mode 100644 index 000000000..3360070dd --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/EnergyLootItemFunctionSerializer.java @@ -0,0 +1,22 @@ +package com.refinedmods.refinedstorage2.platform.common.loot; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import net.minecraft.world.level.storage.loot.Serializer; +import net.minecraft.world.level.storage.loot.functions.LootItemFunction; + +public class EnergyLootItemFunctionSerializer implements Serializer { + @Override + public void serialize(final JsonObject jsonObject, + final LootItemFunction lootItemFunction, + final JsonSerializationContext jsonSerializationContext) { + // no op + } + + @Override + public LootItemFunction deserialize(final JsonObject jsonObject, + final JsonDeserializationContext jsonDeserializationContext) { + return new EnergyLootItemFunction(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunction.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunction.java new file mode 100644 index 000000000..7d391f748 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunction.java @@ -0,0 +1,44 @@ +package com.refinedmods.refinedstorage2.platform.common.loot; + +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.AbstractStorageBlockBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.content.LootFunctions; + +import java.util.UUID; + +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.storage.loot.LootContext; +import net.minecraft.world.level.storage.loot.functions.LootItemFunction; +import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType; +import net.minecraft.world.level.storage.loot.parameters.LootContextParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StorageBlockLootItemFunction implements LootItemFunction { + private static final Logger LOGGER = LoggerFactory.getLogger(StorageBlockLootItemFunction.class); + + @Override + public LootItemFunctionType getType() { + return LootFunctions.INSTANCE.getStorageBlock(); + } + + @Override + public ItemStack apply(final ItemStack stack, final LootContext lootContext) { + final BlockEntity blockEntity = lootContext.getParam(LootContextParams.BLOCK_ENTITY); + if (blockEntity instanceof AbstractStorageBlockBlockEntity storageBlockEntity) { + apply(stack, storageBlockEntity); + } + return stack; + } + + private void apply(final ItemStack stack, final AbstractStorageBlockBlockEntity storageBlockEntity) { + final UUID storageId = storageBlockEntity.getStorageId(); + if (storageId != null) { + LOGGER.debug("Transferred storage {} at {} to stack", storageId, storageBlockEntity.getBlockPos()); + PlatformApi.INSTANCE.getStorageContainerItemHelper().setId(stack, storageId); + } else { + LOGGER.warn("Storage block {} has no associated storage ID!", storageBlockEntity.getBlockPos()); + } + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunctionSerializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunctionSerializer.java new file mode 100644 index 000000000..face54610 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/StorageBlockLootItemFunctionSerializer.java @@ -0,0 +1,22 @@ +package com.refinedmods.refinedstorage2.platform.common.loot; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import net.minecraft.world.level.storage.loot.Serializer; +import net.minecraft.world.level.storage.loot.functions.LootItemFunction; + +public class StorageBlockLootItemFunctionSerializer implements Serializer { + @Override + public void serialize(final JsonObject jsonObject, + final LootItemFunction lootItemFunction, + final JsonSerializationContext jsonSerializationContext) { + // no op + } + + @Override + public LootItemFunction deserialize(final JsonObject jsonObject, + final JsonDeserializationContext jsonDeserializationContext) { + return new StorageBlockLootItemFunction(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/package-info.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/package-info.java new file mode 100644 index 000000000..32030996a --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/loot/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.common.loot; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/ControllerModelPredicateProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/ControllerModelPredicateProvider.java index 81e5febe2..550c33368 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/ControllerModelPredicateProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/ControllerModelPredicateProvider.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.render.model; -import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import javax.annotation.Nullable; @@ -15,6 +15,11 @@ public float unclampedCall(final ItemStack stack, @Nullable final ClientLevel level, @Nullable final LivingEntity entity, final int seed) { - return ControllerBlockItem.getPercentFull(stack); + if (stack.getTag() == null) { // for newly created items + return 1; + } + return PlatformApi.INSTANCE.getEnergyStorage(stack) + .map(energyStorage -> (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) + .orElse(1F); } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index e08a7f6e4..3710c3ebb 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -254,7 +254,7 @@ private void registerCreativeModeTab() { createIdentifier("general"), CreativeModeTab.builder(CreativeModeTab.Row.TOP, 0) .title(createTranslation("itemGroup", "general")) - .icon(() -> new ItemStack(Blocks.INSTANCE.getController().getDefault())) + .icon(() -> new ItemStack(Blocks.INSTANCE.getCreativeController().getDefault())) .displayItems((params, output) -> CreativeModeTabItems.append(output::accept)) .build() ); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java index 16c174845..47654f689 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -2,13 +2,13 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.common.block.ColorableBlock; import com.refinedmods.refinedstorage2.platform.common.content.BlockColorMap; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; import com.refinedmods.refinedstorage2.platform.common.content.ContentIds; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.Tags; -import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; import com.refinedmods.refinedstorage2.platform.common.screen.AbstractBaseScreen; import java.util.function.Supplier; @@ -73,7 +73,8 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) registry.group( createIdentifier("fully_charged_controller"), createTranslation("block", "controller.rei_fully_charged"), - ControllerBlockItem.getAllAtCapacity().map(EntryStacks::of).collect(Collectors.toList()) + AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) + .map(EntryStacks::of).collect(Collectors.toList()) ); groupItems( registry, diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/loot/BlockDropProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/loot/BlockDropProvider.java index 74947c19e..799c7985d 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/loot/BlockDropProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/datagen/loot/BlockDropProvider.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.forge.datagen.loot; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; +import com.refinedmods.refinedstorage2.platform.common.loot.EnergyLootItemFunction; import java.util.ArrayList; import java.util.List; @@ -20,7 +21,10 @@ protected void generate() { Blocks.INSTANCE.getCable().forEach((color, id, block) -> dropSelf(block.get())); Blocks.INSTANCE.getGrid().forEach((color, id, block) -> dropSelf(block.get())); Blocks.INSTANCE.getCraftingGrid().forEach((color, id, block) -> dropSelf(block.get())); - Blocks.INSTANCE.getController().forEach((color, id, block) -> dropSelf(block.get())); + Blocks.INSTANCE.getController().forEach((color, id, block) -> add( + block.get(), + createSingleItemTable(block.get()).apply(EnergyLootItemFunction::new) + )); Blocks.INSTANCE.getCreativeController().forEach((color, id, block) -> dropSelf(block.get())); Blocks.INSTANCE.getDetector().forEach((color, id, block) -> dropSelf(block.get())); Blocks.INSTANCE.getConstructor().forEach((color, id, block) -> dropSelf(block.get())); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java index 345c25822..d07b17dd0 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -2,14 +2,16 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.common.block.ColorableBlock; import com.refinedmods.refinedstorage2.platform.common.content.BlockColorMap; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; import com.refinedmods.refinedstorage2.platform.common.content.ContentIds; +import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.Tags; -import com.refinedmods.refinedstorage2.platform.common.item.block.ControllerBlockItem; import com.refinedmods.refinedstorage2.platform.common.screen.AbstractBaseScreen; +import java.util.function.Supplier; import java.util.stream.Collectors; import me.shedaniel.rei.api.client.plugins.REIClientPlugin; @@ -17,7 +19,9 @@ import me.shedaniel.rei.api.client.registry.screen.ExclusionZones; import me.shedaniel.rei.api.client.registry.screen.ScreenRegistry; import me.shedaniel.rei.api.client.registry.transfer.TransferHandlerRegistry; +import me.shedaniel.rei.api.common.entry.comparison.ItemComparatorRegistry; import me.shedaniel.rei.api.common.util.EntryIngredients; +import me.shedaniel.rei.api.common.util.EntryStacks; import me.shedaniel.rei.forge.REIPluginClient; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.TagKey; @@ -47,6 +51,11 @@ public void registerTransferHandlers(final TransferHandlerRegistry registry) { registry.register(new CraftingGridTransferHandler()); } + @Override + public void registerItemComparators(final ItemComparatorRegistry registry) { + Items.INSTANCE.getControllers().stream().map(Supplier::get).forEach(registry::registerNbt); + } + @SuppressWarnings("UnstableApiUsage") @Override public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) { @@ -63,7 +72,8 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) registry.group( createIdentifier("fully_charged_controller"), createTranslation("block", "controller.rei_fully_charged"), - EntryIngredients.ofItemStacks(ControllerBlockItem.getAllAtCapacity().collect(Collectors.toSet())) + AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) + .map(EntryStacks::of).collect(Collectors.toList()) ); groupItems( registry, From 707b8784cbac1f7de89c38ffaa752e223c2f0514 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Fri, 1 Sep 2023 16:50:47 +0200 Subject: [PATCH 03/11] refactor: remove duplication around energy item / block item --- .../platform/api/PlatformApi.java | 5 +- .../platform/api/PlatformApiProxy.java | 13 ++- .../api/item/AbstractEnergyBlockItem.java | 58 ++++++------- .../platform/api/item/AbstractEnergyItem.java | 37 ++------- .../platform/api/item/EnergyItemHelper.java | 25 ++++++ .../platform/common/PlatformApiImpl.java | 15 ++-- .../block/entity/ControllerBlockEntity.java | 6 +- .../common/content/CreativeModeTabItems.java | 4 +- .../internal/item/EnergyItemHelperImpl.java | 82 +++++++++++++++++++ .../common/item/AbstractNetworkBoundItem.java | 3 +- .../item/block/ControllerBlockItem.java | 25 +----- .../rei/RefinedStorageREIClientPlugin.java | 4 +- .../rei/RefinedStorageREIClientPlugin.java | 4 +- 13 files changed, 166 insertions(+), 115 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItemHelper.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/EnergyItemHelperImpl.java diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index b874ce9cc..a9e5da57d 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -19,6 +19,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -75,8 +76,6 @@ public interface PlatformApi { MutableComponent createTranslation(String category, String value, Object... args); - MutableComponent createStoredWithCapacityTranslation(long stored, long capacity, double pct); - ComponentMapFactory getNetworkComponentMapFactory(); PlatformRegistry getGridSynchronizerRegistry(); @@ -143,5 +142,7 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe Optional getEnergyStorage(ItemStack stack); + EnergyItemHelper getEnergyItemHelper(); + EnergyStorage asItemEnergyStorage(EnergyStorage energyStorage, ItemStack stack); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index ac6613efe..d93c0da34 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -19,6 +19,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -121,13 +122,6 @@ public MutableComponent createTranslation(final String category, final String va return ensureLoaded().createTranslation(category, value, args); } - @Override - public MutableComponent createStoredWithCapacityTranslation(final long stored, - final long capacity, - final double pct) { - return ensureLoaded().createStoredWithCapacityTranslation(stored, capacity, pct); - } - @Override public ComponentMapFactory getNetworkComponentMapFactory() { return ensureLoaded().getNetworkComponentMapFactory(); @@ -286,6 +280,11 @@ public Optional getEnergyStorage(final ItemStack stack) { return ensureLoaded().getEnergyStorage(stack); } + @Override + public EnergyItemHelper getEnergyItemHelper() { + return ensureLoaded().getEnergyItemHelper(); + } + @Override public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { return ensureLoaded().asItemEnergyStorage(energyStorage, stack); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java index 4323d7e85..071661175 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java @@ -1,25 +1,24 @@ package com.refinedmods.refinedstorage2.platform.api.item; -import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; - import java.util.List; -import java.util.function.Supplier; -import java.util.stream.Stream; import javax.annotation.Nullable; -import net.minecraft.ChatFormatting; +import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; -import net.minecraft.util.Mth; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; public abstract class AbstractEnergyBlockItem extends BlockItem implements EnergyItem { - protected AbstractEnergyBlockItem(final Block block, final Properties properties) { + private final EnergyItemHelper helper; + + protected AbstractEnergyBlockItem(final Block block, final Properties properties, final EnergyItemHelper helper) { super(block, properties); + this.helper = helper; } @Override @@ -30,49 +29,38 @@ public void appendHoverText( final TooltipFlag flag ) { super.appendHoverText(stack, level, lines, flag); - PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> { - final long stored = energyStorage.getStored(); - final long capacity = energyStorage.getCapacity(); - final double pct = stored / (double) capacity; - lines.add(PlatformApi.INSTANCE.createStoredWithCapacityTranslation(stored, capacity, pct) - .withStyle(ChatFormatting.GRAY)); - }); + helper.addTooltip(stack, lines); } @Override public boolean isBarVisible(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).isPresent(); + return helper.isBarVisible(stack); } @Override public int getBarWidth(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> (int) Math.round( - (energyStorage.getStored() / (double) energyStorage.getCapacity()) * 13D - )).orElse(0); + return helper.getBarWidth(stack); } @Override public int getBarColor(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> Mth.hsvToRgb( - Math.max(0.0F, (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) / 3.0F, - 1.0F, - 1.0F - )).orElse(0); + return helper.getBarColor(stack); } public ItemStack createAtEnergyCapacity() { - final ItemStack stack = new ItemStack(this); - PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> energyStorage.receive( - energyStorage.getCapacity(), - Action.EXECUTE - )); - return stack; + return helper.createAtEnergyCapacity(this); } - public static Stream createAllAtEnergyCapacity(final List> items) { - return items.stream().map(Supplier::get) - .filter(AbstractEnergyBlockItem.class::isInstance) - .map(AbstractEnergyBlockItem.class::cast) - .map(AbstractEnergyBlockItem::createAtEnergyCapacity); + @Override + protected boolean updateCustomBlockEntityTag( + final BlockPos pos, + final Level level, + @Nullable final Player player, + final ItemStack stack, + final BlockState blockState + ) { + final boolean result = super.updateCustomBlockEntityTag(pos, level, player, stack, blockState); + helper.passEnergyToBlockEntity(pos, level, stack); + return result; } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java index 9295c068c..b21dadda4 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java @@ -1,22 +1,20 @@ package com.refinedmods.refinedstorage2.platform.api.item; -import com.refinedmods.refinedstorage2.api.core.Action; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; - import java.util.List; import javax.annotation.Nullable; -import net.minecraft.ChatFormatting; import net.minecraft.network.chat.Component; -import net.minecraft.util.Mth; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; public abstract class AbstractEnergyItem extends Item implements EnergyItem { - protected AbstractEnergyItem(final Properties properties) { + private final EnergyItemHelper helper; + + protected AbstractEnergyItem(final Properties properties, final EnergyItemHelper helper) { super(properties); + this.helper = helper; } @Override @@ -27,42 +25,25 @@ public void appendHoverText( final TooltipFlag flag ) { super.appendHoverText(stack, level, lines, flag); - PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> { - final long stored = energyStorage.getStored(); - final long capacity = energyStorage.getCapacity(); - final double pct = stored / (double) capacity; - lines.add(PlatformApi.INSTANCE.createStoredWithCapacityTranslation(stored, capacity, pct) - .withStyle(ChatFormatting.GRAY)); - }); + helper.addTooltip(stack, lines); } @Override public boolean isBarVisible(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).isPresent(); + return helper.isBarVisible(stack); } @Override public int getBarWidth(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> (int) Math.round( - (energyStorage.getStored() / (double) energyStorage.getCapacity()) * 13D - )).orElse(0); + return helper.getBarWidth(stack); } @Override public int getBarColor(final ItemStack stack) { - return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> Mth.hsvToRgb( - Math.max(0.0F, (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) / 3.0F, - 1.0F, - 1.0F - )).orElse(0); + return helper.getBarColor(stack); } public ItemStack createAtEnergyCapacity() { - final ItemStack stack = new ItemStack(this); - PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> energyStorage.receive( - energyStorage.getCapacity(), - Action.EXECUTE - )); - return stack; + return helper.createAtEnergyCapacity(this); } } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItemHelper.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItemHelper.java new file mode 100644 index 000000000..7d7160f0f --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/EnergyItemHelper.java @@ -0,0 +1,25 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import java.util.List; + +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface EnergyItemHelper { + void addTooltip(ItemStack stack, List lines); + + boolean isBarVisible(ItemStack stack); + + int getBarWidth(ItemStack stack); + + int getBarColor(ItemStack stack); + + ItemStack createAtEnergyCapacity(Item item); + + void passEnergyToBlockEntity(BlockPos pos, Level level, ItemStack stack); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 13f827d08..15caba72e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -23,6 +23,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -44,6 +45,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; +import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; @@ -131,6 +133,7 @@ public class PlatformApiImpl implements PlatformApi { private final Map, ResourceRendering> resourceRenderingMap = new HashMap<>(); private final CompositeWirelessTransmitterRangeModifier wirelessTransmitterRangeModifier = new CompositeWirelessTransmitterRangeModifier(); + private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); @Override public PlatformRegistry> getStorageTypeRegistry() { @@ -217,13 +220,6 @@ public MutableComponent createTranslation(final String category, final String va return IdentifierUtil.createTranslation(category, value, args); } - @Override - public MutableComponent createStoredWithCapacityTranslation(final long stored, - final long capacity, - final double pct) { - return IdentifierUtil.createStoredWithCapacityTranslation(stored, capacity, pct); - } - @Override public ComponentMapFactory getNetworkComponentMapFactory() { return networkComponentMapFactory; @@ -408,6 +404,11 @@ public Optional getEnergyStorage(final ItemStack stack) { return Platform.INSTANCE.getEnergyStorage(stack); } + @Override + public EnergyItemHelper getEnergyItemHelper() { + return energyItemHelper; + } + @Override public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index 5f760ea06..b487a290f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -100,7 +100,7 @@ private void saveRenderingInfo(final CompoundTag tag) { public void load(final CompoundTag tag) { super.load(tag); if (tag.contains(TAG_STORED)) { - loadEnergy(tag.getLong(TAG_STORED)); + energyStorage.receive(tag.getLong(TAG_STORED), Action.EXECUTE); } } @@ -135,8 +135,4 @@ public long getActualCapacity() { public EnergyStorage getEnergyStorage() { return energyStorage; } - - public void loadEnergy(final long stored) { - energyStorage.receive(stored, Action.EXECUTE); - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java index 0fe1369f1..a4803c336 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.content; -import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; +import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.ItemStorageType; import com.refinedmods.refinedstorage2.platform.common.item.ProcessorItem; @@ -24,7 +24,7 @@ public static void append(final Consumer consumer) { private static void appendBlocks(final Consumer consumer) { final Consumer itemConsumer = item -> consumer.accept(new ItemStack(item)); Items.INSTANCE.getControllers().stream().map(Supplier::get).forEach(itemConsumer); - AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()).forEach(consumer); + EnergyItemHelperImpl.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()).forEach(consumer); Items.INSTANCE.getCreativeControllers().stream().map(Supplier::get).forEach(itemConsumer); Items.INSTANCE.getCables().stream().map(Supplier::get).forEach(itemConsumer); Items.INSTANCE.getImporters().stream().map(Supplier::get).forEach(itemConsumer); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/EnergyItemHelperImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/EnergyItemHelperImpl.java new file mode 100644 index 000000000..8faba40e9 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/EnergyItemHelperImpl.java @@ -0,0 +1,82 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.item; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.blockentity.EnergyBlockEntity; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import net.minecraft.ChatFormatting; +import net.minecraft.core.BlockPos; +import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createStoredWithCapacityTranslation; + +public class EnergyItemHelperImpl implements EnergyItemHelper { + @Override + public void addTooltip(final ItemStack stack, final List lines) { + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> { + final long stored = energyStorage.getStored(); + final long capacity = energyStorage.getCapacity(); + final double pct = stored / (double) capacity; + lines.add(createStoredWithCapacityTranslation(stored, capacity, pct).withStyle(ChatFormatting.GRAY)); + }); + } + + @Override + public boolean isBarVisible(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).isPresent(); + } + + @Override + public int getBarWidth(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> (int) Math.round( + (energyStorage.getStored() / (double) energyStorage.getCapacity()) * 13D + )).orElse(0); + } + + @Override + public int getBarColor(final ItemStack stack) { + return PlatformApi.INSTANCE.getEnergyStorage(stack).map(energyStorage -> Mth.hsvToRgb( + Math.max(0.0F, (float) energyStorage.getStored() / (float) energyStorage.getCapacity()) / 3.0F, + 1.0F, + 1.0F + )).orElse(0); + } + + @Override + public ItemStack createAtEnergyCapacity(final Item item) { + final ItemStack stack = item.getDefaultInstance(); + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent(energyStorage -> energyStorage.receive( + energyStorage.getCapacity(), + Action.EXECUTE + )); + return stack; + } + + @Override + public void passEnergyToBlockEntity(final BlockPos pos, final Level level, final ItemStack stack) { + if (level.isClientSide() || !(level.getBlockEntity(pos) instanceof EnergyBlockEntity energyBlockEntity)) { + return; + } + PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent( + energyStorage -> energyBlockEntity.getEnergyStorage().receive(energyStorage.getStored(), Action.EXECUTE) + ); + } + + public static Stream createAllAtEnergyCapacity(final List> items) { + return items.stream().map(Supplier::get) + .filter(AbstractEnergyBlockItem.class::isInstance) + .map(AbstractEnergyBlockItem.class::cast) + .map(AbstractEnergyBlockItem::createAtEnergyCapacity); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java index b6e85b60f..946a14343 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.item; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyItem; import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; @@ -41,7 +42,7 @@ public abstract class AbstractNetworkBoundItem extends AbstractEnergyItem { private static final String TAG_DIMENSION = "dim"; protected AbstractNetworkBoundItem(final Properties properties) { - super(properties); + super(properties, PlatformApi.INSTANCE.getEnergyItemHelper()); } public boolean isBound(final ItemStack stack) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java index b52ab71d8..8bc37651e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java @@ -6,20 +6,14 @@ import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.block.entity.ControllerBlockEntity; import java.util.Optional; -import javax.annotation.Nullable; -import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; @@ -28,7 +22,7 @@ public class ControllerBlockItem extends AbstractEnergyBlockItem { private final Component name; public ControllerBlockItem(final Block block, final Component displayName) { - super(block, new Item.Properties().stacksTo(1)); + super(block, new Item.Properties().stacksTo(1), PlatformApi.INSTANCE.getEnergyItemHelper()); this.name = displayName; } @@ -54,21 +48,4 @@ public Optional createEnergyStorage(final ItemStack stack) { ); return Optional.of(PlatformApi.INSTANCE.asItemEnergyStorage(energyStorage, stack)); } - - @Override - protected boolean updateCustomBlockEntityTag( - final BlockPos pos, - final Level level, - @Nullable final Player player, - final ItemStack stack, - final BlockState blockState - ) { - final boolean result = super.updateCustomBlockEntityTag(pos, level, player, stack, blockState); - if (!level.isClientSide() && level.getBlockEntity(pos) instanceof ControllerBlockEntity controllerBlockEntity) { - PlatformApi.INSTANCE.getEnergyStorage(stack).ifPresent( - energyStorage -> controllerBlockEntity.loadEnergy(energyStorage.getStored()) - ); - } - return result; - } } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java index 47654f689..f11ede392 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -2,13 +2,13 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.common.block.ColorableBlock; import com.refinedmods.refinedstorage2.platform.common.content.BlockColorMap; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; import com.refinedmods.refinedstorage2.platform.common.content.ContentIds; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.Tags; +import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.screen.AbstractBaseScreen; import java.util.function.Supplier; @@ -73,7 +73,7 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) registry.group( createIdentifier("fully_charged_controller"), createTranslation("block", "controller.rei_fully_charged"), - AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) + EnergyItemHelperImpl.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) .map(EntryStacks::of).collect(Collectors.toList()) ); groupItems( diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java index d07b17dd0..95f94a182 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/RefinedStorageREIClientPlugin.java @@ -2,13 +2,13 @@ import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyBlockItem; import com.refinedmods.refinedstorage2.platform.common.block.ColorableBlock; import com.refinedmods.refinedstorage2.platform.common.content.BlockColorMap; import com.refinedmods.refinedstorage2.platform.common.content.Blocks; import com.refinedmods.refinedstorage2.platform.common.content.ContentIds; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.content.Tags; +import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.screen.AbstractBaseScreen; import java.util.function.Supplier; @@ -72,7 +72,7 @@ public void registerCollapsibleEntries(final CollapsibleEntryRegistry registry) registry.group( createIdentifier("fully_charged_controller"), createTranslation("block", "controller.rei_fully_charged"), - AbstractEnergyBlockItem.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) + EnergyItemHelperImpl.createAllAtEnergyCapacity(Items.INSTANCE.getControllers()) .map(EntryStacks::of).collect(Collectors.toList()) ); groupItems( From 2cd3946dab3765a347c259df6159cedd24002fed Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Fri, 1 Sep 2023 17:54:50 +0200 Subject: [PATCH 04/11] refactor: api for network bound items --- .../platform/api/PlatformApi.java | 3 + .../platform/api/PlatformApiProxy.java | 6 + .../api/item/AbstractEnergyBlockItem.java | 2 + .../platform/api/item/AbstractEnergyItem.java | 2 + .../item/AbstractNetworkBoundEnergyItem.java | 49 +++++++++ .../api/item/NetworkBoundItemHelper.java | 26 +++++ .../api/item/NetworkBoundItemSession.java | 16 +++ .../platform/common/PlatformApiImpl.java | 8 ++ .../AbstractBaseContainerMenu.java | 5 +- .../slot/PlayerSlotReference.java | 4 +- .../common/internal/grid/WirelessGrid.java | 53 ++------- .../internal/grid/WirelessGridOperations.java | 14 +-- .../item/NetworkBoundItemHelperImpl.java} | 104 ++++++++---------- .../item/NetworkBoundItemSessionImpl.java} | 48 +++++--- .../common/item/WirelessGridItem.java | 33 +++--- .../item/block/ControllerBlockItem.java | 1 - .../NetworkItemItemPropertyFunction.java | 4 +- 17 files changed, 230 insertions(+), 148 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemSession.java rename refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/{item/AbstractNetworkBoundItem.java => internal/item/NetworkBoundItemHelperImpl.java} (69%) rename refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/{item/NetworkBoundItemContext.java => internal/item/NetworkBoundItemSessionImpl.java} (51%) diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index a9e5da57d..68c119669 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -20,6 +20,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -145,4 +146,6 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe EnergyItemHelper getEnergyItemHelper(); EnergyStorage asItemEnergyStorage(EnergyStorage energyStorage, ItemStack stack); + + NetworkBoundItemHelper getNetworkBoundItemHelper(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index d93c0da34..5411ec11f 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -20,6 +20,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -290,6 +291,11 @@ public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, fina return ensureLoaded().asItemEnergyStorage(energyStorage, stack); } + @Override + public NetworkBoundItemHelper getNetworkBoundItemHelper() { + return ensureLoaded().getNetworkBoundItemHelper(); + } + private PlatformApi ensureLoaded() { if (delegate == null) { throw new IllegalStateException("Platform API not loaded yet"); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java index 071661175..52870ecec 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyBlockItem.java @@ -12,7 +12,9 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; +import org.apiguardian.api.API; +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") public abstract class AbstractEnergyBlockItem extends BlockItem implements EnergyItem { private final EnergyItemHelper helper; diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java index b21dadda4..e4dbd9b95 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractEnergyItem.java @@ -8,7 +8,9 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.level.Level; +import org.apiguardian.api.API; +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") public abstract class AbstractEnergyItem extends Item implements EnergyItem { private final EnergyItemHelper helper; diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java new file mode 100644 index 000000000..46c31e34b --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java @@ -0,0 +1,49 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import java.util.List; +import java.util.Optional; +import javax.annotation.Nullable; + +import net.minecraft.network.chat.Component; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.context.UseOnContext; +import net.minecraft.world.level.Level; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public abstract class AbstractNetworkBoundEnergyItem extends AbstractEnergyItem { + protected final NetworkBoundItemHelper networkBoundItemHelper; + + protected AbstractNetworkBoundEnergyItem(final Properties properties, + final EnergyItemHelper energyItemHelper, + final NetworkBoundItemHelper networkBoundItemHelper) { + super(properties, energyItemHelper); + this.networkBoundItemHelper = networkBoundItemHelper; + } + + @Override + public InteractionResult useOn(final UseOnContext ctx) { + return networkBoundItemHelper.bind(ctx); + } + + @Override + public Optional getTooltipImage(final ItemStack stack) { + return networkBoundItemHelper.getTooltipImage(stack); + } + + @Override + public void appendHoverText(final ItemStack stack, + @Nullable final Level level, + final List tooltip, + final TooltipFlag flag) { + super.appendHoverText(stack, level, tooltip, flag); + networkBoundItemHelper.addTooltip(stack, tooltip); + } + + public boolean isBound(final ItemStack stack) { + return networkBoundItemHelper.isBound(stack); + } +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java new file mode 100644 index 000000000..211398d14 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java @@ -0,0 +1,26 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import java.util.List; +import java.util.Optional; + +import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.inventory.tooltip.TooltipComponent; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.context.UseOnContext; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface NetworkBoundItemHelper { + void addTooltip(ItemStack stack, List lines); + + InteractionResult bind(UseOnContext ctx); + + Optional getTooltipImage(ItemStack stack); + + NetworkBoundItemSession openSession(ItemStack stack, ServerPlayer player, InteractionHand hand); + + boolean isBound(ItemStack stack); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemSession.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemSession.java new file mode 100644 index 000000000..4ecf4618a --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemSession.java @@ -0,0 +1,16 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import com.refinedmods.refinedstorage2.api.network.Network; + +import java.util.Optional; + +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface NetworkBoundItemSession { + Optional resolveNetwork(); + + boolean isActive(); + + void drainEnergy(long amount); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 15caba72e..a6fa5acb4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -24,6 +24,7 @@ import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -46,6 +47,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.item.NetworkBoundItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; @@ -134,6 +136,7 @@ public class PlatformApiImpl implements PlatformApi { private final CompositeWirelessTransmitterRangeModifier wirelessTransmitterRangeModifier = new CompositeWirelessTransmitterRangeModifier(); private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); + private final NetworkBoundItemHelper networkBoundItemHelper = new NetworkBoundItemHelperImpl(); @Override public PlatformRegistry> getStorageTypeRegistry() { @@ -414,4 +417,9 @@ public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { return new ItemEnergyStorage(stack, energyStorage); } + + @Override + public NetworkBoundItemHelper getNetworkBoundItemHelper() { + return networkBoundItemHelper; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java index e503cf6dd..16bce7c38 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java @@ -74,8 +74,7 @@ protected void addPlayerInventory(final Inventory inventory, final int inventory for (int i = 0; i < 9; i++) { final int x = inventoryX + i * 18; final int y = inventoryY + 4 + (3 * 18); - final boolean disabled = disabledPlayerInventorySlot != null - && disabledPlayerInventorySlot.getSlotIndex() == id; + final boolean disabled = disabledPlayerInventorySlot != null && disabledPlayerInventorySlot.isDisabled(id); addSlot(disabled ? new DisabledSlot(inventory, id, x, y) : new Slot(inventory, id, x, y)); id++; } @@ -107,6 +106,6 @@ public void clicked(final int id, final int dragType, final ClickType clickType, private boolean isSwappingDisabledSlotWithNumberKeys(final int dragType, final ClickType clickType) { return disabledPlayerInventorySlot != null && clickType == ClickType.SWAP - && dragType == disabledPlayerInventorySlot.getSlotIndex(); + && disabledPlayerInventorySlot.isDisabled(dragType); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java index 79624d01b..ddcef11e4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java @@ -17,8 +17,8 @@ public ItemStack resolve(final Player player) { return player.getInventory().getItem(slotIndex); } - public int getSlotIndex() { - return slotIndex; + public boolean isDisabled(final int playerSlotIndex) { + return playerSlotIndex == slotIndex; } public void writeToBuf(final ByteBuf buf) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGrid.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGrid.java index 86e5ef01e..c624df9ba 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGrid.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGrid.java @@ -5,12 +5,9 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridOperations; -import com.refinedmods.refinedstorage2.api.network.Network; import com.refinedmods.refinedstorage2.api.network.component.EnergyNetworkComponent; import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; -import com.refinedmods.refinedstorage2.api.network.impl.component.GraphNetworkComponent; import com.refinedmods.refinedstorage2.api.network.impl.node.grid.GridWatchers; -import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.api.storage.Actor; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; @@ -19,68 +16,38 @@ import com.refinedmods.refinedstorage2.api.storage.TrackedResourceAmount; import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannelType; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitter; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; -import com.refinedmods.refinedstorage2.platform.common.item.NetworkBoundItemContext; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; -import net.minecraft.server.MinecraftServer; - public class WirelessGrid implements Grid { - private final MinecraftServer server; - private final NetworkBoundItemContext ctx; + private final NetworkBoundItemSession session; private final GridWatchers watchers; - public WirelessGrid(final MinecraftServer server, final NetworkBoundItemContext ctx) { - this.server = server; - this.ctx = ctx; + public WirelessGrid(final NetworkBoundItemSession session) { + this.session = session; this.watchers = new GridWatchers(PlatformApi.INSTANCE.getStorageChannelTypeRegistry().getAll()); } - private Optional getNetwork() { - if (ctx.getNetworkReference() == null) { - return Optional.empty(); - } - return Optional.ofNullable(server.getLevel(ctx.getNetworkReference().dimensionKey())) - .filter(level -> level.isLoaded(ctx.getNetworkReference().pos())) - .map(level -> level.getBlockEntity(ctx.getNetworkReference().pos())) - .filter(PlatformNetworkNodeContainer.class::isInstance) - .map(PlatformNetworkNodeContainer.class::cast) - .map(PlatformNetworkNodeContainer::getNode) - .map(NetworkNode::getNetwork) - .filter(this::isInRange); - } - - private boolean isInRange(final Network network) { - return network.getComponent(GraphNetworkComponent.class) - .getContainers(WirelessTransmitter.class) - .stream() - .anyMatch(wirelessTransmitter -> wirelessTransmitter.isInRange( - ctx.getPlayerLevel(), - ctx.getPlayerPosition() - )); - } - private Optional getStorage() { - return getNetwork().map(network -> network.getComponent(StorageNetworkComponent.class)); + return session.resolveNetwork().map(network -> network.getComponent(StorageNetworkComponent.class)); } @Override public void addWatcher(final GridWatcher watcher, final Class actorType) { - getNetwork().ifPresent(network -> watchers.addWatcher(watcher, actorType, network)); + session.resolveNetwork().ifPresent(network -> watchers.addWatcher(watcher, actorType, network)); } @Override public void removeWatcher(final GridWatcher watcher) { - getNetwork().ifPresent(network -> watchers.removeWatcher(watcher, network)); + session.resolveNetwork().ifPresent(network -> watchers.removeWatcher(watcher, network)); } @Override @@ -91,10 +58,10 @@ public Storage getItemStorage() { @Override public boolean isActive() { - final boolean networkActive = getNetwork().map( + final boolean networkActive = session.resolveNetwork().map( network -> network.getComponent(EnergyNetworkComponent.class).getStored() > 0 ).orElse(false); - return networkActive && ctx.isActive(); + return networkActive && session.isActive(); } @Override @@ -109,7 +76,7 @@ public GridOperations createOperations(final PlatformStorageChannelType storage.getStorageChannel(storageChannelType)) .map(storageChannel -> storageChannelType.createGridOperations(storageChannel, actor)) - .map(gridOperations -> (GridOperations) new WirelessGridOperations<>(gridOperations, ctx, watchers)) + .map(gridOperations -> (GridOperations) new WirelessGridOperations<>(gridOperations, session, watchers)) .orElseGet(this::createNoOpGridOperations); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGridOperations.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGridOperations.java index 89801bf3f..4b239a038 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGridOperations.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/grid/WirelessGridOperations.java @@ -6,19 +6,19 @@ import com.refinedmods.refinedstorage2.api.network.impl.node.grid.GridWatchers; import com.refinedmods.refinedstorage2.api.storage.ExtractableStorage; import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.item.NetworkBoundItemContext; public class WirelessGridOperations implements GridOperations { private final GridOperations delegate; - private final NetworkBoundItemContext ctx; + private final NetworkBoundItemSession session; private final GridWatchers watchers; public WirelessGridOperations(final GridOperations delegate, - final NetworkBoundItemContext ctx, + final NetworkBoundItemSession session, final GridWatchers watchers) { this.delegate = delegate; - this.ctx = ctx; + this.session = session; this.watchers = watchers; } @@ -45,9 +45,9 @@ public boolean insert(final T resource, } private void drain(final long amount) { - final boolean wasActive = ctx.isActive(); - ctx.drain(amount); - final boolean isActive = ctx.isActive(); + final boolean wasActive = session.isActive(); + session.drainEnergy(amount); + final boolean isActive = session.isActive(); if (wasActive != isActive) { watchers.activeChanged(isActive); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java similarity index 69% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java index 946a14343..029b832ab 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/AbstractNetworkBoundItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java @@ -1,16 +1,14 @@ -package com.refinedmods.refinedstorage2.platform.common.item; +package com.refinedmods.refinedstorage2.platform.common.internal.item; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.item.AbstractEnergyItem; import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import java.util.List; import java.util.Objects; import java.util.Optional; -import java.util.function.Consumer; -import javax.annotation.Nullable; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; @@ -21,17 +19,16 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.level.Level; import net.minecraft.world.level.block.entity.BlockEntity; import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -public abstract class AbstractNetworkBoundItem extends AbstractEnergyItem { +public class NetworkBoundItemHelperImpl implements NetworkBoundItemHelper { private static final MutableComponent UNBOUND = createTranslation("item", "network_item.unbound") .withStyle(ChatFormatting.RED); private static final Component UNBOUND_HELP = createTranslation("item", "network_item.unbound.help"); @@ -41,10 +38,7 @@ public abstract class AbstractNetworkBoundItem extends AbstractEnergyItem { private static final String TAG_Z = "z"; private static final String TAG_DIMENSION = "dim"; - protected AbstractNetworkBoundItem(final Properties properties) { - super(properties, PlatformApi.INSTANCE.getEnergyItemHelper()); - } - + @Override public boolean isBound(final ItemStack stack) { final CompoundTag tag = stack.getTag(); if (tag == null) { @@ -53,37 +47,22 @@ public boolean isBound(final ItemStack stack) { return tag.contains(TAG_X) && tag.contains(TAG_Y) && tag.contains(TAG_Z) && tag.contains(TAG_DIMENSION); } - private Optional getNetworkReference(final ItemStack stack) { - if (!isBound(stack)) { - return Optional.empty(); - } - final CompoundTag tag = Objects.requireNonNull(stack.getTag()); - final int x = tag.getInt(TAG_X); - final int y = tag.getInt(TAG_Y); - final int z = tag.getInt(TAG_Z); - final ResourceLocation dimension = new ResourceLocation(tag.getString(TAG_DIMENSION)); - return Optional.of(new NetworkBoundItemContext.NetworkReference( - ResourceKey.create(Registries.DIMENSION, dimension), - new BlockPos(x, y, z) - )); - } - - protected void tryUse( - final ItemStack stack, - final ServerPlayer player, - final PlayerSlotReference slotReference, - final Consumer contextConsumer - ) { - final Optional networkReference = getNetworkReference(stack); - contextConsumer.accept(new NetworkBoundItemContext( - player, - slotReference, - networkReference.orElse(null) - )); + @Override + public void addTooltip(final ItemStack stack, final List lines) { + getNetworkReference(stack).ifPresentOrElse( + network -> lines.add(createTranslation( + "item", + "network_item.bound_to", + network.pos().getX(), + network.pos().getY(), + network.pos().getZ() + ).withStyle(ChatFormatting.GRAY)), + () -> lines.add(UNBOUND) + ); } @Override - public InteractionResult useOn(final UseOnContext ctx) { + public InteractionResult bind(final UseOnContext ctx) { if (ctx.getPlayer() == null) { return InteractionResult.PASS; } @@ -100,24 +79,6 @@ public InteractionResult useOn(final UseOnContext ctx) { return InteractionResult.SUCCESS; } - @Override - public void appendHoverText(final ItemStack stack, - @Nullable final Level level, - final List tooltip, - final TooltipFlag flag) { - super.appendHoverText(stack, level, tooltip, flag); - getNetworkReference(stack).ifPresentOrElse( - network -> tooltip.add(createTranslation( - "item", - "network_item.bound_to", - network.pos().getX(), - network.pos().getY(), - network.pos().getZ() - ).withStyle(ChatFormatting.GRAY)), - () -> tooltip.add(UNBOUND) - ); - } - @Override public Optional getTooltipImage(final ItemStack stack) { if (isBound(stack)) { @@ -125,4 +86,31 @@ public Optional getTooltipImage(final ItemStack stack) { } return Optional.of(new HelpTooltipComponent(UNBOUND_HELP)); } + + @Override + public NetworkBoundItemSession openSession(final ItemStack stack, + final ServerPlayer player, + final InteractionHand hand) { + final Optional networkReference = getNetworkReference(stack); + return new NetworkBoundItemSessionImpl( + player, + PlayerSlotReference.of(player, hand), + networkReference.orElse(null) + ); + } + + private Optional getNetworkReference(final ItemStack stack) { + if (!isBound(stack)) { + return Optional.empty(); + } + final CompoundTag tag = Objects.requireNonNull(stack.getTag()); + final int x = tag.getInt(TAG_X); + final int y = tag.getInt(TAG_Y); + final int z = tag.getInt(TAG_Z); + final ResourceLocation dimension = new ResourceLocation(tag.getString(TAG_DIMENSION)); + return Optional.of(new NetworkBoundItemSessionImpl.NetworkReference( + ResourceKey.create(Registries.DIMENSION, dimension), + new BlockPos(x, y, z) + )); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java similarity index 51% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java index e5064def1..e0c997059 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/NetworkBoundItemContext.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java @@ -1,9 +1,16 @@ -package com.refinedmods.refinedstorage2.platform.common.item; +package com.refinedmods.refinedstorage2.platform.common.internal.item; import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.impl.component.GraphNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; +import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitter; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; +import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.core.BlockPos; @@ -12,14 +19,14 @@ import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; -public class NetworkBoundItemContext { +public class NetworkBoundItemSessionImpl implements NetworkBoundItemSession { private final Player player; private final Vec3 playerPosition; private final PlayerSlotReference playerSlotReference; @Nullable private final NetworkReference networkReference; - public NetworkBoundItemContext( + public NetworkBoundItemSessionImpl( final Player player, final PlayerSlotReference playerSlotReference, @Nullable final NetworkReference networkReference @@ -34,31 +41,46 @@ public NetworkBoundItemContext( this.networkReference = networkReference; } - public Vec3 getPlayerPosition() { - return playerPosition; + @Override + public Optional resolveNetwork() { + if (networkReference == null) { + return Optional.empty(); + } + return Optional.ofNullable(player.getServer()) + .map(server -> server.getLevel(networkReference.dimensionKey())) + .filter(level -> level.isLoaded(networkReference.pos())) + .map(level -> level.getBlockEntity(networkReference.pos())) + .filter(PlatformNetworkNodeContainer.class::isInstance) + .map(PlatformNetworkNodeContainer.class::cast) + .map(PlatformNetworkNodeContainer::getNode) + .map(NetworkNode::getNetwork) + .filter(this::isInRange); } - public ResourceKey getPlayerLevel() { - return player.level().dimension(); + private boolean isInRange(final Network network) { + return network.getComponent(GraphNetworkComponent.class) + .getContainers(WirelessTransmitter.class) + .stream() + .anyMatch(wirelessTransmitter -> wirelessTransmitter.isInRange( + player.level().dimension(), + playerPosition + )); } + @Override public boolean isActive() { return Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)) .map(energyStorage -> energyStorage.getStored() > 0) .orElse(true); } - public void drain(final long amount) { + @Override + public void drainEnergy(final long amount) { Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)).ifPresent( energyStorage -> energyStorage.extract(amount, Action.EXECUTE) ); } - @Nullable - public NetworkReference getNetworkReference() { - return networkReference; - } - public record NetworkReference(ResourceKey dimensionKey, BlockPos pos) { } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java index 15fd00057..a27de499c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java @@ -4,6 +4,8 @@ import com.refinedmods.refinedstorage2.api.network.impl.energy.EnergyStorageImpl; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractNetworkBoundEnergyItem; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.internal.grid.WirelessGrid; @@ -11,7 +13,6 @@ import java.util.Optional; -import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResultHolder; @@ -20,11 +21,15 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; -public class WirelessGridItem extends AbstractNetworkBoundItem { +public class WirelessGridItem extends AbstractNetworkBoundEnergyItem { private final boolean creative; public WirelessGridItem(final boolean creative) { - super(new Item.Properties().stacksTo(1)); + super( + new Item.Properties().stacksTo(1), + PlatformApi.INSTANCE.getEnergyItemHelper(), + PlatformApi.INSTANCE.getNetworkBoundItemHelper() + ); this.creative = creative; } @@ -32,29 +37,19 @@ public WirelessGridItem(final boolean creative) { public InteractionResultHolder use(final Level level, final Player player, final InteractionHand hand) { final ItemStack stack = player.getItemInHand(hand); if (player instanceof ServerPlayer serverPlayer && level.getServer() != null) { - final PlayerSlotReference slotReference = PlayerSlotReference.of(player, hand); - tryUse( - stack, - serverPlayer, - slotReference, - ctx -> open(level.getServer(), serverPlayer, ctx, slotReference) - ); + final NetworkBoundItemSession session = networkBoundItemHelper.openSession(stack, serverPlayer, hand); + open(serverPlayer, hand, session); } return InteractionResultHolder.consume(stack); } - private void open( - final MinecraftServer server, - final ServerPlayer player, - final NetworkBoundItemContext ctx, - final PlayerSlotReference slotReference - ) { - ctx.drain(Platform.INSTANCE.getConfig().getWirelessGrid().getOpenEnergyUsage()); - final Grid grid = new WirelessGrid(server, ctx); + private void open(final ServerPlayer player, final InteractionHand hand, final NetworkBoundItemSession session) { + session.drainEnergy(Platform.INSTANCE.getConfig().getWirelessGrid().getOpenEnergyUsage()); + final Grid grid = new WirelessGrid(session); Platform.INSTANCE.getMenuOpener().openMenu(player, new WirelessGridExtendedMenuProvider( grid, PlatformApi.INSTANCE.getStorageChannelTypeRegistry(), - slotReference + PlayerSlotReference.of(player, hand) )); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java index 8bc37651e..c03d60f9d 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/block/ControllerBlockItem.java @@ -17,7 +17,6 @@ import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; -// TODO: Make network bound item api accessible. public class ControllerBlockItem extends AbstractEnergyBlockItem { private final Component name; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/NetworkItemItemPropertyFunction.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/NetworkItemItemPropertyFunction.java index 8d6b046cf..abed03a94 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/NetworkItemItemPropertyFunction.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/NetworkItemItemPropertyFunction.java @@ -1,6 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.render; -import com.refinedmods.refinedstorage2.platform.common.item.AbstractNetworkBoundItem; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractNetworkBoundEnergyItem; import javax.annotation.Nullable; @@ -18,7 +18,7 @@ public float unclampedCall(final ItemStack itemStack, @Nullable final ClientLevel clientLevel, @Nullable final LivingEntity livingEntity, final int i) { - if (itemStack.getItem() instanceof AbstractNetworkBoundItem boundItem) { + if (itemStack.getItem() instanceof AbstractNetworkBoundEnergyItem boundItem) { return boundItem.isBound(itemStack) ? 1 : 0; } return 0; From 9a926d8f4c614cb37353565d294e652185261b07 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 2 Sep 2023 13:32:06 +0200 Subject: [PATCH 05/11] chore: update refined architect For mixin support on Forge for Curios. --- .github/workflows/build.yml | 2 +- .github/workflows/draft-release.yml | 2 +- .github/workflows/issue-for-unsupported-version.yml | 2 +- .github/workflows/publish-release.yml | 2 +- .github/workflows/resolved-issue-locking.yml | 2 +- .github/workflows/validate-branch-name.yml | 2 +- .github/workflows/validate-changelog.yml | 2 +- .github/workflows/validate-commit-messages.yml | 2 +- settings.gradle | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index f96511362..7bf568ea5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,5 +8,5 @@ on: types: [ opened, synchronize, reopened ] jobs: build: - uses: refinedmods/refinedarchitect/.github/workflows/build.yml@v0.8.2 + uses: refinedmods/refinedarchitect/.github/workflows/build.yml@v0.9.0 secrets: inherit diff --git a/.github/workflows/draft-release.yml b/.github/workflows/draft-release.yml index 8b020b580..e7027dbde 100644 --- a/.github/workflows/draft-release.yml +++ b/.github/workflows/draft-release.yml @@ -17,7 +17,7 @@ on: type: string jobs: draft: - uses: refinedmods/refinedarchitect/.github/workflows/draft-release.yml@v0.8.2 + uses: refinedmods/refinedarchitect/.github/workflows/draft-release.yml@v0.9.0 with: release-type: ${{ inputs.release-type }} version-number-override: ${{ inputs.version-number-override }} diff --git a/.github/workflows/issue-for-unsupported-version.yml b/.github/workflows/issue-for-unsupported-version.yml index 4c50548ab..27fdc3297 100644 --- a/.github/workflows/issue-for-unsupported-version.yml +++ b/.github/workflows/issue-for-unsupported-version.yml @@ -4,4 +4,4 @@ on: types: [ labeled, unlabeled, reopened ] jobs: unsupported-labeler: - uses: refinedmods/refinedarchitect/.github/workflows/issue-for-unsupported-version.yml@v0.8.2 \ No newline at end of file + uses: refinedmods/refinedarchitect/.github/workflows/issue-for-unsupported-version.yml@v0.9.0 \ No newline at end of file diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 34fcd3465..39ec95967 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -7,7 +7,7 @@ on: - closed jobs: publish-release: - uses: refinedmods/refinedarchitect/.github/workflows/publish-release.yml@v0.8.2 + uses: refinedmods/refinedarchitect/.github/workflows/publish-release.yml@v0.9.0 secrets: inherit with: project-name: 'Refined Storage' diff --git a/.github/workflows/resolved-issue-locking.yml b/.github/workflows/resolved-issue-locking.yml index f4fc0ab2a..050b0b699 100644 --- a/.github/workflows/resolved-issue-locking.yml +++ b/.github/workflows/resolved-issue-locking.yml @@ -4,4 +4,4 @@ on: - cron: '0 0 * * *' jobs: lock: - uses: refinedmods/refinedarchitect/.github/workflows/resolved-issue-locking.yml@v0.8.2 \ No newline at end of file + uses: refinedmods/refinedarchitect/.github/workflows/resolved-issue-locking.yml@v0.9.0 \ No newline at end of file diff --git a/.github/workflows/validate-branch-name.yml b/.github/workflows/validate-branch-name.yml index 4916592d7..6f09baf29 100644 --- a/.github/workflows/validate-branch-name.yml +++ b/.github/workflows/validate-branch-name.yml @@ -2,4 +2,4 @@ name: Validate branch name on: [ pull_request ] jobs: validate-branch-name: - uses: refinedmods/refinedarchitect/.github/workflows/validate-branch-name.yml@v0.8.2 \ No newline at end of file + uses: refinedmods/refinedarchitect/.github/workflows/validate-branch-name.yml@v0.9.0 \ No newline at end of file diff --git a/.github/workflows/validate-changelog.yml b/.github/workflows/validate-changelog.yml index 1ea905446..b7b83f9f3 100644 --- a/.github/workflows/validate-changelog.yml +++ b/.github/workflows/validate-changelog.yml @@ -4,4 +4,4 @@ on: types: [ opened, synchronize, reopened, ready_for_review, labeled, unlabeled ] jobs: validate-changelog: - uses: refinedmods/refinedarchitect/.github/workflows/validate-changelog.yml@v0.8.2 \ No newline at end of file + uses: refinedmods/refinedarchitect/.github/workflows/validate-changelog.yml@v0.9.0 \ No newline at end of file diff --git a/.github/workflows/validate-commit-messages.yml b/.github/workflows/validate-commit-messages.yml index 7d569590f..918f1807b 100644 --- a/.github/workflows/validate-commit-messages.yml +++ b/.github/workflows/validate-commit-messages.yml @@ -2,4 +2,4 @@ name: Validate commit messages on: [ pull_request ] jobs: validate-commit-messages: - uses: refinedmods/refinedarchitect/.github/workflows/validate-commit-messages.yml@v0.8.2 \ No newline at end of file + uses: refinedmods/refinedarchitect/.github/workflows/validate-commit-messages.yml@v0.9.0 \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index d9be98334..48e8abd26 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,4 +1,4 @@ -gradle.ext.refinedArchitectVersion = "0.8.2" +gradle.ext.refinedArchitectVersion = "0.9.0" dependencyResolutionManagement { repositories { From fe8e13adcd02b39a674d9c8f0aeca3b83a6dc375 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 2 Sep 2023 13:33:04 +0200 Subject: [PATCH 06/11] feat: open wireless grid keybinding --- CHANGELOG.md | 6 +- .../platform/api/PlatformApi.java | 10 ++++ .../platform/api/PlatformApiProxy.java | 19 +++++++ .../item/AbstractNetworkBoundEnergyItem.java | 23 ++++++++ .../api/item/NetworkBoundItemHelper.java | 3 +- .../platform/api/item/SlotReference.java | 17 ++++++ .../platform/common/PlatformApiImpl.java | 55 +++++++++++++++++++ .../AbstractBaseContainerMenu.java | 11 ++-- .../AbstractSingleAmountContainerMenu.java | 11 ++-- .../RegulatorUpgradeContainerMenu.java | 4 +- .../grid/WirelessGridContainerMenu.java | 9 +-- .../slot/PlayerSlotReference.java | 37 ------------- .../platform/common/content/KeyMappings.java | 11 ++++ .../item/NetworkBoundItemHelperImpl.java | 7 +-- .../item/NetworkBoundItemSessionImpl.java | 13 +++-- .../internal/item/SlotReferenceImpl.java | 48 ++++++++++++++++ .../common/item/RegulatorUpgradeItem.java | 15 ++--- .../common/item/WirelessGridItem.java | 37 +++++-------- .../WirelessGridExtendedMenuProvider.java | 12 ++-- .../packet/ClientToServerCommunications.java | 3 + .../assets/refinedstorage2/lang/en_us.json | 3 + .../fabric/ClientModInitializerImpl.java | 23 ++++++++ .../platform/fabric/ModInitializerImpl.java | 2 + .../platform/fabric/packet/PacketIds.java | 1 + .../c2s/ClientToServerCommunicationsImpl.java | 6 ++ .../packet/c2s/UseNetworkBoundItemPacket.java | 35 ++++++++++++ .../platform/forge/ClientModInitializer.java | 30 ++++++++++ .../platform/forge/packet/NetworkManager.java | 8 +++ .../c2s/ClientToServerCommunicationsImpl.java | 6 ++ .../packet/c2s/UseNetworkBoundItemPacket.java | 50 +++++++++++++++++ 30 files changed, 412 insertions(+), 103 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java delete mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 5888ad433..74151d0ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,13 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- "Open Wireless Grid" keybinding. + ### Changed -- You can now recharge the Controller in item form. +- You can now recharge the Controller in item form. ### Removed diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index 68c119669..c37ee3642 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -21,6 +21,7 @@ import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -40,9 +41,12 @@ import java.util.Optional; import java.util.Set; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import org.apiguardian.api.API; @@ -148,4 +152,10 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe EnergyStorage asItemEnergyStorage(EnergyStorage energyStorage, ItemStack stack); NetworkBoundItemHelper getNetworkBoundItemHelper(); + + SlotReference createSlotReference(FriendlyByteBuf buf); + + SlotReference createSlotReference(Player player, InteractionHand hand); + + void useNetworkBoundItem(Player player, Item... items); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index 5411ec11f..ad09d3949 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -21,6 +21,7 @@ import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -41,9 +42,12 @@ import java.util.Set; import javax.annotation.Nullable; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -296,6 +300,21 @@ public NetworkBoundItemHelper getNetworkBoundItemHelper() { return ensureLoaded().getNetworkBoundItemHelper(); } + @Override + public SlotReference createSlotReference(final FriendlyByteBuf buf) { + return ensureLoaded().createSlotReference(buf); + } + + @Override + public SlotReference createSlotReference(final Player player, final InteractionHand hand) { + return ensureLoaded().createSlotReference(player, hand); + } + + @Override + public void useNetworkBoundItem(final Player player, final Item... items) { + ensureLoaded().useNetworkBoundItem(player, items); + } + private PlatformApi ensureLoaded() { if (delegate == null) { throw new IllegalStateException("Platform API not loaded yet"); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java index 46c31e34b..e7a93b74e 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java @@ -1,11 +1,17 @@ package com.refinedmods.refinedstorage2.platform.api.item; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; + import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.network.chat.Component; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; +import net.minecraft.world.InteractionResultHolder; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; @@ -43,6 +49,23 @@ public void appendHoverText(final ItemStack stack, networkBoundItemHelper.addTooltip(stack, tooltip); } + @Override + public InteractionResultHolder use(final Level level, final Player player, final InteractionHand hand) { + final ItemStack stack = player.getItemInHand(hand); + if (player instanceof ServerPlayer serverPlayer && level.getServer() != null) { + final SlotReference slotReference = PlatformApi.INSTANCE.createSlotReference(player, hand); + final NetworkBoundItemSession session = networkBoundItemHelper.openSession( + stack, + serverPlayer, + slotReference + ); + use(serverPlayer, slotReference, session); + } + return InteractionResultHolder.consume(stack); + } + + public abstract void use(ServerPlayer player, SlotReference slotReference, NetworkBoundItemSession session); + public boolean isBound(final ItemStack stack) { return networkBoundItemHelper.isBound(stack); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java index 211398d14..9d08fad52 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/NetworkBoundItemHelper.java @@ -5,7 +5,6 @@ import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.ItemStack; @@ -20,7 +19,7 @@ public interface NetworkBoundItemHelper { Optional getTooltipImage(ItemStack stack); - NetworkBoundItemSession openSession(ItemStack stack, ServerPlayer player, InteractionHand hand); + NetworkBoundItemSession openSession(ItemStack stack, ServerPlayer player, SlotReference slotReference); boolean isBound(ItemStack stack); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java new file mode 100644 index 000000000..00bde9f66 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java @@ -0,0 +1,17 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import java.util.Optional; + +import io.netty.buffer.ByteBuf; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface SlotReference { + boolean isDisabledSlot(int playerSlotIndex); + + void writeToBuf(ByteBuf buf); + + Optional resolve(Player player); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index a6fa5acb4..bcdf8d559 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -25,6 +25,7 @@ import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -48,6 +49,7 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.item.NetworkBoundItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.item.SlotReferenceImpl; import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; @@ -66,6 +68,7 @@ import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; @@ -74,15 +77,20 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.OptionalInt; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; +import net.minecraft.ChatFormatting; import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.MutableComponent; import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; @@ -422,4 +430,51 @@ public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, public NetworkBoundItemHelper getNetworkBoundItemHelper() { return networkBoundItemHelper; } + + @Override + public SlotReference createSlotReference(final FriendlyByteBuf buf) { + return SlotReferenceImpl.of(buf); + } + + @Override + public SlotReference createSlotReference(final Player player, final InteractionHand hand) { + return SlotReferenceImpl.of(player, hand); + } + + @Override + public void useNetworkBoundItem(final Player player, final Item... items) { + findItem(player, items).ifPresent( + slotIndex -> Platform.INSTANCE.getClientToServerCommunications().sendUseNetworkBoundItem( + new SlotReferenceImpl(slotIndex) + ) + ); + } + + private OptionalInt findItem(final Player player, final Item... items) { + final Set validItems = new HashSet<>(Arrays.asList(items)); + OptionalInt slotIndex = OptionalInt.empty(); + for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { + final ItemStack slot = player.getInventory().getItem(i); + if (!validItems.contains(slot.getItem())) { + continue; + } + if (slotIndex.isPresent()) { + player.sendSystemMessage(createTranslation( + "item", + "network_item.cannot_open_with_shortcut_due_to_duplicate", + items[0].getDescription() + ).withStyle(ChatFormatting.RED)); + return OptionalInt.empty(); + } + slotIndex = OptionalInt.of(i); + } + if (slotIndex.isEmpty()) { + player.sendSystemMessage(createTranslation( + "item", + "network_item.cannot_open_because_not_found", + items[0].getDescription() + ).withStyle(ChatFormatting.RED)); + } + return slotIndex; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java index 16bce7c38..b2f16454b 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractBaseContainerMenu.java @@ -1,12 +1,12 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ClientProperty; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.Property; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyType; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ServerProperty; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.DisabledSlot; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import java.util.HashMap; @@ -25,7 +25,7 @@ public abstract class AbstractBaseContainerMenu extends AbstractContainerMenu { protected final TransferManager transferManager; @Nullable - protected PlayerSlotReference disabledPlayerInventorySlot; + protected SlotReference disabledSlot; private final Map, Property> propertyMap = new HashMap<>(); protected AbstractBaseContainerMenu(final MenuType type, final int syncId) { @@ -74,7 +74,8 @@ protected void addPlayerInventory(final Inventory inventory, final int inventory for (int i = 0; i < 9; i++) { final int x = inventoryX + i * 18; final int y = inventoryY + 4 + (3 * 18); - final boolean disabled = disabledPlayerInventorySlot != null && disabledPlayerInventorySlot.isDisabled(id); + final boolean disabled = disabledSlot != null + && disabledSlot.isDisabledSlot(id); addSlot(disabled ? new DisabledSlot(inventory, id, x, y) : new Slot(inventory, id, x, y)); id++; } @@ -104,8 +105,8 @@ public void clicked(final int id, final int dragType, final ClickType clickType, } private boolean isSwappingDisabledSlotWithNumberKeys(final int dragType, final ClickType clickType) { - return disabledPlayerInventorySlot != null + return disabledSlot != null && clickType == ClickType.SWAP - && disabledPlayerInventorySlot.isDisabled(dragType); + && disabledSlot.isDisabledSlot(dragType); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java index 6f815b2e1..64c42d950 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java @@ -1,8 +1,9 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.ResourceSlot; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; @@ -26,7 +27,7 @@ protected AbstractSingleAmountContainerMenu(final MenuType type, final Component filterHelpText) { super(type, syncId); if (buf.readBoolean()) { - disabledPlayerInventorySlot = PlayerSlotReference.of(buf); + disabledSlot = PlatformApi.INSTANCE.createSlotReference(buf); } this.clientAmount = buf.readDouble(); this.filterHelpText = filterHelpText; @@ -39,9 +40,9 @@ protected AbstractSingleAmountContainerMenu(final MenuType type, final Player player, final ResourceContainer resourceContainer, final Component filterHelpText, - @Nullable final PlayerSlotReference disabledSlotReference) { + @Nullable final SlotReference disabledSlotReference) { super(type, syncId, player); - this.disabledPlayerInventorySlot = disabledSlotReference; + this.disabledSlot = disabledSlotReference; this.filterHelpText = filterHelpText; addSlots(player, resourceContainer); } @@ -66,7 +67,7 @@ public void changeAmountOnClient(final double newAmount) { public static void writeToBuf(final FriendlyByteBuf buf, final double amount, final ResourceContainer container, - @Nullable final PlayerSlotReference disabledSlotReference) { + @Nullable final SlotReference disabledSlotReference) { if (disabledSlotReference != null) { buf.writeBoolean(true); disabledSlotReference.writeToBuf(buf); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/RegulatorUpgradeContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/RegulatorUpgradeContainerMenu.java index 359b2a741..0e604b5e0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/RegulatorUpgradeContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/RegulatorUpgradeContainerMenu.java @@ -1,7 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ResourceContainer; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import java.util.function.Consumer; @@ -28,7 +28,7 @@ public RegulatorUpgradeContainerMenu(final int syncId, final Player player, final ResourceContainer resourceContainer, final Consumer amountAcceptor, - final PlayerSlotReference slotReference) { + final SlotReference slotReference) { super( Menus.INSTANCE.getRegulatorUpgrade(), syncId, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java index ab5c5a9cc..487a1bef7 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java @@ -1,7 +1,8 @@ package com.refinedmods.refinedstorage2.platform.common.containermenu.grid; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import net.minecraft.network.FriendlyByteBuf; @@ -10,16 +11,16 @@ public class WirelessGridContainerMenu extends AbstractGridContainerMenu { public WirelessGridContainerMenu(final int syncId, final Inventory playerInventory, final FriendlyByteBuf buf) { super(Menus.INSTANCE.getWirelessGrid(), syncId, playerInventory, buf); - this.disabledPlayerInventorySlot = PlayerSlotReference.of(buf); + this.disabledSlot = PlatformApi.INSTANCE.createSlotReference(buf); addSlots(0); } public WirelessGridContainerMenu(final int syncId, final Inventory playerInventory, final Grid grid, - final PlayerSlotReference slotReference) { + final SlotReference itemReference) { super(Menus.INSTANCE.getWirelessGrid(), syncId, playerInventory, grid); - this.disabledPlayerInventorySlot = slotReference; + this.disabledSlot = itemReference; addSlots(0); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java deleted file mode 100644 index ddcef11e4..000000000 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/slot/PlayerSlotReference.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.refinedmods.refinedstorage2.platform.common.containermenu.slot; - -import io.netty.buffer.ByteBuf; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; - -public final class PlayerSlotReference { - private final int slotIndex; - - private PlayerSlotReference(final int slotIndex) { - this.slotIndex = slotIndex; - } - - public ItemStack resolve(final Player player) { - return player.getInventory().getItem(slotIndex); - } - - public boolean isDisabled(final int playerSlotIndex) { - return playerSlotIndex == slotIndex; - } - - public void writeToBuf(final ByteBuf buf) { - buf.writeInt(slotIndex); - } - - public static PlayerSlotReference of(final ByteBuf buf) { - return new PlayerSlotReference(buf.readInt()); - } - - public static PlayerSlotReference of(final Player player, final InteractionHand hand) { - return new PlayerSlotReference(hand == InteractionHand.MAIN_HAND - ? player.getInventory().selected - : Inventory.SLOT_OFFHAND); - } -} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/KeyMappings.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/KeyMappings.java index 2bf6f5da6..4b102dd6c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/KeyMappings.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/KeyMappings.java @@ -14,6 +14,8 @@ public final class KeyMappings { private KeyMapping clearCraftingGridMatrixToNetwork; @Nullable private KeyMapping clearCraftingGridMatrixToInventory; + @Nullable + private KeyMapping openWirelessGrid; private KeyMappings() { } @@ -43,4 +45,13 @@ public KeyMapping getClearCraftingGridMatrixToInventory() { public void setClearCraftingGridMatrixToInventory(final KeyMapping clearCraftingGridMatrixToInventory) { this.clearCraftingGridMatrixToInventory = clearCraftingGridMatrixToInventory; } + + @Nullable + public KeyMapping getOpenWirelessGrid() { + return openWirelessGrid; + } + + public void setOpenWirelessGrid(final KeyMapping openWirelessGrid) { + this.openWirelessGrid = openWirelessGrid; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java index 029b832ab..ec9812d66 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemHelperImpl.java @@ -3,8 +3,8 @@ import com.refinedmods.refinedstorage2.platform.api.item.HelpTooltipComponent; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import java.util.List; import java.util.Objects; @@ -19,7 +19,6 @@ import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.inventory.tooltip.TooltipComponent; import net.minecraft.world.item.ItemStack; @@ -90,11 +89,11 @@ public Optional getTooltipImage(final ItemStack stack) { @Override public NetworkBoundItemSession openSession(final ItemStack stack, final ServerPlayer player, - final InteractionHand hand) { + final SlotReference slotReference) { final Optional networkReference = getNetworkReference(stack); return new NetworkBoundItemSessionImpl( player, - PlayerSlotReference.of(player, hand), + slotReference, networkReference.orElse(null) ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java index e0c997059..e83d8b8e4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/NetworkBoundItemSessionImpl.java @@ -6,9 +6,9 @@ import com.refinedmods.refinedstorage2.api.network.node.NetworkNode; import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitter; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.network.node.PlatformNetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import java.util.Optional; import javax.annotation.Nullable; @@ -22,13 +22,13 @@ public class NetworkBoundItemSessionImpl implements NetworkBoundItemSession { private final Player player; private final Vec3 playerPosition; - private final PlayerSlotReference playerSlotReference; + private final SlotReference slotReference; @Nullable private final NetworkReference networkReference; public NetworkBoundItemSessionImpl( final Player player, - final PlayerSlotReference playerSlotReference, + final SlotReference slotReference, @Nullable final NetworkReference networkReference ) { this.player = player; @@ -37,7 +37,7 @@ public NetworkBoundItemSessionImpl( // If the network is no longer accessible, certain assumptions will break (e.g. grid watcher can no longer // be removed after it was added). this.playerPosition = new Vec3(player.position().x, player.position().y, player.position().z); - this.playerSlotReference = playerSlotReference; + this.slotReference = slotReference; this.networkReference = networkReference; } @@ -69,14 +69,15 @@ private boolean isInRange(final Network network) { @Override public boolean isActive() { - return Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)) + return slotReference.resolve(player) + .flatMap(Platform.INSTANCE::getEnergyStorage) .map(energyStorage -> energyStorage.getStored() > 0) .orElse(true); } @Override public void drainEnergy(final long amount) { - Platform.INSTANCE.getEnergyStorage(playerSlotReference.resolve(player)).ifPresent( + slotReference.resolve(player).flatMap(Platform.INSTANCE::getEnergyStorage).ifPresent( energyStorage -> energyStorage.extract(amount, Action.EXECUTE) ); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java new file mode 100644 index 000000000..f6350deb8 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java @@ -0,0 +1,48 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.item; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; + +import java.util.Optional; + +import io.netty.buffer.ByteBuf; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; + +public final class SlotReferenceImpl implements SlotReference { + private final int slotIndex; + + public SlotReferenceImpl(final int slotIndex) { + this.slotIndex = slotIndex; + } + + @Override + public Optional resolve(final Player player) { + final ItemStack item = player.getInventory().getItem(slotIndex); + if (item.isEmpty()) { + return Optional.empty(); + } + return Optional.of(item); + } + + @Override + public boolean isDisabledSlot(final int playerSlotIndex) { + return playerSlotIndex == slotIndex; + } + + @Override + public void writeToBuf(final ByteBuf buf) { + buf.writeInt(slotIndex); + } + + public static SlotReference of(final ByteBuf buf) { + return new SlotReferenceImpl(buf.readInt()); + } + + public static SlotReference of(final Player player, final InteractionHand hand) { + return new SlotReferenceImpl(hand == InteractionHand.MAIN_HAND + ? player.getInventory().selected + : Inventory.SLOT_OFFHAND); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java index 6eff0b8cf..3333e7069 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java @@ -1,13 +1,14 @@ package com.refinedmods.refinedstorage2.platform.common.item; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.item.AbstractUpgradeItem; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ResourceAmountTemplate; import com.refinedmods.refinedstorage2.platform.api.resource.ResourceContainer; import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.AbstractSingleAmountContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.RegulatorUpgradeContainerMenu; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -49,7 +50,7 @@ public InteractionResultHolder use(final Level level, final Player pl getResourceFilterContainer(stack), getAmount(stack), newAmount -> setAmount(stack, newAmount), - PlayerSlotReference.of(player, hand) + PlatformApi.INSTANCE.createSlotReference(player, hand) )); } return InteractionResultHolder.success(stack); @@ -119,21 +120,21 @@ private static class ExtendedMenuProviderImpl implements ExtendedMenuProvider { private final ResourceContainer resourceContainer; private final double amount; private final Consumer amountAcceptor; - private final PlayerSlotReference playerSlotReference; + private final SlotReference slotReference; private ExtendedMenuProviderImpl(final ResourceContainer resourceContainer, final double amount, final Consumer amountAcceptor, - final PlayerSlotReference playerSlotReference) { + final SlotReference slotReference) { this.resourceContainer = resourceContainer; this.amount = amount; this.amountAcceptor = amountAcceptor; - this.playerSlotReference = playerSlotReference; + this.slotReference = slotReference; } @Override public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByteBuf buf) { - AbstractSingleAmountContainerMenu.writeToBuf(buf, amount, resourceContainer, playerSlotReference); + AbstractSingleAmountContainerMenu.writeToBuf(buf, amount, resourceContainer, slotReference); } @Override @@ -148,7 +149,7 @@ public AbstractContainerMenu createMenu(final int syncId, final Inventory invent player, resourceContainer, amountAcceptor, - playerSlotReference + slotReference ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java index a27de499c..c32068be4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/WirelessGridItem.java @@ -6,20 +6,16 @@ import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.item.AbstractNetworkBoundEnergyItem; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.common.Platform; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.internal.grid.WirelessGrid; import com.refinedmods.refinedstorage2.platform.common.menu.WirelessGridExtendedMenuProvider; import java.util.Optional; import net.minecraft.server.level.ServerPlayer; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResultHolder; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; public class WirelessGridItem extends AbstractNetworkBoundEnergyItem { private final boolean creative; @@ -34,33 +30,26 @@ public WirelessGridItem(final boolean creative) { } @Override - public InteractionResultHolder use(final Level level, final Player player, final InteractionHand hand) { - final ItemStack stack = player.getItemInHand(hand); - if (player instanceof ServerPlayer serverPlayer && level.getServer() != null) { - final NetworkBoundItemSession session = networkBoundItemHelper.openSession(stack, serverPlayer, hand); - open(serverPlayer, hand, session); + public Optional createEnergyStorage(final ItemStack stack) { + if (creative) { + return Optional.empty(); } - return InteractionResultHolder.consume(stack); + final EnergyStorage energyStorage = new EnergyStorageImpl( + Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity() + ); + return Optional.of(PlatformApi.INSTANCE.asItemEnergyStorage(energyStorage, stack)); } - private void open(final ServerPlayer player, final InteractionHand hand, final NetworkBoundItemSession session) { + @Override + public void use(final ServerPlayer player, + final SlotReference slotReference, + final NetworkBoundItemSession session) { session.drainEnergy(Platform.INSTANCE.getConfig().getWirelessGrid().getOpenEnergyUsage()); final Grid grid = new WirelessGrid(session); Platform.INSTANCE.getMenuOpener().openMenu(player, new WirelessGridExtendedMenuProvider( grid, PlatformApi.INSTANCE.getStorageChannelTypeRegistry(), - PlayerSlotReference.of(player, hand) + slotReference )); } - - @Override - public Optional createEnergyStorage(final ItemStack stack) { - if (creative) { - return Optional.empty(); - } - final EnergyStorage energyStorage = new EnergyStorageImpl( - Platform.INSTANCE.getConfig().getWirelessGrid().getEnergyCapacity() - ); - return Optional.of(PlatformApi.INSTANCE.asItemEnergyStorage(energyStorage, stack)); - } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java index e234d788b..686917f5e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java @@ -1,10 +1,10 @@ package com.refinedmods.refinedstorage2.platform.common.menu; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.WirelessGridContainerMenu; -import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.PlayerSlotReference; import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import net.minecraft.network.FriendlyByteBuf; @@ -16,12 +16,12 @@ import net.minecraft.world.inventory.AbstractContainerMenu; public class WirelessGridExtendedMenuProvider extends GridExtendedMenuProvider { - private final PlayerSlotReference slotReference; + private final SlotReference itemReference; public WirelessGridExtendedMenuProvider(final Grid grid, final PlatformRegistry> storageChannelTypeRegistry, - final PlayerSlotReference slotReference) { + final SlotReference itemReference) { super(grid, storageChannelTypeRegistry, new MenuProvider() { @Override public Component getDisplayName() { @@ -30,15 +30,15 @@ public Component getDisplayName() { @Override public AbstractContainerMenu createMenu(final int syncId, final Inventory inventory, final Player player) { - return new WirelessGridContainerMenu(syncId, inventory, grid, slotReference); + return new WirelessGridContainerMenu(syncId, inventory, grid, itemReference); } }); - this.slotReference = slotReference; + this.itemReference = itemReference; } @Override public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByteBuf buf) { super.writeScreenOpeningData(player, buf); - slotReference.writeToBuf(buf); + itemReference.writeToBuf(buf); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/packet/ClientToServerCommunications.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/packet/ClientToServerCommunications.java index 80ecb1d5b..59ff10a08 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/packet/ClientToServerCommunications.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/packet/ClientToServerCommunications.java @@ -3,6 +3,7 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridExtractMode; import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyType; @@ -38,4 +39,6 @@ void sendGridScroll(PlatformStorageChannelType storageChannelType, void sendResourceSlotAmountChange(int slotIndex, long amount); void sendSingleAmountChange(double amount); + + void sendUseNetworkBoundItem(SlotReference slotReference); } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index 5242626a9..a63c6c115 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -190,6 +190,8 @@ "item.refinedstorage2.network_item.unbound": "Unbound.", "item.refinedstorage2.network_item.unbound.help": "Use on any storage network device to bind.", "item.refinedstorage2.network_item.bound_to": "Bound to %d, %d, %d.", + "item.refinedstorage2.network_item.cannot_open_with_shortcut_due_to_duplicate": "There is more than one %s in your inventory.", + "item.refinedstorage2.network_item.cannot_open_because_not_found": "There isn't any %s in your inventory.", "misc.refinedstorage2.stored": "Stored: %s", "misc.refinedstorage2.stored_with_capacity": "Stored: %s / %s (%d%%)", "misc.refinedstorage2.total": "%d total", @@ -212,6 +214,7 @@ "key.refinedstorage2.focus_search_bar": "Focus search bar", "key.refinedstorage2.clear_crafting_grid_matrix_to_network": "Clear Crafting Grid matrix to network", "key.refinedstorage2.clear_crafting_grid_matrix_to_inventory": "Clear Crafting Grid matrix to inventory", + "key.refinedstorage2.open_wireless_grid": "Open Wireless Grid", "refinedstorage2.subtitle.wrench": "Wrench used", "category.refinedstorage2.key_bindings": "Refined Storage 2", "text.autoconfig.refinedstorage2.title": "Refined Storage 2", diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java index 50e9fbff1..44be51ce9 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java @@ -38,12 +38,14 @@ import com.mojang.blaze3d.platform.InputConstants; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.model.loading.v1.ModelLoadingPlugin; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.rendering.v1.TooltipComponentCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; @@ -52,6 +54,7 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.item.ItemProperties; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.DyeColor; @@ -287,6 +290,26 @@ private void registerKeyBindings() { GLFW.GLFW_KEY_TAB, KEY_BINDINGS_TRANSLATION_KEY ))); + KeyMappings.INSTANCE.setOpenWirelessGrid(KeyBindingHelper.registerKeyBinding(new KeyMapping( + createTranslationKey("key", "open_wireless_grid"), + InputConstants.Type.KEYSYM, + InputConstants.UNKNOWN.getValue(), + KEY_BINDINGS_TRANSLATION_KEY + ))); + ClientTickEvents.END_CLIENT_TICK.register(client -> { + final Player player = Minecraft.getInstance().player; + if (player == null) { + return; + } + final KeyMapping openWirelessGrid = KeyMappings.INSTANCE.getOpenWirelessGrid(); + while (openWirelessGrid != null && openWirelessGrid.consumeClick()) { + PlatformApi.INSTANCE.useNetworkBoundItem( + player, + Items.INSTANCE.getWirelessGrid(), + Items.INSTANCE.getCreativeWirelessGrid() + ); + } + }); } private void registerModelPredicates() { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index 3710c3ebb..baff85bd3 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -42,6 +42,7 @@ import com.refinedmods.refinedstorage2.platform.fabric.packet.c2s.ResourceSlotChangePacket; import com.refinedmods.refinedstorage2.platform.fabric.packet.c2s.SingleAmountChangePacket; import com.refinedmods.refinedstorage2.platform.fabric.packet.c2s.StorageInfoRequestPacket; +import com.refinedmods.refinedstorage2.platform.fabric.packet.c2s.UseNetworkBoundItemPacket; import com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil; import java.util.Arrays; @@ -284,6 +285,7 @@ private void registerPackets() { new ResourceSlotChangePacket() ); ServerPlayNetworking.registerGlobalReceiver(PacketIds.SINGLE_AMOUNT_CHANGE, new SingleAmountChangePacket()); + ServerPlayNetworking.registerGlobalReceiver(PacketIds.USE_NETWORK_BOUND_ITEM, new UseNetworkBoundItemPacket()); } @SuppressWarnings("checkstyle:Indentation") diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/PacketIds.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/PacketIds.java index 59d290461..c0a02ea47 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/PacketIds.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/PacketIds.java @@ -24,6 +24,7 @@ public final class PacketIds { public static final ResourceLocation RESOURCE_FILTER_SLOT_CHANGE = createIdentifier("resource_filter_slot_change"); public static final ResourceLocation RESOURCE_SLOT_AMOUNT_CHANGE = createIdentifier("resource_slot_amount_change"); public static final ResourceLocation SINGLE_AMOUNT_CHANGE = createIdentifier("detector_amount_change"); + public static final ResourceLocation USE_NETWORK_BOUND_ITEM = createIdentifier("use_network_bound_item"); private PacketIds() { } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java index 0816073e8..f2a27a06f 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyType; @@ -126,6 +127,11 @@ public void sendSingleAmountChange(final double amount) { sendToServer(PacketIds.SINGLE_AMOUNT_CHANGE, buf -> buf.writeDouble(amount)); } + @Override + public void sendUseNetworkBoundItem(final SlotReference slotReference) { + sendToServer(PacketIds.USE_NETWORK_BOUND_ITEM, slotReference::writeToBuf); + } + private static void sendToServer(final ResourceLocation id, final Consumer bufConsumer) { final FriendlyByteBuf buf = new FriendlyByteBuf(Unpooled.buffer()); bufConsumer.accept(buf); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java new file mode 100644 index 000000000..74d730799 --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java @@ -0,0 +1,35 @@ +package com.refinedmods.refinedstorage2.platform.fabric.packet.c2s; + +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractNetworkBoundEnergyItem; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; + +import net.fabricmc.fabric.api.networking.v1.PacketSender; +import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.server.network.ServerGamePacketListenerImpl; + +public class UseNetworkBoundItemPacket implements ServerPlayNetworking.PlayChannelHandler { + @Override + public void receive(final MinecraftServer server, + final ServerPlayer player, + final ServerGamePacketListenerImpl handler, + final FriendlyByteBuf buf, + final PacketSender responseSender) { + final SlotReference slotReference = PlatformApi.INSTANCE.createSlotReference(buf); + server.execute(() -> slotReference.resolve(player).ifPresent(stack -> { + if (!(stack.getItem() instanceof AbstractNetworkBoundEnergyItem networkBoundItem)) { + return; + } + final NetworkBoundItemSession sess = PlatformApi.INSTANCE.getNetworkBoundItemHelper().openSession( + stack, + player, + slotReference + ); + networkBoundItem.use(player, slotReference, sess); + })); + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java index 68ce41a57..b43b6535c 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java @@ -25,19 +25,23 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.item.ItemProperties; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; +import net.minecraftforge.client.event.InputEvent; import net.minecraftforge.client.event.ModelEvent; import net.minecraftforge.client.event.RegisterClientTooltipComponentFactoriesEvent; import net.minecraftforge.client.event.RegisterKeyMappingsEvent; import net.minecraftforge.client.settings.KeyConflictContext; import net.minecraftforge.client.settings.KeyModifier; +import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @@ -58,6 +62,7 @@ private ClientModInitializer() { @SubscribeEvent public static void onClientSetup(final FMLClientSetupEvent e) { + MinecraftForge.EVENT_BUS.addListener(ClientModInitializer::onKeyInput); e.enqueueWork(ClientModInitializer::registerModelPredicates); e.enqueueWork(() -> registerScreens(new ScreenRegistration() { @Override @@ -75,6 +80,22 @@ public > void registerAlternativeGridHints(); } + @SubscribeEvent + public static void onKeyInput(final InputEvent.Key e) { + final Player player = Minecraft.getInstance().player; + if (player == null) { + return; + } + final KeyMapping openWirelessGrid = KeyMappings.INSTANCE.getOpenWirelessGrid(); + if (openWirelessGrid != null && openWirelessGrid.isDown()) { + PlatformApi.INSTANCE.useNetworkBoundItem( + player, + Items.INSTANCE.getWirelessGrid(), + Items.INSTANCE.getCreativeWirelessGrid() + ); + } + } + private static void registerModelPredicates() { Items.INSTANCE.getControllers().forEach(controllerBlockItem -> ItemProperties.register( controllerBlockItem.get(), @@ -117,6 +138,15 @@ public static void onRegisterKeyMappings(final RegisterKeyMappingsEvent e) { ); e.register(clearCraftingGridMatrixToInventory); KeyMappings.INSTANCE.setClearCraftingGridMatrixToInventory(clearCraftingGridMatrixToInventory); + + final KeyMapping openWirelessGrid = new KeyMapping( + createTranslationKey("key", "open_wireless_grid"), + KeyConflictContext.IN_GAME, + InputConstants.UNKNOWN, + KEY_BINDINGS_TRANSLATION_KEY + ); + e.register(openWirelessGrid); + KeyMappings.INSTANCE.setOpenWirelessGrid(openWirelessGrid); } private static void registerBlockEntityRenderer() { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/NetworkManager.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/NetworkManager.java index 00eb6722a..c93624a61 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/NetworkManager.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/NetworkManager.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.forge.packet.c2s.ResourceSlotChangePacket; import com.refinedmods.refinedstorage2.platform.forge.packet.c2s.SingleAmountChangePacket; import com.refinedmods.refinedstorage2.platform.forge.packet.c2s.StorageInfoRequestPacket; +import com.refinedmods.refinedstorage2.platform.forge.packet.c2s.UseNetworkBoundItemPacket; import com.refinedmods.refinedstorage2.platform.forge.packet.s2c.ControllerEnergyInfoPacket; import com.refinedmods.refinedstorage2.platform.forge.packet.s2c.GridActivePacket; import com.refinedmods.refinedstorage2.platform.forge.packet.s2c.GridClearPacket; @@ -167,6 +168,13 @@ public NetworkManager() { SingleAmountChangePacket::decode, SingleAmountChangePacket::handle ); + handler.registerMessage( + id++, + UseNetworkBoundItemPacket.class, + UseNetworkBoundItemPacket::encode, + UseNetworkBoundItemPacket::decode, + UseNetworkBoundItemPacket::handle + ); } public void send(final ServerPlayer player, final Object message) { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/ClientToServerCommunicationsImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/ClientToServerCommunicationsImpl.java index 0da99cec5..75df46c38 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/ClientToServerCommunicationsImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/ClientToServerCommunicationsImpl.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.api.grid.operations.GridInsertMode; import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollMode; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyType; @@ -105,4 +106,9 @@ public void sendResourceSlotAmountChange(final int slotIndex, final long amount) public void sendSingleAmountChange(final double amount) { networkManager.send(new SingleAmountChangePacket(amount)); } + + @Override + public void sendUseNetworkBoundItem(final SlotReference slotReference) { + networkManager.send(new UseNetworkBoundItemPacket(slotReference)); + } } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java new file mode 100644 index 000000000..1824a1899 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java @@ -0,0 +1,50 @@ +package com.refinedmods.refinedstorage2.platform.forge.packet.c2s; + +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.item.AbstractNetworkBoundEnergyItem; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; + +import java.util.function.Supplier; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.server.level.ServerPlayer; +import net.minecraftforge.network.NetworkEvent; + +public class UseNetworkBoundItemPacket { + private final SlotReference slotReference; + + public UseNetworkBoundItemPacket(final SlotReference slotReference) { + this.slotReference = slotReference; + } + + public static UseNetworkBoundItemPacket decode(final FriendlyByteBuf buf) { + return new UseNetworkBoundItemPacket(PlatformApi.INSTANCE.createSlotReference(buf)); + } + + public static void encode(final UseNetworkBoundItemPacket packet, final FriendlyByteBuf buf) { + packet.slotReference.writeToBuf(buf); + } + + public static void handle(final UseNetworkBoundItemPacket packet, final Supplier ctx) { + final ServerPlayer player = ctx.get().getSender(); + if (player != null) { + ctx.get().enqueueWork(() -> handle(packet, player)); + } + ctx.get().setPacketHandled(true); + } + + private static void handle(final UseNetworkBoundItemPacket packet, final ServerPlayer player) { + packet.slotReference.resolve(player).ifPresent(stack -> { + if (!(stack.getItem() instanceof AbstractNetworkBoundEnergyItem networkBoundItem)) { + return; + } + final NetworkBoundItemSession sess = PlatformApi.INSTANCE.getNetworkBoundItemHelper().openSession( + stack, + player, + packet.slotReference + ); + networkBoundItem.use(player, packet.slotReference, sess); + }); + } +} From 5058fe92eaed4898564b6ebc480c931e5c332946 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 2 Sep 2023 14:00:03 +0200 Subject: [PATCH 07/11] feat: curios integration on Forge --- CHANGELOG.md | 1 + .../platform/api/PlatformApi.java | 12 ++- .../platform/api/PlatformApiProxy.java | 25 +++++- .../item/AbstractNetworkBoundEnergyItem.java | 2 +- .../platform/api/item/SlotReference.java | 6 +- .../api/item/SlotReferenceFactory.java | 9 ++ .../api/item/SlotReferenceProvider.java | 13 +++ .../common/AbstractClientModInitializer.java | 20 +++++ .../platform/common/PlatformApiImpl.java | 78 +++++++++--------- .../AbstractSingleAmountContainerMenu.java | 4 +- .../grid/WirelessGridContainerMenu.java | 6 +- .../item/CompositeSlotReferenceProvider.java | 54 ++++++++++++ ...eImpl.java => InventorySlotReference.java} | 20 +++-- .../item/InventorySlotReferenceFactory.java | 18 ++++ .../item/InventorySlotReferenceProvider.java | 27 ++++++ .../common/item/RegulatorUpgradeItem.java | 2 +- .../WirelessGridExtendedMenuProvider.java | 11 +-- .../assets/refinedstorage2/lang/en_us.json | 1 + .../fabric/ClientModInitializerImpl.java | 17 +--- .../c2s/ClientToServerCommunicationsImpl.java | 5 +- .../packet/c2s/UseNetworkBoundItemPacket.java | 8 +- refinedstorage2-platform-forge/build.gradle | 6 ++ .../platform/forge/ClientModInitializer.java | 15 +--- .../platform/forge/ModInitializer.java | 13 +++ .../curios/CuriosSlotReference.java | 46 +++++++++++ .../curios/CuriosSlotReferenceFactory.java | 18 ++++ .../curios/CuriosSlotReferenceProvider.java | 41 +++++++++ .../integration/curios/package-info.java | 7 ++ .../packet/c2s/UseNetworkBoundItemPacket.java | 13 ++- .../refinedstorage2/textures/slot/curios.png | Bin 0 -> 261 bytes .../curios/tags/items/refinedstorage2.json | 7 ++ .../curios/entities/refinedstorage2.json | 8 ++ .../curios/slots/refinedstorage2.json | 5 ++ 33 files changed, 414 insertions(+), 104 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceFactory.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceProvider.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/CompositeSlotReferenceProvider.java rename refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/{SlotReferenceImpl.java => InventorySlotReference.java} (68%) create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceFactory.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceProvider.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReference.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceFactory.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceProvider.java create mode 100644 refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/package-info.java create mode 100644 refinedstorage2-platform-forge/src/main/resources/assets/refinedstorage2/textures/slot/curios.png create mode 100644 refinedstorage2-platform-forge/src/main/resources/data/curios/tags/items/refinedstorage2.json create mode 100644 refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/entities/refinedstorage2.json create mode 100644 refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/slots/refinedstorage2.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 74151d0ef..4591c4278 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Added - "Open Wireless Grid" keybinding. +- Curios integration on Forge. ### Changed diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index c37ee3642..1356e971f 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -22,6 +22,8 @@ import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -153,9 +155,15 @@ GridScrollingStrategy createGridScrollingStrategy(AbstractContainerMenu containe NetworkBoundItemHelper getNetworkBoundItemHelper(); - SlotReference createSlotReference(FriendlyByteBuf buf); + PlatformRegistry getSlotReferenceFactoryRegistry(); - SlotReference createSlotReference(Player player, InteractionHand hand); + void writeSlotReference(SlotReference slotReference, FriendlyByteBuf buf); + + Optional getSlotReference(FriendlyByteBuf buf); + + void addSlotReferenceProvider(SlotReferenceProvider slotReferenceProvider); + + SlotReference createInventorySlotReference(Player player, InteractionHand hand); void useNetworkBoundItem(Player player, Item... items); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index ad09d3949..b142df2cc 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -22,6 +22,8 @@ import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -301,13 +303,28 @@ public NetworkBoundItemHelper getNetworkBoundItemHelper() { } @Override - public SlotReference createSlotReference(final FriendlyByteBuf buf) { - return ensureLoaded().createSlotReference(buf); + public PlatformRegistry getSlotReferenceFactoryRegistry() { + return ensureLoaded().getSlotReferenceFactoryRegistry(); } @Override - public SlotReference createSlotReference(final Player player, final InteractionHand hand) { - return ensureLoaded().createSlotReference(player, hand); + public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { + ensureLoaded().writeSlotReference(slotReference, buf); + } + + @Override + public Optional getSlotReference(final FriendlyByteBuf buf) { + return ensureLoaded().getSlotReference(buf); + } + + @Override + public void addSlotReferenceProvider(final SlotReferenceProvider slotReferenceProvider) { + ensureLoaded().addSlotReferenceProvider(slotReferenceProvider); + } + + @Override + public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { + return ensureLoaded().createInventorySlotReference(player, hand); } @Override diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java index e7a93b74e..28d0c49e2 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/AbstractNetworkBoundEnergyItem.java @@ -53,7 +53,7 @@ public void appendHoverText(final ItemStack stack, public InteractionResultHolder use(final Level level, final Player player, final InteractionHand hand) { final ItemStack stack = player.getItemInHand(hand); if (player instanceof ServerPlayer serverPlayer && level.getServer() != null) { - final SlotReference slotReference = PlatformApi.INSTANCE.createSlotReference(player, hand); + final SlotReference slotReference = PlatformApi.INSTANCE.createInventorySlotReference(player, hand); final NetworkBoundItemSession session = networkBoundItemHelper.openSession( stack, serverPlayer, diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java index 00bde9f66..c1f4541d7 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReference.java @@ -2,7 +2,7 @@ import java.util.Optional; -import io.netty.buffer.ByteBuf; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import org.apiguardian.api.API; @@ -11,7 +11,9 @@ public interface SlotReference { boolean isDisabledSlot(int playerSlotIndex); - void writeToBuf(ByteBuf buf); + void writeToBuffer(FriendlyByteBuf buf); Optional resolve(Player player); + + SlotReferenceFactory getFactory(); } diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceFactory.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceFactory.java new file mode 100644 index 000000000..d29200b50 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceFactory.java @@ -0,0 +1,9 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import net.minecraft.network.FriendlyByteBuf; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface SlotReferenceFactory { + SlotReference create(FriendlyByteBuf buf); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceProvider.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceProvider.java new file mode 100644 index 000000000..ebe5ede52 --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/item/SlotReferenceProvider.java @@ -0,0 +1,13 @@ +package com.refinedmods.refinedstorage2.platform.api.item; + +import java.util.List; +import java.util.Set; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +public interface SlotReferenceProvider { + List find(Player player, Set validItems); +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java index fde55a532..e445ddc49 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java @@ -5,6 +5,8 @@ import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.GridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.WirelessGridContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.content.Items; +import com.refinedmods.refinedstorage2.platform.common.content.KeyMappings; import com.refinedmods.refinedstorage2.platform.common.content.Menus; import com.refinedmods.refinedstorage2.platform.common.internal.resource.FluidResourceRendering; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ItemResourceRendering; @@ -25,10 +27,13 @@ import com.refinedmods.refinedstorage2.platform.common.screen.grid.GridScreen; import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.FluidGridInsertionHint; +import net.minecraft.client.KeyMapping; +import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; @@ -61,6 +66,21 @@ protected static void registerResourceRendering() { PlatformApi.INSTANCE.registerResourceRendering(FluidResource.class, new FluidResourceRendering()); } + protected static void handleInputEvents() { + final Player player = Minecraft.getInstance().player; + if (player == null) { + return; + } + final KeyMapping openWirelessGrid = KeyMappings.INSTANCE.getOpenWirelessGrid(); + while (openWirelessGrid != null && openWirelessGrid.consumeClick()) { + PlatformApi.INSTANCE.useNetworkBoundItem( + player, + Items.INSTANCE.getWirelessGrid(), + Items.INSTANCE.getCreativeWirelessGrid() + ); + } + } + @FunctionalInterface public interface ScreenRegistration { > void register(MenuType type, diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index bcdf8d559..9a08fe597 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -26,6 +26,8 @@ import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; @@ -47,9 +49,11 @@ import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridInsertionStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; +import com.refinedmods.refinedstorage2.platform.common.internal.item.CompositeSlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReference; +import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReferenceFactory; import com.refinedmods.refinedstorage2.platform.common.internal.item.NetworkBoundItemHelperImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.item.SlotReferenceImpl; import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; @@ -77,15 +81,14 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; -import java.util.OptionalInt; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; -import net.minecraft.ChatFormatting; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Player; @@ -145,6 +148,11 @@ public class PlatformApiImpl implements PlatformApi { new CompositeWirelessTransmitterRangeModifier(); private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); private final NetworkBoundItemHelper networkBoundItemHelper = new NetworkBoundItemHelperImpl(); + private final PlatformRegistry slotReferenceFactoryRegistry = new PlatformRegistryImpl<>( + createIdentifier("inventory"), + InventorySlotReferenceFactory.INSTANCE + ); + private final CompositeSlotReferenceProvider slotReferenceProvider = new CompositeSlotReferenceProvider(); @Override public PlatformRegistry> getStorageTypeRegistry() { @@ -432,49 +440,43 @@ public NetworkBoundItemHelper getNetworkBoundItemHelper() { } @Override - public SlotReference createSlotReference(final FriendlyByteBuf buf) { - return SlotReferenceImpl.of(buf); + public PlatformRegistry getSlotReferenceFactoryRegistry() { + return slotReferenceFactoryRegistry; } @Override - public SlotReference createSlotReference(final Player player, final InteractionHand hand) { - return SlotReferenceImpl.of(player, hand); + public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { + this.slotReferenceFactoryRegistry.getId(slotReference.getFactory()).ifPresentOrElse(id -> { + buf.writeBoolean(true); + buf.writeResourceLocation(id); + slotReference.writeToBuffer(buf); + }, () -> buf.writeBoolean(false)); } @Override - public void useNetworkBoundItem(final Player player, final Item... items) { - findItem(player, items).ifPresent( - slotIndex -> Platform.INSTANCE.getClientToServerCommunications().sendUseNetworkBoundItem( - new SlotReferenceImpl(slotIndex) - ) - ); + public Optional getSlotReference(final FriendlyByteBuf buf) { + if (!buf.readBoolean()) { + return Optional.empty(); + } + final ResourceLocation id = buf.readResourceLocation(); + return slotReferenceFactoryRegistry.get(id).map(factory -> factory.create(buf)); } - private OptionalInt findItem(final Player player, final Item... items) { + @Override + public void addSlotReferenceProvider(final SlotReferenceProvider provider) { + slotReferenceProvider.addProvider(provider); + } + + @Override + public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { + return InventorySlotReference.of(player, hand); + } + + @Override + public void useNetworkBoundItem(final Player player, final Item... items) { final Set validItems = new HashSet<>(Arrays.asList(items)); - OptionalInt slotIndex = OptionalInt.empty(); - for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { - final ItemStack slot = player.getInventory().getItem(i); - if (!validItems.contains(slot.getItem())) { - continue; - } - if (slotIndex.isPresent()) { - player.sendSystemMessage(createTranslation( - "item", - "network_item.cannot_open_with_shortcut_due_to_duplicate", - items[0].getDescription() - ).withStyle(ChatFormatting.RED)); - return OptionalInt.empty(); - } - slotIndex = OptionalInt.of(i); - } - if (slotIndex.isEmpty()) { - player.sendSystemMessage(createTranslation( - "item", - "network_item.cannot_open_because_not_found", - items[0].getDescription() - ).withStyle(ChatFormatting.RED)); - } - return slotIndex; + slotReferenceProvider.findForUse(player, items[0], validItems).ifPresent( + slotReference -> Platform.INSTANCE.getClientToServerCommunications().sendUseNetworkBoundItem(slotReference) + ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java index 64c42d950..25e3988a5 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/AbstractSingleAmountContainerMenu.java @@ -27,7 +27,7 @@ protected AbstractSingleAmountContainerMenu(final MenuType type, final Component filterHelpText) { super(type, syncId); if (buf.readBoolean()) { - disabledSlot = PlatformApi.INSTANCE.createSlotReference(buf); + disabledSlot = PlatformApi.INSTANCE.getSlotReference(buf).orElse(null); } this.clientAmount = buf.readDouble(); this.filterHelpText = filterHelpText; @@ -70,7 +70,7 @@ public static void writeToBuf(final FriendlyByteBuf buf, @Nullable final SlotReference disabledSlotReference) { if (disabledSlotReference != null) { buf.writeBoolean(true); - disabledSlotReference.writeToBuf(buf); + PlatformApi.INSTANCE.writeSlotReference(disabledSlotReference, buf); } else { buf.writeBoolean(false); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java index 487a1bef7..f2b3adab6 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/grid/WirelessGridContainerMenu.java @@ -11,16 +11,16 @@ public class WirelessGridContainerMenu extends AbstractGridContainerMenu { public WirelessGridContainerMenu(final int syncId, final Inventory playerInventory, final FriendlyByteBuf buf) { super(Menus.INSTANCE.getWirelessGrid(), syncId, playerInventory, buf); - this.disabledSlot = PlatformApi.INSTANCE.createSlotReference(buf); + this.disabledSlot = PlatformApi.INSTANCE.getSlotReference(buf).orElse(null); addSlots(0); } public WirelessGridContainerMenu(final int syncId, final Inventory playerInventory, final Grid grid, - final SlotReference itemReference) { + final SlotReference slotReference) { super(Menus.INSTANCE.getWirelessGrid(), syncId, playerInventory, grid); - this.disabledSlot = itemReference; + this.disabledSlot = slotReference; addSlots(0); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/CompositeSlotReferenceProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/CompositeSlotReferenceProvider.java new file mode 100644 index 000000000..09149ca82 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/CompositeSlotReferenceProvider.java @@ -0,0 +1,54 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.item; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import net.minecraft.ChatFormatting; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; + +public class CompositeSlotReferenceProvider implements SlotReferenceProvider { + private final List providers = new ArrayList<>(List.of( + new InventorySlotReferenceProvider() + )); + + public void addProvider(final SlotReferenceProvider provider) { + providers.add(provider); + } + + @Override + public List find(final Player player, final Set validItems) { + return providers.stream().flatMap(p -> p.find(player, validItems).stream()).collect(Collectors.toList()); + } + + public Optional findForUse(final Player player, + final Item referenceItem, + final Set validItems) { + final List foundReferences = find(player, validItems); + if (foundReferences.size() > 1) { + player.sendSystemMessage(createTranslation( + "item", + "network_item.cannot_open_with_shortcut_due_to_duplicate", + referenceItem.getDescription() + ).withStyle(ChatFormatting.RED)); + return Optional.empty(); + } + if (foundReferences.isEmpty()) { + player.sendSystemMessage(createTranslation( + "item", + "network_item.cannot_open_because_not_found", + referenceItem.getDescription() + ).withStyle(ChatFormatting.RED)); + return Optional.empty(); + } + return Optional.of(foundReferences.get(0)); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReference.java similarity index 68% rename from refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java rename to refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReference.java index f6350deb8..e0c7424fd 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/SlotReferenceImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReference.java @@ -1,19 +1,20 @@ package com.refinedmods.refinedstorage2.platform.common.internal.item; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; import java.util.Optional; -import io.netty.buffer.ByteBuf; +import net.minecraft.network.FriendlyByteBuf; import net.minecraft.world.InteractionHand; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; -public final class SlotReferenceImpl implements SlotReference { +public final class InventorySlotReference implements SlotReference { private final int slotIndex; - public SlotReferenceImpl(final int slotIndex) { + public InventorySlotReference(final int slotIndex) { this.slotIndex = slotIndex; } @@ -26,22 +27,23 @@ public Optional resolve(final Player player) { return Optional.of(item); } + @Override + public SlotReferenceFactory getFactory() { + return InventorySlotReferenceFactory.INSTANCE; + } + @Override public boolean isDisabledSlot(final int playerSlotIndex) { return playerSlotIndex == slotIndex; } @Override - public void writeToBuf(final ByteBuf buf) { + public void writeToBuffer(final FriendlyByteBuf buf) { buf.writeInt(slotIndex); } - public static SlotReference of(final ByteBuf buf) { - return new SlotReferenceImpl(buf.readInt()); - } - public static SlotReference of(final Player player, final InteractionHand hand) { - return new SlotReferenceImpl(hand == InteractionHand.MAIN_HAND + return new InventorySlotReference(hand == InteractionHand.MAIN_HAND ? player.getInventory().selected : Inventory.SLOT_OFFHAND); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceFactory.java new file mode 100644 index 000000000..b344b840f --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceFactory.java @@ -0,0 +1,18 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.item; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; + +import net.minecraft.network.FriendlyByteBuf; + +public class InventorySlotReferenceFactory implements SlotReferenceFactory { + public static final SlotReferenceFactory INSTANCE = new InventorySlotReferenceFactory(); + + private InventorySlotReferenceFactory() { + } + + @Override + public SlotReference create(final FriendlyByteBuf buf) { + return new InventorySlotReference(buf.readInt()); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceProvider.java new file mode 100644 index 000000000..9b0b28b6e --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/item/InventorySlotReferenceProvider.java @@ -0,0 +1,27 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.item; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; + +public class InventorySlotReferenceProvider implements SlotReferenceProvider { + @Override + public List find(final Player player, final Set validItems) { + final List result = new ArrayList<>(); + for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { + final ItemStack slot = player.getInventory().getItem(i); + if (!validItems.contains(slot.getItem())) { + continue; + } + result.add(new InventorySlotReference(i)); + } + return result; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java index 3333e7069..1443590bb 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java @@ -50,7 +50,7 @@ public InteractionResultHolder use(final Level level, final Player pl getResourceFilterContainer(stack), getAmount(stack), newAmount -> setAmount(stack, newAmount), - PlatformApi.INSTANCE.createSlotReference(player, hand) + PlatformApi.INSTANCE.createInventorySlotReference(player, hand) )); } return InteractionResultHolder.success(stack); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java index 686917f5e..a938057ae 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/menu/WirelessGridExtendedMenuProvider.java @@ -1,5 +1,6 @@ package com.refinedmods.refinedstorage2.platform.common.menu; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; @@ -16,12 +17,12 @@ import net.minecraft.world.inventory.AbstractContainerMenu; public class WirelessGridExtendedMenuProvider extends GridExtendedMenuProvider { - private final SlotReference itemReference; + private final SlotReference slotReference; public WirelessGridExtendedMenuProvider(final Grid grid, final PlatformRegistry> storageChannelTypeRegistry, - final SlotReference itemReference) { + final SlotReference slotReference) { super(grid, storageChannelTypeRegistry, new MenuProvider() { @Override public Component getDisplayName() { @@ -30,15 +31,15 @@ public Component getDisplayName() { @Override public AbstractContainerMenu createMenu(final int syncId, final Inventory inventory, final Player player) { - return new WirelessGridContainerMenu(syncId, inventory, grid, itemReference); + return new WirelessGridContainerMenu(syncId, inventory, grid, slotReference); } }); - this.itemReference = itemReference; + this.slotReference = slotReference; } @Override public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByteBuf buf) { super.writeScreenOpeningData(player, buf); - itemReference.writeToBuf(buf); + PlatformApi.INSTANCE.writeSlotReference(slotReference, buf); } } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index a63c6c115..fabd5813a 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -217,6 +217,7 @@ "key.refinedstorage2.open_wireless_grid": "Open Wireless Grid", "refinedstorage2.subtitle.wrench": "Wrench used", "category.refinedstorage2.key_bindings": "Refined Storage 2", + "curios.identifier.refinedstorage2": "Refined Storage 2", "text.autoconfig.refinedstorage2.title": "Refined Storage 2", "text.autoconfig.refinedstorage2.option.grid": "Grid", "text.autoconfig.refinedstorage2.option.grid.largeFont": "Large font", diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java index 44be51ce9..88b9851f9 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java @@ -45,7 +45,6 @@ import net.fabricmc.fabric.api.client.rendering.v1.TooltipComponentCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.KeyMapping; -import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; @@ -54,7 +53,6 @@ import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.item.ItemProperties; import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.DyeColor; @@ -296,20 +294,7 @@ private void registerKeyBindings() { InputConstants.UNKNOWN.getValue(), KEY_BINDINGS_TRANSLATION_KEY ))); - ClientTickEvents.END_CLIENT_TICK.register(client -> { - final Player player = Minecraft.getInstance().player; - if (player == null) { - return; - } - final KeyMapping openWirelessGrid = KeyMappings.INSTANCE.getOpenWirelessGrid(); - while (openWirelessGrid != null && openWirelessGrid.consumeClick()) { - PlatformApi.INSTANCE.useNetworkBoundItem( - player, - Items.INSTANCE.getWirelessGrid(), - Items.INSTANCE.getCreativeWirelessGrid() - ); - } - }); + ClientTickEvents.END_CLIENT_TICK.register(client -> handleInputEvents()); } private void registerModelPredicates() { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java index f2a27a06f..1d079ed41 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/ClientToServerCommunicationsImpl.java @@ -129,7 +129,10 @@ public void sendSingleAmountChange(final double amount) { @Override public void sendUseNetworkBoundItem(final SlotReference slotReference) { - sendToServer(PacketIds.USE_NETWORK_BOUND_ITEM, slotReference::writeToBuf); + sendToServer( + PacketIds.USE_NETWORK_BOUND_ITEM, + buf -> PlatformApi.INSTANCE.writeSlotReference(slotReference, buf) + ); } private static void sendToServer(final ResourceLocation id, final Consumer bufConsumer) { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java index 74d730799..11396275e 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/packet/c2s/UseNetworkBoundItemPacket.java @@ -5,6 +5,8 @@ import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemSession; import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import java.util.Optional; + import net.fabricmc.fabric.api.networking.v1.PacketSender; import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; import net.minecraft.network.FriendlyByteBuf; @@ -19,8 +21,8 @@ public void receive(final MinecraftServer server, final ServerGamePacketListenerImpl handler, final FriendlyByteBuf buf, final PacketSender responseSender) { - final SlotReference slotReference = PlatformApi.INSTANCE.createSlotReference(buf); - server.execute(() -> slotReference.resolve(player).ifPresent(stack -> { + final Optional slotRefMaybe = PlatformApi.INSTANCE.getSlotReference(buf); + server.execute(() -> slotRefMaybe.ifPresent(slotReference -> slotReference.resolve(player).ifPresent(stack -> { if (!(stack.getItem() instanceof AbstractNetworkBoundEnergyItem networkBoundItem)) { return; } @@ -30,6 +32,6 @@ public void receive(final MinecraftServer server, slotReference ); networkBoundItem.use(player, slotReference, sess); - })); + }))); } } diff --git a/refinedstorage2-platform-forge/build.gradle b/refinedstorage2-platform-forge/build.gradle index dbb51f66c..2223434c7 100644 --- a/refinedstorage2-platform-forge/build.gradle +++ b/refinedstorage2-platform-forge/build.gradle @@ -7,6 +7,9 @@ repositories { name = 'REI' url 'https://maven.shedaniel.me/' } + maven { + url = "https://maven.theillusivec4.top/" + } } forgeProject("refinedstorage2", project(":refinedstorage2-platform-common"), apis, compileApis) @@ -24,6 +27,9 @@ dependencies { compileOnly fg.deobf(forge.rei.cloth.math.get()) // runtimeOnly fg.deobf(forge.rei.impl.get()) // runtimeOnly fg.deobf(forge.rei.architectury.get()) + + runtimeOnly fg.deobf("top.theillusivec4.curios:curios-forge:5.2.0+1.20.1") + compileOnly fg.deobf("top.theillusivec4.curios:curios-forge:5.2.0+1.20.1:api") } enablePublishing() diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java index b43b6535c..8005d9c8c 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java @@ -25,14 +25,12 @@ import com.mojang.blaze3d.platform.InputConstants; import net.minecraft.client.KeyMapping; -import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screens.MenuScreens; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.inventory.MenuAccess; import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; import net.minecraft.client.renderer.blockentity.BlockEntityRenderers; import net.minecraft.client.renderer.item.ItemProperties; -import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.inventory.MenuType; import net.minecraftforge.client.event.InputEvent; @@ -82,18 +80,7 @@ public > void @SubscribeEvent public static void onKeyInput(final InputEvent.Key e) { - final Player player = Minecraft.getInstance().player; - if (player == null) { - return; - } - final KeyMapping openWirelessGrid = KeyMappings.INSTANCE.getOpenWirelessGrid(); - if (openWirelessGrid != null && openWirelessGrid.isDown()) { - PlatformApi.INSTANCE.useNetworkBoundItem( - player, - Items.INSTANCE.getWirelessGrid(), - Items.INSTANCE.getCreativeWirelessGrid() - ); - } + handleInputEvents(); } private static void registerModelPredicates() { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java index 1d68050dd..3ebba0e32 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ModInitializer.java @@ -20,6 +20,8 @@ import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; import com.refinedmods.refinedstorage2.platform.forge.block.entity.ForgeDiskDriveBlockEntity; +import com.refinedmods.refinedstorage2.platform.forge.integration.curios.CuriosSlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.forge.integration.curios.CuriosSlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.forge.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.FluidGridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.forge.internal.grid.FluidGridInsertionStrategy; @@ -112,6 +114,7 @@ public ModInitializer() { registerSounds(); registerRecipeSerializers(); registerTickHandler(); + registerSlotReferenceProviders(); DistExecutor.unsafeRunWhenOn(Dist.CLIENT, () -> () -> { FMLJavaModLoadingContext.get().getModEventBus().addListener(ClientModInitializer::onClientSetup); @@ -253,6 +256,16 @@ private void registerTickHandler() { MinecraftForge.EVENT_BUS.addListener(this::onServerTick); } + protected void registerSlotReferenceProviders() { + CuriosSlotReferenceProvider.create().ifPresent(slotReferenceProvider -> { + PlatformApi.INSTANCE.getSlotReferenceFactoryRegistry().register( + createIdentifier("curios"), + CuriosSlotReferenceFactory.INSTANCE + ); + PlatformApi.INSTANCE.addSlotReferenceProvider(slotReferenceProvider); + }); + } + @SubscribeEvent public void onCommonSetup(final FMLCommonSetupEvent e) { registerUpgradeMappings(); diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReference.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReference.java new file mode 100644 index 000000000..ab5589eaf --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReference.java @@ -0,0 +1,46 @@ +package com.refinedmods.refinedstorage2.platform.forge.integration.curios; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; + +import java.util.Optional; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; +import top.theillusivec4.curios.api.CuriosApi; +import top.theillusivec4.curios.api.SlotResult; + +public class CuriosSlotReference implements SlotReference { + private final String identifier; + private final int index; + + public CuriosSlotReference(final String identifier, final int index) { + this.identifier = identifier; + this.index = index; + } + + @Override + public boolean isDisabledSlot(final int playerSlotIndex) { + return false; + } + + @Override + public void writeToBuffer(final FriendlyByteBuf buf) { + buf.writeUtf(identifier); + buf.writeInt(index); + } + + @Override + public Optional resolve(final Player player) { + return CuriosApi.getCuriosInventory(player) + .resolve() + .flatMap(curiosInventory -> curiosInventory.findCurio(identifier, index)) + .map(SlotResult::stack); + } + + @Override + public SlotReferenceFactory getFactory() { + return CuriosSlotReferenceFactory.INSTANCE; + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceFactory.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceFactory.java new file mode 100644 index 000000000..5cc8274e8 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceFactory.java @@ -0,0 +1,18 @@ +package com.refinedmods.refinedstorage2.platform.forge.integration.curios; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; + +import net.minecraft.network.FriendlyByteBuf; + +public class CuriosSlotReferenceFactory implements SlotReferenceFactory { + public static final SlotReferenceFactory INSTANCE = new CuriosSlotReferenceFactory(); + + private CuriosSlotReferenceFactory() { + } + + @Override + public SlotReference create(final FriendlyByteBuf buf) { + return new CuriosSlotReference(buf.readUtf(), buf.readInt()); + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceProvider.java new file mode 100644 index 000000000..a9a7bcb2b --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/CuriosSlotReferenceProvider.java @@ -0,0 +1,41 @@ +package com.refinedmods.refinedstorage2.platform.forge.integration.curios; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; +import net.minecraftforge.fml.ModList; +import top.theillusivec4.curios.api.CuriosApi; + +public class CuriosSlotReferenceProvider implements SlotReferenceProvider { + private CuriosSlotReferenceProvider() { + } + + @Override + public List find(final Player player, final Set validItems) { + return CuriosApi.getCuriosInventory(player) + .resolve() + .map(curiosInventory -> curiosInventory.findCurios("refinedstorage2")) + .orElse(Collections.emptyList()) + .stream() + .filter(slotResult -> validItems.contains(slotResult.stack().getItem())) + .map(slotResult -> (SlotReference) new CuriosSlotReference( + slotResult.slotContext().identifier(), + slotResult.slotContext().index() + )) + .toList(); + } + + public static Optional create() { + if (!ModList.get().isLoaded("curios")) { + return Optional.empty(); + } + return Optional.of(new CuriosSlotReferenceProvider()); + } +} diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/package-info.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/package-info.java new file mode 100644 index 000000000..9fa3e224b --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/curios/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.forge.integration.curios; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java index 1824a1899..9eeb6fe31 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/packet/c2s/UseNetworkBoundItemPacket.java @@ -6,24 +6,28 @@ import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; import java.util.function.Supplier; +import javax.annotation.Nullable; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerPlayer; import net.minecraftforge.network.NetworkEvent; +import static java.util.Objects.requireNonNull; + public class UseNetworkBoundItemPacket { + @Nullable private final SlotReference slotReference; - public UseNetworkBoundItemPacket(final SlotReference slotReference) { + public UseNetworkBoundItemPacket(@Nullable final SlotReference slotReference) { this.slotReference = slotReference; } public static UseNetworkBoundItemPacket decode(final FriendlyByteBuf buf) { - return new UseNetworkBoundItemPacket(PlatformApi.INSTANCE.createSlotReference(buf)); + return new UseNetworkBoundItemPacket(PlatformApi.INSTANCE.getSlotReference(buf).orElse(null)); } public static void encode(final UseNetworkBoundItemPacket packet, final FriendlyByteBuf buf) { - packet.slotReference.writeToBuf(buf); + PlatformApi.INSTANCE.writeSlotReference(requireNonNull(packet.slotReference), buf); } public static void handle(final UseNetworkBoundItemPacket packet, final Supplier ctx) { @@ -35,6 +39,9 @@ public static void handle(final UseNetworkBoundItemPacket packet, final Supplier } private static void handle(final UseNetworkBoundItemPacket packet, final ServerPlayer player) { + if (packet.slotReference == null) { + return; + } packet.slotReference.resolve(player).ifPresent(stack -> { if (!(stack.getItem() instanceof AbstractNetworkBoundEnergyItem networkBoundItem)) { return; diff --git a/refinedstorage2-platform-forge/src/main/resources/assets/refinedstorage2/textures/slot/curios.png b/refinedstorage2-platform-forge/src/main/resources/assets/refinedstorage2/textures/slot/curios.png new file mode 100644 index 0000000000000000000000000000000000000000..90fb5ee2eb92322229c786daabac7a9df8483bd7 GIT binary patch literal 261 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`jKx9jP7LeL$-D$|SkfJR9T^xl z_H+M9WCij$3p^r=85sBugD~Uq{1quc!C9Uzjv*HQ$$$R;w`W#u;Pet^3F4PotFkO zoHMBS_drhBsEsR`p^I5?IpYxvd7cT(EbE;#7*;x7YZmI=A;fJ}QTAWY#%F_6gZ704 zJr^?uWu6bM7G{<`XIxH5pV-#S@V7|0?7#sAhEEd;`8Mx0-wSjlgQu&X%Q~loCIHrE BQ$hd$ literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-forge/src/main/resources/data/curios/tags/items/refinedstorage2.json b/refinedstorage2-platform-forge/src/main/resources/data/curios/tags/items/refinedstorage2.json new file mode 100644 index 000000000..778353b57 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/resources/data/curios/tags/items/refinedstorage2.json @@ -0,0 +1,7 @@ +{ + "replace": false, + "values": [ + "refinedstorage2:wireless_grid", + "refinedstorage2:creative_wireless_grid" + ] +} \ No newline at end of file diff --git a/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/entities/refinedstorage2.json b/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/entities/refinedstorage2.json new file mode 100644 index 000000000..6cc2d352f --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/entities/refinedstorage2.json @@ -0,0 +1,8 @@ +{ + "entities": [ + "player" + ], + "slots": [ + "refinedstorage2" + ] +} \ No newline at end of file diff --git a/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/slots/refinedstorage2.json b/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/slots/refinedstorage2.json new file mode 100644 index 000000000..1d751f8d6 --- /dev/null +++ b/refinedstorage2-platform-forge/src/main/resources/data/refinedstorage2/curios/slots/refinedstorage2.json @@ -0,0 +1,5 @@ +{ + "order": 5, + "size": 2, + "icon": "refinedstorage2:slot/curios" +} \ No newline at end of file From 522bda5e95015cebe119af8c42ec40923a76c9a2 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Sat, 2 Sep 2023 20:06:44 +0200 Subject: [PATCH 08/11] feat: trinkets integration on Fabric --- CHANGELOG.md | 1 + .../assets/refinedstorage2/lang/en_us.json | 1 + refinedstorage2-platform-fabric/build.gradle | 7 +++ .../platform/fabric/ModInitializerImpl.java | 13 +++++ .../trinkets/TrinketsSlotReference.java | 48 ++++++++++++++++++ .../TrinketsSlotReferenceFactory.java | 18 +++++++ .../TrinketsSlotReferenceProvider.java | 47 +++++++++++++++++ .../integration/trinkets/package-info.java | 7 +++ .../textures/slot/trinkets.png | Bin 0 -> 173 bytes .../trinkets/entities/refinedstorage2.json | 8 +++ .../slots/refinedstorage2/wireless.json | 5 ++ .../tags/items/refinedstorage2/wireless.json | 7 +++ 12 files changed, 162 insertions(+) create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReference.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceFactory.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceProvider.java create mode 100644 refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/package-info.java create mode 100644 refinedstorage2-platform-fabric/src/main/resources/assets/refinedstorage2/textures/slot/trinkets.png create mode 100644 refinedstorage2-platform-fabric/src/main/resources/data/trinkets/entities/refinedstorage2.json create mode 100644 refinedstorage2-platform-fabric/src/main/resources/data/trinkets/slots/refinedstorage2/wireless.json create mode 100644 refinedstorage2-platform-fabric/src/main/resources/data/trinkets/tags/items/refinedstorage2/wireless.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 4591c4278..0a05cfdcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - "Open Wireless Grid" keybinding. - Curios integration on Forge. +- Trinkets integration on Fabric. ### Changed diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index fabd5813a..e02294bde 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -218,6 +218,7 @@ "refinedstorage2.subtitle.wrench": "Wrench used", "category.refinedstorage2.key_bindings": "Refined Storage 2", "curios.identifier.refinedstorage2": "Refined Storage 2", + "trinkets.slot.refinedstorage2.wireless": "Refined Storage 2", "text.autoconfig.refinedstorage2.title": "Refined Storage 2", "text.autoconfig.refinedstorage2.option.grid": "Grid", "text.autoconfig.refinedstorage2.option.grid.largeFont": "Large font", diff --git a/refinedstorage2-platform-fabric/build.gradle b/refinedstorage2-platform-fabric/build.gradle index bf1f2670b..9f1ed55e3 100644 --- a/refinedstorage2-platform-fabric/build.gradle +++ b/refinedstorage2-platform-fabric/build.gradle @@ -21,6 +21,10 @@ repositories { name = 'NoIndium' url = 'https://maven.cafeteria.dev/releases/' } + maven { + name = "Trinkets" + url = 'https://maven.ladysnake.org/releases' + } } fabricProject("refinedstorage2", project(":refinedstorage2-platform-common"), apis, compileApis) @@ -57,6 +61,9 @@ dependencies { // modRuntimeOnly fabric.jei.impl modRuntimeOnly fabric.wthit + + // https://www.curseforge.com/minecraft/mc-mods/trinkets/files + modImplementation "dev.emi:trinkets:3.7.1" } enablePublishing() diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java index baff85bd3..ab9396031 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ModInitializerImpl.java @@ -21,6 +21,8 @@ import com.refinedmods.refinedstorage2.platform.common.item.WirelessGridItem; import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; import com.refinedmods.refinedstorage2.platform.fabric.block.entity.FabricDiskDriveBlockEntity; +import com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets.TrinketsSlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets.TrinketsSlotReferenceProvider; import com.refinedmods.refinedstorage2.platform.fabric.internal.energy.EnergyStorageAdapter; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.FluidGridExtractionStrategy; import com.refinedmods.refinedstorage2.platform.fabric.internal.grid.FluidGridInsertionStrategy; @@ -111,6 +113,7 @@ public void onInitialize() { registerRecipeSerializers(new DirectRegistryCallback<>(BuiltInRegistries.RECIPE_SERIALIZER)); registerSidedHandlers(); registerTickHandler(); + registerSlotReferenceProviders(); registerWrenchingEvent(); LOGGER.info("Refined Storage 2 has loaded."); @@ -357,6 +360,16 @@ private void registerTickHandler() { ServerTickEvents.START_SERVER_TICK.register(server -> TickHandler.runQueuedActions()); } + private void registerSlotReferenceProviders() { + TrinketsSlotReferenceProvider.create().ifPresent(slotReferenceProvider -> { + PlatformApi.INSTANCE.getSlotReferenceFactoryRegistry().register( + createIdentifier("trinkets"), + TrinketsSlotReferenceFactory.INSTANCE + ); + PlatformApi.INSTANCE.addSlotReferenceProvider(slotReferenceProvider); + }); + } + private void registerWrenchingEvent() { UseBlockCallback.EVENT.register((player, level, hand, hitResult) -> { final BlockState state = level.getBlockState(hitResult.getBlockPos()); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReference.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReference.java new file mode 100644 index 000000000..9eafb71b1 --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReference.java @@ -0,0 +1,48 @@ +package com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; + +import java.util.Optional; + +import dev.emi.trinkets.api.TrinketsApi; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; + +public class TrinketsSlotReference implements SlotReference { + private final String groupName; + private final String slotName; + private final int index; + + public TrinketsSlotReference(final String groupName, final String slotName, final int index) { + this.groupName = groupName; + this.slotName = slotName; + this.index = index; + } + + @Override + public boolean isDisabledSlot(final int playerSlotIndex) { + return false; + } + + @Override + public void writeToBuffer(final FriendlyByteBuf buf) { + buf.writeUtf(groupName); + buf.writeUtf(slotName); + buf.writeInt(index); + } + + @Override + public Optional resolve(final Player player) { + return TrinketsApi.getTrinketComponent(player) + .map(trinkets -> trinkets.getInventory().get(groupName)) + .map(groupMap -> groupMap.get(slotName)) + .map(trinketInventory -> trinketInventory.getItem(index)); + } + + @Override + public SlotReferenceFactory getFactory() { + return TrinketsSlotReferenceFactory.INSTANCE; + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceFactory.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceFactory.java new file mode 100644 index 000000000..54f3aed7c --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceFactory.java @@ -0,0 +1,18 @@ +package com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; + +import net.minecraft.network.FriendlyByteBuf; + +public class TrinketsSlotReferenceFactory implements SlotReferenceFactory { + public static final SlotReferenceFactory INSTANCE = new TrinketsSlotReferenceFactory(); + + private TrinketsSlotReferenceFactory() { + } + + @Override + public SlotReference create(final FriendlyByteBuf buf) { + return new TrinketsSlotReference(buf.readUtf(), buf.readUtf(), buf.readInt()); + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceProvider.java new file mode 100644 index 000000000..515659b10 --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/TrinketsSlotReferenceProvider.java @@ -0,0 +1,47 @@ +package com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets; + +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import dev.emi.trinkets.api.TrinketsApi; +import net.minecraft.util.Tuple; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.Item; + +public class TrinketsSlotReferenceProvider implements SlotReferenceProvider { + @Override + public List find(final Player player, final Set validItems) { + return TrinketsApi.getTrinketComponent(player) + .map(trinkets -> trinkets.getEquipped(s -> validItems.contains(s.getItem()))) + .orElse(Collections.emptyList()) + .stream() + .map(Tuple::getA) + .map(trinketsSlotReference -> (SlotReference) new TrinketsSlotReference( + trinketsSlotReference.inventory().getSlotType().getGroup(), + trinketsSlotReference.inventory().getSlotType().getName(), + trinketsSlotReference.index() + )) + .toList(); + } + + public static Optional create() { + if (!isTrinketsLoaded()) { + return Optional.empty(); + } + return Optional.of(new TrinketsSlotReferenceProvider()); + } + + private static boolean isTrinketsLoaded() { + try { + Class.forName("dev.emi.trinkets.api.TrinketsApi"); + return true; + } catch (ClassNotFoundException e) { + return false; + } + } +} diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/package-info.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/package-info.java new file mode 100644 index 000000000..f247c4b8b --- /dev/null +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/trinkets/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.fabric.integration.trinkets; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-fabric/src/main/resources/assets/refinedstorage2/textures/slot/trinkets.png b/refinedstorage2-platform-fabric/src/main/resources/assets/refinedstorage2/textures/slot/trinkets.png new file mode 100644 index 0000000000000000000000000000000000000000..2d0f73a53d75815c628ba03d8f25950de7c2888b GIT binary patch literal 173 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!73?$#)eFPF Date: Sun, 3 Sep 2023 10:30:13 +0200 Subject: [PATCH 09/11] feat: storage monitor --- CHANGELOG.md | 1 + .../platform/api/PlatformApi.java | 10 + .../platform/api/PlatformApiProxy.java | 704 +++++++------ .../StorageMonitorExtractionStrategy.java | 13 + .../StorageMonitorInsertionStrategy.java | 15 + .../storagemonitor/package-info.java | 7 + .../api/resource/ResourceRendering.java | 7 +- .../common/AbstractClientModInitializer.java | 2 + .../common/AbstractModInitializer.java | 35 +- .../platform/common/Config.java | 2 + .../platform/common/ContainedFluid.java | 9 + .../platform/common/Platform.java | 3 +- .../platform/common/PlatformApiImpl.java | 992 +++++++++--------- .../platform/common/PlatformProxy.java | 5 +- .../common/block/StorageMonitorBlock.java | 101 ++ .../block/entity/ControllerBlockEntity.java | 8 +- .../block/entity/ImporterBlockEntity.java | 5 +- .../constructor/ConstructorBlockEntity.java | 5 +- .../destructor/DestructorBlockEntity.java | 5 +- .../entity/detector/DetectorBlockEntity.java | 5 +- .../AbstractDiskDriveBlockEntity.java | 12 +- .../entity/exporter/ExporterBlockEntity.java | 5 +- .../ExternalStorageBlockEntity.java | 5 +- .../entity/grid/CraftingGridBlockEntity.java | 5 +- .../block/entity/grid/GridBlockEntity.java | 5 +- .../entity/iface/InterfaceBlockEntity.java | 5 +- ...ositeStorageMonitorExtractionStrategy.java | 32 + ...positeStorageMonitorInsertionStrategy.java | 31 + ...FluidStorageMonitorExtractionStrategy.java | 42 + .../FluidStorageMonitorInsertionStrategy.java | 69 ++ .../entity/storagemonitor/InsertTracker.java | 37 + .../ItemStorageMonitorExtractionStrategy.java | 36 + .../ItemStorageMonitorInsertionStrategy.java | 37 + .../StorageMonitorBlockEntity.java | 317 ++++++ .../entity/storagemonitor/package-info.java | 7 + .../StorageMonitorContainerMenu.java | 54 + .../common/content/BlockEntities.java | 11 + .../platform/common/content/Blocks.java | 11 + .../platform/common/content/ContentIds.java | 1 + .../platform/common/content/ContentNames.java | 4 + .../common/content/CreativeModeTabItems.java | 1 + .../common/content/DefaultEnergyUsage.java | 2 + .../platform/common/content/Menus.java | 11 + .../resource/FluidResourceFactory.java | 4 +- .../resource/FluidResourceRendering.java | 17 +- .../resource/ItemResourceRendering.java | 34 +- .../resource/ResourceContainerImpl.java | 1 + ...ucketPlayerInventoryInsertableStorage.java | 89 ++ .../common/item/RegulatorUpgradeItem.java | 3 +- .../platform/common/render/FluidRenderer.java | 3 + .../StorageMonitorBlockEntityRenderer.java | 137 +++ .../render/model/AbstractFluidRenderer.java | 47 + .../common/screen/AbstractBaseScreen.java | 2 +- .../common/screen/StorageMonitorScreen.java | 41 + .../common/screen/amount/DetectorScreen.java | 2 +- .../grid/hint/FluidGridInsertionHint.java | 15 +- .../ResourceClientTooltipComponent.java | 2 +- .../widget/FuzzyModeSideButtonWidget.java | 2 +- .../platform/common/util/BiDirection.java | 32 +- .../blockstates/storage_monitor.json | 57 + .../assets/refinedstorage2/lang/en_us.json | 11 +- .../refinedstorage2/models/block/disk.json | 2 +- .../models/block/disk_drive_base.json | 10 +- .../models/block/disk_inactive.json | 2 +- .../models/block/interface_active.json | 2 +- .../models/block/interface_inactive.json | 2 +- .../models/block/storage_monitor.json | 12 + .../models/item/storage_monitor.json | 3 + .../bottom.png} | Bin .../textures/block/{ => disk_drive}/disk.png | Bin .../{disk_drive.png => disk_drive/front.png} | Bin .../side.png} | Bin .../top.png} | Bin .../active.png} | Bin .../inactive.png} | Bin .../refinedstorage2/textures/block/side.png | Bin 0 -> 15349 bytes .../textures/block/storage_monitor/back.png | Bin 0 -> 1415 bytes .../textures/block/storage_monitor/front.png | Bin 0 -> 1273 bytes .../textures/block/storage_monitor/left.png | Bin 0 -> 1451 bytes .../textures/block/storage_monitor/right.png | Bin 0 -> 1443 bytes .../textures/block/storage_monitor/top.png | Bin 0 -> 1391 bytes .../textures/gui/storage_monitor.png | Bin 0 -> 1816 bytes .../advancements/better_than_a_barrel.json | 28 + .../loot_tables/blocks/storage_monitor.json | 19 + .../recipes/storage_monitor.json | 31 + .../fabric/ClientModInitializerImpl.java | 5 + .../platform/fabric/ConfigImpl.java | 10 + .../platform/fabric/PlatformImpl.java | 36 +- .../grid/FluidGridExtractionStrategy.java | 8 +- .../render/FluidVariantFluidRenderer.java | 22 +- ...orage.java => SingleStackStorageImpl.java} | 12 +- .../platform/forge/ClientModInitializer.java | 5 + .../platform/forge/ConfigImpl.java | 11 + .../platform/forge/PlatformImpl.java | 26 +- .../forge/render/FluidStackFluidRenderer.java | 17 + .../refinedstorage2/textures/slot/curios.png | Bin 261 -> 257 bytes 96 files changed, 2492 insertions(+), 944 deletions(-) create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorExtractionStrategy.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorInsertionStrategy.java create mode 100644 refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/package-info.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/ContainedFluid.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/StorageMonitorBlock.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorExtractionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorInsertionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorExtractionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorInsertionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/InsertTracker.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorExtractionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorInsertionStrategy.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/StorageMonitorBlockEntity.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/package-info.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/StorageMonitorContainerMenu.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/storage/BucketPlayerInventoryInsertableStorage.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/entity/StorageMonitorBlockEntityRenderer.java create mode 100644 refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/StorageMonitorScreen.java create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/blockstates/storage_monitor.json create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/storage_monitor.json create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/storage_monitor.json rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{disk_drive_bottom.png => disk_drive/bottom.png} (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{ => disk_drive}/disk.png (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{disk_drive.png => disk_drive/front.png} (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{disk_drive_side.png => disk_drive/side.png} (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{disk_drive_top.png => disk_drive/top.png} (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{interface_active.png => interface/active.png} (100%) rename refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/{interface_inactive.png => interface/inactive.png} (100%) create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/side.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/back.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/front.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/left.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/right.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/top.png create mode 100644 refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/gui/storage_monitor.png create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/better_than_a_barrel.json create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/loot_tables/blocks/storage_monitor.json create mode 100644 refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/storage_monitor.json rename refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/{BucketSingleStackStorage.java => SingleStackStorageImpl.java} (54%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a05cfdcd..584a35d3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - "Open Wireless Grid" keybinding. - Curios integration on Forge. - Trinkets integration on Fabric. +- Storage Monitor ### Changed diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java index 1356e971f..5387f40f7 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApi.java @@ -7,6 +7,8 @@ import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitterRangeModifier; import com.refinedmods.refinedstorage2.platform.api.grid.Grid; import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategy; @@ -81,6 +83,14 @@ public interface PlatformApi { void addConstructorStrategyFactory(ConstructorStrategyFactory factory); + void addStorageMonitorExtractionStrategy(StorageMonitorExtractionStrategy strategy); + + StorageMonitorExtractionStrategy getStorageMonitorExtractionStrategy(); + + void addStorageMonitorInsertionStrategy(StorageMonitorInsertionStrategy strategy); + + StorageMonitorInsertionStrategy getStorageMonitorInsertionStrategy(); + MutableComponent createTranslation(String category, String value, Object... args); ComponentMapFactory getNetworkComponentMapFactory(); diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java index b142df2cc..b4f895589 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/PlatformApiProxy.java @@ -1,341 +1,363 @@ -package com.refinedmods.refinedstorage2.platform.api; - -import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; -import com.refinedmods.refinedstorage2.api.network.Network; -import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; -import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; -import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitterRangeModifier; -import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHint; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHints; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; -import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; -import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; -import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; -import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.api.network.node.importer.ImporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.resource.ResourceFactory; -import com.refinedmods.refinedstorage2.platform.api.resource.ResourceRendering; -import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; -import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; -import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; - -import java.util.Collection; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nullable; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; - -public class PlatformApiProxy implements PlatformApi { - @Nullable - private PlatformApi delegate; - - public void setDelegate(final PlatformApi delegate) { - if (this.delegate != null) { - throw new IllegalStateException("Platform API already injected"); - } - this.delegate = delegate; - } - - @Override - public PlatformRegistry> getStorageTypeRegistry() { - return ensureLoaded().getStorageTypeRegistry(); - } - - @Override - public StorageRepository getStorageRepository(final Level level) { - return ensureLoaded().getStorageRepository(level); - } - - @Override - public StorageContainerItemHelper getStorageContainerItemHelper() { - return ensureLoaded().getStorageContainerItemHelper(); - } - - @Override - public PlatformRegistry> getStorageChannelTypeRegistry() { - return ensureLoaded().getStorageChannelTypeRegistry(); - } - - @Override - public PlatformRegistry getImporterTransferStrategyRegistry() { - return ensureLoaded().getImporterTransferStrategyRegistry(); - } - - @Override - public PlatformRegistry getExporterTransferStrategyRegistry() { - return ensureLoaded().getExporterTransferStrategyRegistry(); - } - - @Override - public void addExternalStorageProviderFactory(final PlatformExternalStorageProviderFactory factory) { - ensureLoaded().addExternalStorageProviderFactory(factory); - } - - @Override - public Collection getExternalStorageProviderFactories() { - return ensureLoaded().getExternalStorageProviderFactories(); - } - - @Override - public Collection getDestructorStrategyFactories() { - return ensureLoaded().getDestructorStrategyFactories(); - } - - @Override - public void addDestructorStrategyFactory(final DestructorStrategyFactory factory) { - ensureLoaded().addDestructorStrategyFactory(factory); - } - - @Override - public Collection getConstructorStrategyFactories() { - return ensureLoaded().getConstructorStrategyFactories(); - } - - @Override - public void addConstructorStrategyFactory(final ConstructorStrategyFactory factory) { - ensureLoaded().addConstructorStrategyFactory(factory); - } - - @Override - public MutableComponent createTranslation(final String category, final String value, final Object... args) { - return ensureLoaded().createTranslation(category, value, args); - } - - @Override - public ComponentMapFactory getNetworkComponentMapFactory() { - return ensureLoaded().getNetworkComponentMapFactory(); - } - - @Override - public PlatformRegistry getGridSynchronizerRegistry() { - return ensureLoaded().getGridSynchronizerRegistry(); - } - - @Override - public UpgradeRegistry getUpgradeRegistry() { - return ensureLoaded().getUpgradeRegistry(); - } - - @Override - public BuiltinUpgradeDestinations getBuiltinUpgradeDestinations() { - return ensureLoaded().getBuiltinUpgradeDestinations(); - } - - @Override - public void requestNetworkNodeInitialization(final NetworkNodeContainer container, - final Level level, - final Runnable callback) { - ensureLoaded().requestNetworkNodeInitialization(container, level, callback); - } - - @Override - public void requestNetworkNodeRemoval(final NetworkNodeContainer container, final Level level) { - ensureLoaded().requestNetworkNodeRemoval(container, level); - } - - @Override - public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { - ensureLoaded().requestNetworkNodeUpdate(container, level); - } - - @Override - public GridInsertionStrategy createGridInsertionStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - return ensureLoaded().createGridInsertionStrategy(containerMenu, player, grid); - } - - @Override - public void addGridInsertionStrategyFactory(final GridInsertionStrategyFactory insertionStrategyFactory) { - ensureLoaded().addGridInsertionStrategyFactory(insertionStrategyFactory); - } - - @Override - public void addAlternativeGridInsertionHint(final GridInsertionHint hint) { - ensureLoaded().addAlternativeGridInsertionHint(hint); - } - - @Override - public GridInsertionHints getGridInsertionHints() { - return ensureLoaded().getGridInsertionHints(); - } - - @Override - public GridExtractionStrategy createGridExtractionStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - return ensureLoaded().createGridExtractionStrategy(containerMenu, player, grid); - } - - @Override - public void addGridExtractionStrategyFactory(final GridExtractionStrategyFactory extractionStrategyFactory) { - ensureLoaded().addGridExtractionStrategyFactory(extractionStrategyFactory); - } - - @Override - public GridScrollingStrategy createGridScrollingStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - return ensureLoaded().createGridScrollingStrategy(containerMenu, player, grid); - } - - @Override - public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory scrollingStrategyFactory) { - ensureLoaded().addGridScrollingStrategyFactory(scrollingStrategyFactory); - } - - @Override - public void addResourceFactory(final ResourceFactory factory) { - ensureLoaded().addResourceFactory(factory); - } - - @Override - public ResourceFactory getItemResourceFactory() { - return ensureLoaded().getItemResourceFactory(); - } - - @Override - public PlatformStorageChannelType getItemStorageChannelType() { - return ensureLoaded().getItemStorageChannelType(); - } - - @Override - public StorageType getItemStorageType() { - return ensureLoaded().getItemStorageType(); - } - - @Override - public ResourceFactory getFluidResourceFactory() { - return ensureLoaded().getFluidResourceFactory(); - } - - @Override - public PlatformStorageChannelType getFluidStorageChannelType() { - return ensureLoaded().getFluidStorageChannelType(); - } - - @Override - public StorageType getFluidStorageType() { - return ensureLoaded().getFluidStorageType(); - } - - @Override - public Set> getAlternativeResourceFactories() { - return ensureLoaded().getAlternativeResourceFactories(); - } - - @Override - public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { - ensureLoaded().registerResourceRendering(resourceClass, rendering); - } - - @Override - public ResourceRendering getResourceRendering(final T resource) { - return ensureLoaded().getResourceRendering(resource); - } - - @Override - public void registerIngredientConverter(final IngredientConverter converter) { - ensureLoaded().registerIngredientConverter(converter); - } - - @Override - public IngredientConverter getIngredientConverter() { - return ensureLoaded().getIngredientConverter(); - } - - @Override - public void addWirelessTransmitterRangeModifier(final WirelessTransmitterRangeModifier rangeModifier) { - ensureLoaded().addWirelessTransmitterRangeModifier(rangeModifier); - } - - @Override - public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { - return ensureLoaded().getWirelessTransmitterRangeModifier(); - } - - @Override - public Optional getEnergyStorage(final ItemStack stack) { - return ensureLoaded().getEnergyStorage(stack); - } - - @Override - public EnergyItemHelper getEnergyItemHelper() { - return ensureLoaded().getEnergyItemHelper(); - } - - @Override - public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { - return ensureLoaded().asItemEnergyStorage(energyStorage, stack); - } - - @Override - public NetworkBoundItemHelper getNetworkBoundItemHelper() { - return ensureLoaded().getNetworkBoundItemHelper(); - } - - @Override - public PlatformRegistry getSlotReferenceFactoryRegistry() { - return ensureLoaded().getSlotReferenceFactoryRegistry(); - } - - @Override - public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { - ensureLoaded().writeSlotReference(slotReference, buf); - } - - @Override - public Optional getSlotReference(final FriendlyByteBuf buf) { - return ensureLoaded().getSlotReference(buf); - } - - @Override - public void addSlotReferenceProvider(final SlotReferenceProvider slotReferenceProvider) { - ensureLoaded().addSlotReferenceProvider(slotReferenceProvider); - } - - @Override - public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { - return ensureLoaded().createInventorySlotReference(player, hand); - } - - @Override - public void useNetworkBoundItem(final Player player, final Item... items) { - ensureLoaded().useNetworkBoundItem(player, items); - } - - private PlatformApi ensureLoaded() { - if (delegate == null) { - throw new IllegalStateException("Platform API not loaded yet"); - } - return delegate; - } -} +package com.refinedmods.refinedstorage2.platform.api; + +import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitterRangeModifier; +import com.refinedmods.refinedstorage2.platform.api.grid.Grid; +import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHint; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHints; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; +import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; +import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; +import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; +import com.refinedmods.refinedstorage2.platform.api.network.node.importer.ImporterTransferStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceFactory; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceRendering; +import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; +import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; +import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; + +import java.util.Collection; +import java.util.Optional; +import java.util.Set; +import javax.annotation.Nullable; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +public class PlatformApiProxy implements PlatformApi { + @Nullable + private PlatformApi delegate; + + public void setDelegate(final PlatformApi delegate) { + if (this.delegate != null) { + throw new IllegalStateException("Platform API already injected"); + } + this.delegate = delegate; + } + + @Override + public PlatformRegistry> getStorageTypeRegistry() { + return ensureLoaded().getStorageTypeRegistry(); + } + + @Override + public StorageRepository getStorageRepository(final Level level) { + return ensureLoaded().getStorageRepository(level); + } + + @Override + public StorageContainerItemHelper getStorageContainerItemHelper() { + return ensureLoaded().getStorageContainerItemHelper(); + } + + @Override + public PlatformRegistry> getStorageChannelTypeRegistry() { + return ensureLoaded().getStorageChannelTypeRegistry(); + } + + @Override + public PlatformRegistry getImporterTransferStrategyRegistry() { + return ensureLoaded().getImporterTransferStrategyRegistry(); + } + + @Override + public PlatformRegistry getExporterTransferStrategyRegistry() { + return ensureLoaded().getExporterTransferStrategyRegistry(); + } + + @Override + public void addExternalStorageProviderFactory(final PlatformExternalStorageProviderFactory factory) { + ensureLoaded().addExternalStorageProviderFactory(factory); + } + + @Override + public Collection getExternalStorageProviderFactories() { + return ensureLoaded().getExternalStorageProviderFactories(); + } + + @Override + public Collection getDestructorStrategyFactories() { + return ensureLoaded().getDestructorStrategyFactories(); + } + + @Override + public void addDestructorStrategyFactory(final DestructorStrategyFactory factory) { + ensureLoaded().addDestructorStrategyFactory(factory); + } + + @Override + public Collection getConstructorStrategyFactories() { + return ensureLoaded().getConstructorStrategyFactories(); + } + + @Override + public void addConstructorStrategyFactory(final ConstructorStrategyFactory factory) { + ensureLoaded().addConstructorStrategyFactory(factory); + } + + @Override + public void addStorageMonitorExtractionStrategy(final StorageMonitorExtractionStrategy strategy) { + ensureLoaded().addStorageMonitorExtractionStrategy(strategy); + } + + @Override + public StorageMonitorExtractionStrategy getStorageMonitorExtractionStrategy() { + return ensureLoaded().getStorageMonitorExtractionStrategy(); + } + + @Override + public void addStorageMonitorInsertionStrategy(final StorageMonitorInsertionStrategy strategy) { + ensureLoaded().addStorageMonitorInsertionStrategy(strategy); + } + + @Override + public StorageMonitorInsertionStrategy getStorageMonitorInsertionStrategy() { + return ensureLoaded().getStorageMonitorInsertionStrategy(); + } + + @Override + public MutableComponent createTranslation(final String category, final String value, final Object... args) { + return ensureLoaded().createTranslation(category, value, args); + } + + @Override + public ComponentMapFactory getNetworkComponentMapFactory() { + return ensureLoaded().getNetworkComponentMapFactory(); + } + + @Override + public PlatformRegistry getGridSynchronizerRegistry() { + return ensureLoaded().getGridSynchronizerRegistry(); + } + + @Override + public UpgradeRegistry getUpgradeRegistry() { + return ensureLoaded().getUpgradeRegistry(); + } + + @Override + public BuiltinUpgradeDestinations getBuiltinUpgradeDestinations() { + return ensureLoaded().getBuiltinUpgradeDestinations(); + } + + @Override + public void requestNetworkNodeInitialization(final NetworkNodeContainer container, + final Level level, + final Runnable callback) { + ensureLoaded().requestNetworkNodeInitialization(container, level, callback); + } + + @Override + public void requestNetworkNodeRemoval(final NetworkNodeContainer container, final Level level) { + ensureLoaded().requestNetworkNodeRemoval(container, level); + } + + @Override + public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { + ensureLoaded().requestNetworkNodeUpdate(container, level); + } + + @Override + public GridInsertionStrategy createGridInsertionStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + return ensureLoaded().createGridInsertionStrategy(containerMenu, player, grid); + } + + @Override + public void addGridInsertionStrategyFactory(final GridInsertionStrategyFactory insertionStrategyFactory) { + ensureLoaded().addGridInsertionStrategyFactory(insertionStrategyFactory); + } + + @Override + public void addAlternativeGridInsertionHint(final GridInsertionHint hint) { + ensureLoaded().addAlternativeGridInsertionHint(hint); + } + + @Override + public GridInsertionHints getGridInsertionHints() { + return ensureLoaded().getGridInsertionHints(); + } + + @Override + public GridExtractionStrategy createGridExtractionStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + return ensureLoaded().createGridExtractionStrategy(containerMenu, player, grid); + } + + @Override + public void addGridExtractionStrategyFactory(final GridExtractionStrategyFactory extractionStrategyFactory) { + ensureLoaded().addGridExtractionStrategyFactory(extractionStrategyFactory); + } + + @Override + public GridScrollingStrategy createGridScrollingStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + return ensureLoaded().createGridScrollingStrategy(containerMenu, player, grid); + } + + @Override + public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory scrollingStrategyFactory) { + ensureLoaded().addGridScrollingStrategyFactory(scrollingStrategyFactory); + } + + @Override + public void addResourceFactory(final ResourceFactory factory) { + ensureLoaded().addResourceFactory(factory); + } + + @Override + public ResourceFactory getItemResourceFactory() { + return ensureLoaded().getItemResourceFactory(); + } + + @Override + public PlatformStorageChannelType getItemStorageChannelType() { + return ensureLoaded().getItemStorageChannelType(); + } + + @Override + public StorageType getItemStorageType() { + return ensureLoaded().getItemStorageType(); + } + + @Override + public ResourceFactory getFluidResourceFactory() { + return ensureLoaded().getFluidResourceFactory(); + } + + @Override + public PlatformStorageChannelType getFluidStorageChannelType() { + return ensureLoaded().getFluidStorageChannelType(); + } + + @Override + public StorageType getFluidStorageType() { + return ensureLoaded().getFluidStorageType(); + } + + @Override + public Set> getAlternativeResourceFactories() { + return ensureLoaded().getAlternativeResourceFactories(); + } + + @Override + public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { + ensureLoaded().registerResourceRendering(resourceClass, rendering); + } + + @Override + public ResourceRendering getResourceRendering(final T resource) { + return ensureLoaded().getResourceRendering(resource); + } + + @Override + public void registerIngredientConverter(final IngredientConverter converter) { + ensureLoaded().registerIngredientConverter(converter); + } + + @Override + public IngredientConverter getIngredientConverter() { + return ensureLoaded().getIngredientConverter(); + } + + @Override + public void addWirelessTransmitterRangeModifier(final WirelessTransmitterRangeModifier rangeModifier) { + ensureLoaded().addWirelessTransmitterRangeModifier(rangeModifier); + } + + @Override + public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { + return ensureLoaded().getWirelessTransmitterRangeModifier(); + } + + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return ensureLoaded().getEnergyStorage(stack); + } + + @Override + public EnergyItemHelper getEnergyItemHelper() { + return ensureLoaded().getEnergyItemHelper(); + } + + @Override + public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, final ItemStack stack) { + return ensureLoaded().asItemEnergyStorage(energyStorage, stack); + } + + @Override + public NetworkBoundItemHelper getNetworkBoundItemHelper() { + return ensureLoaded().getNetworkBoundItemHelper(); + } + + @Override + public PlatformRegistry getSlotReferenceFactoryRegistry() { + return ensureLoaded().getSlotReferenceFactoryRegistry(); + } + + @Override + public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { + ensureLoaded().writeSlotReference(slotReference, buf); + } + + @Override + public Optional getSlotReference(final FriendlyByteBuf buf) { + return ensureLoaded().getSlotReference(buf); + } + + @Override + public void addSlotReferenceProvider(final SlotReferenceProvider slotReferenceProvider) { + ensureLoaded().addSlotReferenceProvider(slotReferenceProvider); + } + + @Override + public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { + return ensureLoaded().createInventorySlotReference(player, hand); + } + + @Override + public void useNetworkBoundItem(final Player player, final Item... items) { + ensureLoaded().useNetworkBoundItem(player, items); + } + + private PlatformApi ensureLoaded() { + if (delegate == null) { + throw new IllegalStateException("Platform API not loaded yet"); + } + return delegate; + } +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorExtractionStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorExtractionStrategy.java new file mode 100644 index 000000000..519fd326a --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorExtractionStrategy.java @@ -0,0 +1,13 @@ +package com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.storage.Actor; + +import net.minecraft.world.entity.player.Player; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +@FunctionalInterface +public interface StorageMonitorExtractionStrategy { + boolean extract(Object resource, boolean fullStack, Player player, Actor actor, Network network); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorInsertionStrategy.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorInsertionStrategy.java new file mode 100644 index 000000000..b2168b22c --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/StorageMonitorInsertionStrategy.java @@ -0,0 +1,15 @@ +package com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.storage.Actor; + +import java.util.Optional; + +import net.minecraft.world.item.ItemStack; +import org.apiguardian.api.API; + +@API(status = API.Status.STABLE, since = "2.0.0-milestone.3.1") +@FunctionalInterface +public interface StorageMonitorInsertionStrategy { + Optional insert(Object configuredResource, ItemStack stack, Actor actor, Network network); +} diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/package-info.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/package-info.java new file mode 100644 index 000000000..34cea1edd --- /dev/null +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/blockentity/storagemonitor/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/ResourceRendering.java b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/ResourceRendering.java index 1e6cd6f8e..87bc86a42 100644 --- a/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/ResourceRendering.java +++ b/refinedstorage2-platform-api/src/main/java/com/refinedmods/refinedstorage2/platform/api/resource/ResourceRendering.java @@ -2,17 +2,22 @@ import java.util.List; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.network.chat.Component; +import net.minecraft.world.level.Level; import org.apiguardian.api.API; @API(status = API.Status.STABLE, since = "2.0.0-milestone.2.13") public interface ResourceRendering { - String getDisplayedAmount(long amount); + String getDisplayedAmount(long amount, boolean withUnits); Component getDisplayName(T resource); List getTooltip(T resource); void render(T resource, GuiGraphics graphics, int x, int y); + + void render(T resource, PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, Level level); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java index e445ddc49..8fb4b7f45 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractClientModInitializer.java @@ -21,6 +21,7 @@ import com.refinedmods.refinedstorage2.platform.common.screen.InterfaceScreen; import com.refinedmods.refinedstorage2.platform.common.screen.ItemStorageBlockScreen; import com.refinedmods.refinedstorage2.platform.common.screen.RegulatorUpgradeScreen; +import com.refinedmods.refinedstorage2.platform.common.screen.StorageMonitorScreen; import com.refinedmods.refinedstorage2.platform.common.screen.WirelessTransmitterScreen; import com.refinedmods.refinedstorage2.platform.common.screen.amount.DetectorScreen; import com.refinedmods.refinedstorage2.platform.common.screen.grid.CraftingGridScreen; @@ -55,6 +56,7 @@ protected static void registerScreens(final ScreenRegistration registration) { registration.register(Menus.INSTANCE.getConstructor(), ConstructorScreen::new); registration.register(Menus.INSTANCE.getRegulatorUpgrade(), RegulatorUpgradeScreen::new); registration.register(Menus.INSTANCE.getWirelessTransmitter(), WirelessTransmitterScreen::new); + registration.register(Menus.INSTANCE.getStorageMonitor(), StorageMonitorScreen::new); } protected static void registerAlternativeGridHints() { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java index d8eb8065c..161c294ef 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/AbstractModInitializer.java @@ -13,6 +13,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.InterfaceBlock; import com.refinedmods.refinedstorage2.platform.common.block.ItemStorageBlock; import com.refinedmods.refinedstorage2.platform.common.block.SimpleBlock; +import com.refinedmods.refinedstorage2.platform.common.block.StorageMonitorBlock; import com.refinedmods.refinedstorage2.platform.common.block.entity.CableBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.ControllerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.ImporterBlockEntity; @@ -34,6 +35,11 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.iface.InterfaceBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.FluidStorageBlockBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.ItemStorageBlockBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.FluidStorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.FluidStorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.ItemStorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.ItemStorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.StorageMonitorBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.BaseWirelessTransmitterRangeModifier; import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.CreativeRangeUpgradeWirelessTransmitterRangeModifier; import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.RangeUpgradeWirelessTransmitterRangeModifier; @@ -45,6 +51,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.InterfaceContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.RegulatorUpgradeContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.containermenu.StorageMonitorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.WirelessTransmitterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.detector.DetectorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.CraftingGridContainerMenu; @@ -108,6 +115,7 @@ import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CONTROLLER; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CRAFTING_GRID; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CREATIVE_CONTROLLER; +import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.CREATIVE_WIRELESS_GRID; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.DESTRUCTION_CORE; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.DESTRUCTOR; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.DETECTOR; @@ -127,6 +135,7 @@ import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.SILICON; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_BLOCK; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_HOUSING; +import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.STORAGE_MONITOR; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.WIRELESS_GRID; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.WIRELESS_TRANSMITTER; import static com.refinedmods.refinedstorage2.platform.common.content.ContentIds.WRENCH; @@ -153,6 +162,8 @@ protected final void initializePlatformApi() { registerAdditionalResourceFactories(); registerDestructorStrategyFactories(); registerConstructorStrategyFactories(); + registerStorageMonitorInsertionStrategies(); + registerStorageMonitorExtractionStrategies(); registerNetworkComponents(); registerWirelessTransmitterRangeModifiers(); } @@ -191,6 +202,16 @@ private void registerConstructorStrategyFactories() { PlatformApi.INSTANCE.addConstructorStrategyFactory(new ItemDropConstructorStrategyFactory()); } + private void registerStorageMonitorInsertionStrategies() { + PlatformApi.INSTANCE.addStorageMonitorInsertionStrategy(new ItemStorageMonitorInsertionStrategy()); + PlatformApi.INSTANCE.addStorageMonitorInsertionStrategy(new FluidStorageMonitorInsertionStrategy()); + } + + private void registerStorageMonitorExtractionStrategies() { + PlatformApi.INSTANCE.addStorageMonitorExtractionStrategy(new ItemStorageMonitorExtractionStrategy()); + PlatformApi.INSTANCE.addStorageMonitorExtractionStrategy(new FluidStorageMonitorExtractionStrategy()); + } + private void registerNetworkComponents() { PlatformApi.INSTANCE.getNetworkComponentMapFactory().addFactory( EnergyNetworkComponent.class, @@ -250,6 +271,7 @@ protected final void registerBlocks( Blocks.INSTANCE.getDestructor().registerBlocks(callback); Blocks.INSTANCE.setInterface(callback.register(INTERFACE, InterfaceBlock::new)); Blocks.INSTANCE.getWirelessTransmitter().registerBlocks(callback); + Blocks.INSTANCE.setStorageMonitor(callback.register(STORAGE_MONITOR, StorageMonitorBlock::new)); } protected final void registerItems( @@ -273,11 +295,12 @@ protected final void registerItems( Blocks.INSTANCE.getWirelessTransmitter().registerItems(callback, Items.INSTANCE::addWirelessTransmitter); registerStorageItems(callback); registerUpgrades(callback, regulatorUpgradeItemSupplier); - Items.INSTANCE.setWirelessGrid(callback.register(ContentIds.WIRELESS_GRID, wirelessGridItemSupplier)); + Items.INSTANCE.setWirelessGrid(callback.register(WIRELESS_GRID, wirelessGridItemSupplier)); Items.INSTANCE.setCreativeWirelessGrid(callback.register( - ContentIds.CREATIVE_WIRELESS_GRID, + CREATIVE_WIRELESS_GRID, creativeWirelessGridItemSupplier )); + callback.register(STORAGE_MONITOR, () -> new SimpleBlockItem(Blocks.INSTANCE.getStorageMonitor())); } private void registerSimpleItems(final RegistryCallback callback) { @@ -531,6 +554,10 @@ protected final void registerBlockEntities( Blocks.INSTANCE.getWirelessTransmitter().toArray() ) )); + BlockEntities.INSTANCE.setStorageMonitor(callback.register( + STORAGE_MONITOR, + () -> typeFactory.create(StorageMonitorBlockEntity::new, Blocks.INSTANCE.getStorageMonitor()) + )); } protected final void registerMenus(final RegistryCallback> callback, @@ -599,6 +626,10 @@ protected final void registerMenus(final RegistryCallback> callback, WIRELESS_TRANSMITTER, () -> menuTypeFactory.create(WirelessTransmitterContainerMenu::new) )); + Menus.INSTANCE.setStorageMonitor(callback.register( + STORAGE_MONITOR, + () -> menuTypeFactory.create(StorageMonitorContainerMenu::new) + )); } protected final void registerLootFunctions(final RegistryCallback callback) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java index 70523581c..7f89c1abb 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Config.java @@ -44,6 +44,8 @@ public interface Config { WirelessTransmitterEntry getWirelessTransmitter(); + SimpleEnergyUsageEntry getStorageMonitor(); + interface SimpleEnergyUsageEntry { long getEnergyUsage(); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/ContainedFluid.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/ContainedFluid.java new file mode 100644 index 000000000..f5d161b7c --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/ContainedFluid.java @@ -0,0 +1,9 @@ +package com.refinedmods.refinedstorage2.platform.common; + +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; + +import net.minecraft.world.item.ItemStack; + +public record ContainedFluid(ItemStack remainderContainer, ResourceAmount fluid) { +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java index 79ca84bb4..4368389a8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/Platform.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; @@ -74,7 +73,7 @@ public interface Platform { FluidRenderer getFluidRenderer(); - Optional> convertToFluid(ItemStack stack); + Optional getContainedFluid(ItemStack stack); Optional convertJeiIngredientToFluid(Object ingredient); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java index 9a08fe597..ccd58f6ad 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformApiImpl.java @@ -1,482 +1,510 @@ -package com.refinedmods.refinedstorage2.platform.common; - -import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; -import com.refinedmods.refinedstorage2.api.network.Network; -import com.refinedmods.refinedstorage2.api.network.NetworkBuilder; -import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; -import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.network.impl.NetworkBuilderImpl; -import com.refinedmods.refinedstorage2.api.network.impl.NetworkFactory; -import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; -import com.refinedmods.refinedstorage2.platform.api.PlatformApi; -import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitterRangeModifier; -import com.refinedmods.refinedstorage2.platform.api.grid.Grid; -import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHint; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHints; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; -import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; -import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; -import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; -import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; -import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; -import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; -import com.refinedmods.refinedstorage2.platform.api.network.node.importer.ImporterTransferStrategyFactory; -import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; -import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; -import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; -import com.refinedmods.refinedstorage2.platform.api.resource.ResourceFactory; -import com.refinedmods.refinedstorage2.platform.api.resource.ResourceRendering; -import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; -import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; -import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; -import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; -import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; -import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.CompositeWirelessTransmitterRangeModifier; -import com.refinedmods.refinedstorage2.platform.common.integration.recipemod.CompositeIngredientConverter; -import com.refinedmods.refinedstorage2.platform.common.internal.energy.ItemEnergyStorage; -import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridExtractionStrategy; -import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridInsertionStrategy; -import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; -import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; -import com.refinedmods.refinedstorage2.platform.common.internal.item.CompositeSlotReferenceProvider; -import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReference; -import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReferenceFactory; -import com.refinedmods.refinedstorage2.platform.common.internal.item.NetworkBoundItemHelperImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; -import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.resource.FluidResourceFactory; -import com.refinedmods.refinedstorage2.platform.common.internal.resource.ItemResourceFactory; -import com.refinedmods.refinedstorage2.platform.common.internal.storage.ClientStorageRepository; -import com.refinedmods.refinedstorage2.platform.common.internal.storage.StorageRepositoryImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; -import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.StorageTypes; -import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.BuiltinUpgradeDestinationsImpl; -import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeRegistryImpl; -import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.GridInsertionHintsImpl; -import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.ItemGridInsertionHint; -import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.SingleItemGridInsertionHint; -import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; -import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.PriorityQueue; -import java.util.Queue; -import java.util.Set; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; - -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; - -public class PlatformApiImpl implements PlatformApi { - private static final String ITEM_REGISTRY_KEY = "item"; - - private final StorageRepository clientStorageRepository = - new ClientStorageRepository(Platform.INSTANCE.getClientToServerCommunications()::sendStorageInfoRequest); - private final ComponentMapFactory networkComponentMapFactory = - new ComponentMapFactory<>(); - private final NetworkBuilder networkBuilder = - new NetworkBuilderImpl(new NetworkFactory(networkComponentMapFactory)); - private final PlatformRegistry> storageTypeRegistry = - new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageTypes.ITEM); - private final PlatformRegistry> storageChannelTypeRegistry = - new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageChannelTypes.ITEM); - private final PlatformRegistry gridSynchronizerRegistry = - new PlatformRegistryImpl<>(createIdentifier("off"), new NoOpGridSynchronizer()); - private final PlatformRegistry importerTransferStrategyRegistry = - new PlatformRegistryImpl<>(createIdentifier("noop"), - (level, pos, direction, upgradeState, amountOverride) -> (filter, actor, network) -> false); - private final PlatformRegistry exporterTransferStrategyRegistry = - new PlatformRegistryImpl<>(createIdentifier("noop"), - (level, pos, direction, upgradeState, amountOverride, fuzzyMode) -> (resource, actor, network) -> false); - private final UpgradeRegistry upgradeRegistry = new UpgradeRegistryImpl(); - private final BuiltinUpgradeDestinations builtinUpgradeDestinations = new BuiltinUpgradeDestinationsImpl(); - private final Queue externalStorageProviderFactories = new PriorityQueue<>( - Comparator.comparingInt(PlatformExternalStorageProviderFactory::getPriority) - ); - private final Queue destructorStrategyFactories = new PriorityQueue<>( - Comparator.comparingInt(DestructorStrategyFactory::getPriority) - ); - private final Queue constructorStrategyFactories = new PriorityQueue<>( - Comparator.comparingInt(ConstructorStrategyFactory::getPriority) - ); - private final CompositeIngredientConverter compositeConverter = new CompositeIngredientConverter(); - private final StorageContainerItemHelper storageContainerItemHelper = new StorageContainerItemHelperImpl(); - private final List gridInsertionStrategyFactories = new ArrayList<>(); - private final GridInsertionHintsImpl gridInsertionHints = new GridInsertionHintsImpl( - new ItemGridInsertionHint(), - new SingleItemGridInsertionHint() - ); - private final List gridExtractionStrategyFactories = new ArrayList<>(); - private final List gridScrollingStrategyFactories = new ArrayList<>(); - private final ResourceFactory itemResourceFactory = new ItemResourceFactory(); - private final ResourceFactory fluidResourceFactory = new FluidResourceFactory(); - private final Set> resourceFactories = new HashSet<>(); - private final Map, ResourceRendering> resourceRenderingMap = new HashMap<>(); - private final CompositeWirelessTransmitterRangeModifier wirelessTransmitterRangeModifier = - new CompositeWirelessTransmitterRangeModifier(); - private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); - private final NetworkBoundItemHelper networkBoundItemHelper = new NetworkBoundItemHelperImpl(); - private final PlatformRegistry slotReferenceFactoryRegistry = new PlatformRegistryImpl<>( - createIdentifier("inventory"), - InventorySlotReferenceFactory.INSTANCE - ); - private final CompositeSlotReferenceProvider slotReferenceProvider = new CompositeSlotReferenceProvider(); - - @Override - public PlatformRegistry> getStorageTypeRegistry() { - return storageTypeRegistry; - } - - @Override - public StorageRepository getStorageRepository(final Level level) { - if (level.getServer() == null) { - return clientStorageRepository; - } - final ServerLevel serverLevel = Objects.requireNonNull(level.getServer().getLevel(Level.OVERWORLD)); - return serverLevel - .getDataStorage() - .computeIfAbsent( - this::createStorageRepository, - this::createStorageRepository, - StorageRepositoryImpl.NAME - ); - } - - @Override - public StorageContainerItemHelper getStorageContainerItemHelper() { - return storageContainerItemHelper; - } - - private StorageRepositoryImpl createStorageRepository(final CompoundTag tag) { - final StorageRepositoryImpl repository = createStorageRepository(); - repository.read(tag); - return repository; - } - - private StorageRepositoryImpl createStorageRepository() { - return new StorageRepositoryImpl(storageTypeRegistry); - } - - @Override - public PlatformRegistry> getStorageChannelTypeRegistry() { - return storageChannelTypeRegistry; - } - - @Override - public PlatformRegistry getImporterTransferStrategyRegistry() { - return importerTransferStrategyRegistry; - } - - @Override - public PlatformRegistry getExporterTransferStrategyRegistry() { - return exporterTransferStrategyRegistry; - } - - @Override - public void addExternalStorageProviderFactory(final PlatformExternalStorageProviderFactory factory) { - externalStorageProviderFactories.add(factory); - } - - @Override - public Collection getExternalStorageProviderFactories() { - return externalStorageProviderFactories; - } - - @Override - public Collection getDestructorStrategyFactories() { - return destructorStrategyFactories; - } - - @Override - public void addDestructorStrategyFactory(final DestructorStrategyFactory factory) { - destructorStrategyFactories.add(factory); - } - - @Override - public Collection getConstructorStrategyFactories() { - return constructorStrategyFactories; - } - - @Override - public void addConstructorStrategyFactory(final ConstructorStrategyFactory factory) { - constructorStrategyFactories.add(factory); - } - - @Override - public MutableComponent createTranslation(final String category, final String value, final Object... args) { - return IdentifierUtil.createTranslation(category, value, args); - } - - @Override - public ComponentMapFactory getNetworkComponentMapFactory() { - return networkComponentMapFactory; - } - - @Override - public PlatformRegistry getGridSynchronizerRegistry() { - return gridSynchronizerRegistry; - } - - @Override - public UpgradeRegistry getUpgradeRegistry() { - return upgradeRegistry; - } - - @Override - public BuiltinUpgradeDestinations getBuiltinUpgradeDestinations() { - return builtinUpgradeDestinations; - } - - @Override - public void requestNetworkNodeInitialization(final NetworkNodeContainer container, - final Level level, - final Runnable callback) { - final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); - TickHandler.runWhenReady(() -> { - networkBuilder.initialize(container, connectionProvider); - callback.run(); - }); - } - - @Override - public void requestNetworkNodeRemoval(final NetworkNodeContainer container, final Level level) { - final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); - networkBuilder.remove(container, connectionProvider); - } - - @Override - public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { - final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); - networkBuilder.update(container, connectionProvider); - } - - @Override - public GridInsertionStrategy createGridInsertionStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - return new CompositeGridInsertionStrategy( - Platform.INSTANCE.getDefaultGridInsertionStrategyFactory().create( - containerMenu, - player, - grid - ), - gridInsertionStrategyFactories.stream().map(f -> f.create( - containerMenu, - player, - grid - )).toList() - ); - } - - @Override - public void addGridInsertionStrategyFactory(final GridInsertionStrategyFactory insertionStrategyFactory) { - gridInsertionStrategyFactories.add(insertionStrategyFactory); - } - - @Override - public void addAlternativeGridInsertionHint(final GridInsertionHint hint) { - gridInsertionHints.addAlternativeHint(hint); - } - - @Override - public GridInsertionHints getGridInsertionHints() { - return gridInsertionHints; - } - - @Override - public GridExtractionStrategy createGridExtractionStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - final List strategies = gridExtractionStrategyFactories - .stream() - .map(f -> f.create(containerMenu, player, grid)) - .toList(); - return new CompositeGridExtractionStrategy(strategies); - } - - @Override - public void addGridExtractionStrategyFactory(final GridExtractionStrategyFactory extractionStrategyFactory) { - gridExtractionStrategyFactories.add(extractionStrategyFactory); - } - - @Override - public GridScrollingStrategy createGridScrollingStrategy(final AbstractContainerMenu containerMenu, - final Player player, - final Grid grid) { - final List strategies = gridScrollingStrategyFactories - .stream() - .map(f -> f.create(containerMenu, player, grid)) - .toList(); - return new CompositeGridScrollingStrategy(strategies); - } - - @Override - public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory scrollingStrategyFactory) { - gridScrollingStrategyFactories.add(scrollingStrategyFactory); - } - - @Override - public void addResourceFactory(final ResourceFactory factory) { - resourceFactories.add(factory); - } - - @Override - public ResourceFactory getItemResourceFactory() { - return itemResourceFactory; - } - - @Override - public PlatformStorageChannelType getItemStorageChannelType() { - return StorageChannelTypes.ITEM; - } - - @Override - public StorageType getItemStorageType() { - return StorageTypes.ITEM; - } - - @Override - public ResourceFactory getFluidResourceFactory() { - return fluidResourceFactory; - } - - @Override - public PlatformStorageChannelType getFluidStorageChannelType() { - return StorageChannelTypes.FLUID; - } - - @Override - public StorageType getFluidStorageType() { - return StorageTypes.FLUID; - } - - @Override - public Set> getAlternativeResourceFactories() { - return resourceFactories; - } - - @Override - public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { - resourceRenderingMap.put(resourceClass, rendering); - } - - @Override - @SuppressWarnings("unchecked") - public ResourceRendering getResourceRendering(final T resource) { - return (ResourceRendering) resourceRenderingMap.get(resource.getClass()); - } - - @Override - public void registerIngredientConverter(final IngredientConverter converter) { - this.compositeConverter.addConverter(converter); - } - - @Override - public IngredientConverter getIngredientConverter() { - return compositeConverter; - } - - @Override - public void addWirelessTransmitterRangeModifier(final WirelessTransmitterRangeModifier rangeModifier) { - wirelessTransmitterRangeModifier.addModifier(rangeModifier); - } - - @Override - public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { - return wirelessTransmitterRangeModifier; - } - - @Override - public Optional getEnergyStorage(final ItemStack stack) { - return Platform.INSTANCE.getEnergyStorage(stack); - } - - @Override - public EnergyItemHelper getEnergyItemHelper() { - return energyItemHelper; - } - - @Override - public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, - final ItemStack stack) { - return new ItemEnergyStorage(stack, energyStorage); - } - - @Override - public NetworkBoundItemHelper getNetworkBoundItemHelper() { - return networkBoundItemHelper; - } - - @Override - public PlatformRegistry getSlotReferenceFactoryRegistry() { - return slotReferenceFactoryRegistry; - } - - @Override - public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { - this.slotReferenceFactoryRegistry.getId(slotReference.getFactory()).ifPresentOrElse(id -> { - buf.writeBoolean(true); - buf.writeResourceLocation(id); - slotReference.writeToBuffer(buf); - }, () -> buf.writeBoolean(false)); - } - - @Override - public Optional getSlotReference(final FriendlyByteBuf buf) { - if (!buf.readBoolean()) { - return Optional.empty(); - } - final ResourceLocation id = buf.readResourceLocation(); - return slotReferenceFactoryRegistry.get(id).map(factory -> factory.create(buf)); - } - - @Override - public void addSlotReferenceProvider(final SlotReferenceProvider provider) { - slotReferenceProvider.addProvider(provider); - } - - @Override - public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { - return InventorySlotReference.of(player, hand); - } - - @Override - public void useNetworkBoundItem(final Player player, final Item... items) { - final Set validItems = new HashSet<>(Arrays.asList(items)); - slotReferenceProvider.findForUse(player, items[0], validItems).ifPresent( - slotReference -> Platform.INSTANCE.getClientToServerCommunications().sendUseNetworkBoundItem(slotReference) - ); - } -} +package com.refinedmods.refinedstorage2.platform.common; + +import com.refinedmods.refinedstorage2.api.core.component.ComponentMapFactory; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.NetworkBuilder; +import com.refinedmods.refinedstorage2.api.network.component.NetworkComponent; +import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; +import com.refinedmods.refinedstorage2.api.network.impl.NetworkBuilderImpl; +import com.refinedmods.refinedstorage2.api.network.impl.NetworkFactory; +import com.refinedmods.refinedstorage2.api.network.node.container.NetworkNodeContainer; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.blockentity.constructor.ConstructorStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.blockentity.destructor.DestructorStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.blockentity.wirelesstransmitter.WirelessTransmitterRangeModifier; +import com.refinedmods.refinedstorage2.platform.api.grid.Grid; +import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridExtractionStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHint; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHints; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategy; +import com.refinedmods.refinedstorage2.platform.api.grid.GridScrollingStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.grid.GridSynchronizer; +import com.refinedmods.refinedstorage2.platform.api.integration.recipemod.IngredientConverter; +import com.refinedmods.refinedstorage2.platform.api.item.EnergyItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.NetworkBoundItemHelper; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReference; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.api.item.SlotReferenceProvider; +import com.refinedmods.refinedstorage2.platform.api.item.StorageContainerItemHelper; +import com.refinedmods.refinedstorage2.platform.api.network.node.exporter.ExporterTransferStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.network.node.externalstorage.PlatformExternalStorageProviderFactory; +import com.refinedmods.refinedstorage2.platform.api.network.node.importer.ImporterTransferStrategyFactory; +import com.refinedmods.refinedstorage2.platform.api.registry.PlatformRegistry; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceFactory; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceRendering; +import com.refinedmods.refinedstorage2.platform.api.storage.StorageRepository; +import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; +import com.refinedmods.refinedstorage2.platform.api.storage.type.StorageType; +import com.refinedmods.refinedstorage2.platform.api.upgrade.BuiltinUpgradeDestinations; +import com.refinedmods.refinedstorage2.platform.api.upgrade.UpgradeRegistry; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.CompositeStorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.CompositeStorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.CompositeWirelessTransmitterRangeModifier; +import com.refinedmods.refinedstorage2.platform.common.integration.recipemod.CompositeIngredientConverter; +import com.refinedmods.refinedstorage2.platform.common.internal.energy.ItemEnergyStorage; +import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.common.internal.grid.CompositeGridScrollingStrategy; +import com.refinedmods.refinedstorage2.platform.common.internal.grid.NoOpGridSynchronizer; +import com.refinedmods.refinedstorage2.platform.common.internal.item.CompositeSlotReferenceProvider; +import com.refinedmods.refinedstorage2.platform.common.internal.item.EnergyItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReference; +import com.refinedmods.refinedstorage2.platform.common.internal.item.InventorySlotReferenceFactory; +import com.refinedmods.refinedstorage2.platform.common.internal.item.NetworkBoundItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.item.StorageContainerItemHelperImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.network.LevelConnectionProvider; +import com.refinedmods.refinedstorage2.platform.common.internal.registry.PlatformRegistryImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.resource.FluidResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.internal.resource.ItemResourceFactory; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.ClientStorageRepository; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.StorageRepositoryImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.StorageTypes; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.BuiltinUpgradeDestinationsImpl; +import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeRegistryImpl; +import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.GridInsertionHintsImpl; +import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.ItemGridInsertionHint; +import com.refinedmods.refinedstorage2.platform.common.screen.grid.hint.SingleItemGridInsertionHint; +import com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil; +import com.refinedmods.refinedstorage2.platform.common.util.TickHandler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; + +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.MutableComponent; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; + +public class PlatformApiImpl implements PlatformApi { + private static final String ITEM_REGISTRY_KEY = "item"; + + private final StorageRepository clientStorageRepository = + new ClientStorageRepository(Platform.INSTANCE.getClientToServerCommunications()::sendStorageInfoRequest); + private final ComponentMapFactory networkComponentMapFactory = + new ComponentMapFactory<>(); + private final NetworkBuilder networkBuilder = + new NetworkBuilderImpl(new NetworkFactory(networkComponentMapFactory)); + private final PlatformRegistry> storageTypeRegistry = + new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageTypes.ITEM); + private final PlatformRegistry> storageChannelTypeRegistry = + new PlatformRegistryImpl<>(createIdentifier(ITEM_REGISTRY_KEY), StorageChannelTypes.ITEM); + private final PlatformRegistry gridSynchronizerRegistry = + new PlatformRegistryImpl<>(createIdentifier("off"), new NoOpGridSynchronizer()); + private final PlatformRegistry importerTransferStrategyRegistry = + new PlatformRegistryImpl<>(createIdentifier("noop"), + (level, pos, direction, upgradeState, amountOverride) -> (filter, actor, network) -> false); + private final PlatformRegistry exporterTransferStrategyRegistry = + new PlatformRegistryImpl<>(createIdentifier("noop"), + (level, pos, direction, upgradeState, amountOverride, fuzzyMode) -> (resource, actor, network) -> false); + private final UpgradeRegistry upgradeRegistry = new UpgradeRegistryImpl(); + private final BuiltinUpgradeDestinations builtinUpgradeDestinations = new BuiltinUpgradeDestinationsImpl(); + private final Queue externalStorageProviderFactories = new PriorityQueue<>( + Comparator.comparingInt(PlatformExternalStorageProviderFactory::getPriority) + ); + private final Queue destructorStrategyFactories = new PriorityQueue<>( + Comparator.comparingInt(DestructorStrategyFactory::getPriority) + ); + private final Queue constructorStrategyFactories = new PriorityQueue<>( + Comparator.comparingInt(ConstructorStrategyFactory::getPriority) + ); + private final CompositeStorageMonitorInsertionStrategy storageMonitorInsertionStrategy = + new CompositeStorageMonitorInsertionStrategy(); + private final CompositeStorageMonitorExtractionStrategy storageMonitorExtractionStrategy = + new CompositeStorageMonitorExtractionStrategy(); + private final CompositeIngredientConverter compositeConverter = new CompositeIngredientConverter(); + private final StorageContainerItemHelper storageContainerItemHelper = new StorageContainerItemHelperImpl(); + private final List gridInsertionStrategyFactories = new ArrayList<>(); + private final GridInsertionHintsImpl gridInsertionHints = new GridInsertionHintsImpl( + new ItemGridInsertionHint(), + new SingleItemGridInsertionHint() + ); + private final List gridExtractionStrategyFactories = new ArrayList<>(); + private final List gridScrollingStrategyFactories = new ArrayList<>(); + private final ResourceFactory itemResourceFactory = new ItemResourceFactory(); + private final ResourceFactory fluidResourceFactory = new FluidResourceFactory(); + private final Set> resourceFactories = new HashSet<>(); + private final Map, ResourceRendering> resourceRenderingMap = new HashMap<>(); + private final CompositeWirelessTransmitterRangeModifier wirelessTransmitterRangeModifier = + new CompositeWirelessTransmitterRangeModifier(); + private final EnergyItemHelper energyItemHelper = new EnergyItemHelperImpl(); + private final NetworkBoundItemHelper networkBoundItemHelper = new NetworkBoundItemHelperImpl(); + private final PlatformRegistry slotReferenceFactoryRegistry = new PlatformRegistryImpl<>( + createIdentifier("inventory"), + InventorySlotReferenceFactory.INSTANCE + ); + private final CompositeSlotReferenceProvider slotReferenceProvider = new CompositeSlotReferenceProvider(); + + @Override + public PlatformRegistry> getStorageTypeRegistry() { + return storageTypeRegistry; + } + + @Override + public StorageRepository getStorageRepository(final Level level) { + if (level.getServer() == null) { + return clientStorageRepository; + } + final ServerLevel serverLevel = Objects.requireNonNull(level.getServer().getLevel(Level.OVERWORLD)); + return serverLevel + .getDataStorage() + .computeIfAbsent( + this::createStorageRepository, + this::createStorageRepository, + StorageRepositoryImpl.NAME + ); + } + + @Override + public StorageContainerItemHelper getStorageContainerItemHelper() { + return storageContainerItemHelper; + } + + private StorageRepositoryImpl createStorageRepository(final CompoundTag tag) { + final StorageRepositoryImpl repository = createStorageRepository(); + repository.read(tag); + return repository; + } + + private StorageRepositoryImpl createStorageRepository() { + return new StorageRepositoryImpl(storageTypeRegistry); + } + + @Override + public PlatformRegistry> getStorageChannelTypeRegistry() { + return storageChannelTypeRegistry; + } + + @Override + public PlatformRegistry getImporterTransferStrategyRegistry() { + return importerTransferStrategyRegistry; + } + + @Override + public PlatformRegistry getExporterTransferStrategyRegistry() { + return exporterTransferStrategyRegistry; + } + + @Override + public void addExternalStorageProviderFactory(final PlatformExternalStorageProviderFactory factory) { + externalStorageProviderFactories.add(factory); + } + + @Override + public Collection getExternalStorageProviderFactories() { + return externalStorageProviderFactories; + } + + @Override + public Collection getDestructorStrategyFactories() { + return destructorStrategyFactories; + } + + @Override + public void addDestructorStrategyFactory(final DestructorStrategyFactory factory) { + destructorStrategyFactories.add(factory); + } + + @Override + public Collection getConstructorStrategyFactories() { + return constructorStrategyFactories; + } + + @Override + public void addConstructorStrategyFactory(final ConstructorStrategyFactory factory) { + constructorStrategyFactories.add(factory); + } + + @Override + public void addStorageMonitorExtractionStrategy(final StorageMonitorExtractionStrategy strategy) { + storageMonitorExtractionStrategy.addStrategy(strategy); + } + + @Override + public StorageMonitorExtractionStrategy getStorageMonitorExtractionStrategy() { + return storageMonitorExtractionStrategy; + } + + @Override + public void addStorageMonitorInsertionStrategy(final StorageMonitorInsertionStrategy strategy) { + storageMonitorInsertionStrategy.addStrategy(strategy); + } + + @Override + public StorageMonitorInsertionStrategy getStorageMonitorInsertionStrategy() { + return storageMonitorInsertionStrategy; + } + + @Override + public MutableComponent createTranslation(final String category, final String value, final Object... args) { + return IdentifierUtil.createTranslation(category, value, args); + } + + @Override + public ComponentMapFactory getNetworkComponentMapFactory() { + return networkComponentMapFactory; + } + + @Override + public PlatformRegistry getGridSynchronizerRegistry() { + return gridSynchronizerRegistry; + } + + @Override + public UpgradeRegistry getUpgradeRegistry() { + return upgradeRegistry; + } + + @Override + public BuiltinUpgradeDestinations getBuiltinUpgradeDestinations() { + return builtinUpgradeDestinations; + } + + @Override + public void requestNetworkNodeInitialization(final NetworkNodeContainer container, + final Level level, + final Runnable callback) { + final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); + TickHandler.runWhenReady(() -> { + networkBuilder.initialize(container, connectionProvider); + callback.run(); + }); + } + + @Override + public void requestNetworkNodeRemoval(final NetworkNodeContainer container, final Level level) { + final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); + networkBuilder.remove(container, connectionProvider); + } + + @Override + public void requestNetworkNodeUpdate(final NetworkNodeContainer container, final Level level) { + final LevelConnectionProvider connectionProvider = new LevelConnectionProvider(level); + networkBuilder.update(container, connectionProvider); + } + + @Override + public GridInsertionStrategy createGridInsertionStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + return new CompositeGridInsertionStrategy( + Platform.INSTANCE.getDefaultGridInsertionStrategyFactory().create( + containerMenu, + player, + grid + ), + gridInsertionStrategyFactories.stream().map(f -> f.create( + containerMenu, + player, + grid + )).toList() + ); + } + + @Override + public void addGridInsertionStrategyFactory(final GridInsertionStrategyFactory insertionStrategyFactory) { + gridInsertionStrategyFactories.add(insertionStrategyFactory); + } + + @Override + public void addAlternativeGridInsertionHint(final GridInsertionHint hint) { + gridInsertionHints.addAlternativeHint(hint); + } + + @Override + public GridInsertionHints getGridInsertionHints() { + return gridInsertionHints; + } + + @Override + public GridExtractionStrategy createGridExtractionStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + final List strategies = gridExtractionStrategyFactories + .stream() + .map(f -> f.create(containerMenu, player, grid)) + .toList(); + return new CompositeGridExtractionStrategy(strategies); + } + + @Override + public void addGridExtractionStrategyFactory(final GridExtractionStrategyFactory extractionStrategyFactory) { + gridExtractionStrategyFactories.add(extractionStrategyFactory); + } + + @Override + public GridScrollingStrategy createGridScrollingStrategy(final AbstractContainerMenu containerMenu, + final Player player, + final Grid grid) { + final List strategies = gridScrollingStrategyFactories + .stream() + .map(f -> f.create(containerMenu, player, grid)) + .toList(); + return new CompositeGridScrollingStrategy(strategies); + } + + @Override + public void addGridScrollingStrategyFactory(final GridScrollingStrategyFactory scrollingStrategyFactory) { + gridScrollingStrategyFactories.add(scrollingStrategyFactory); + } + + @Override + public void addResourceFactory(final ResourceFactory factory) { + resourceFactories.add(factory); + } + + @Override + public ResourceFactory getItemResourceFactory() { + return itemResourceFactory; + } + + @Override + public PlatformStorageChannelType getItemStorageChannelType() { + return StorageChannelTypes.ITEM; + } + + @Override + public StorageType getItemStorageType() { + return StorageTypes.ITEM; + } + + @Override + public ResourceFactory getFluidResourceFactory() { + return fluidResourceFactory; + } + + @Override + public PlatformStorageChannelType getFluidStorageChannelType() { + return StorageChannelTypes.FLUID; + } + + @Override + public StorageType getFluidStorageType() { + return StorageTypes.FLUID; + } + + @Override + public Set> getAlternativeResourceFactories() { + return resourceFactories; + } + + @Override + public void registerResourceRendering(final Class resourceClass, final ResourceRendering rendering) { + resourceRenderingMap.put(resourceClass, rendering); + } + + @Override + @SuppressWarnings("unchecked") + public ResourceRendering getResourceRendering(final T resource) { + return (ResourceRendering) resourceRenderingMap.get(resource.getClass()); + } + + @Override + public void registerIngredientConverter(final IngredientConverter converter) { + this.compositeConverter.addConverter(converter); + } + + @Override + public IngredientConverter getIngredientConverter() { + return compositeConverter; + } + + @Override + public void addWirelessTransmitterRangeModifier(final WirelessTransmitterRangeModifier rangeModifier) { + wirelessTransmitterRangeModifier.addModifier(rangeModifier); + } + + @Override + public WirelessTransmitterRangeModifier getWirelessTransmitterRangeModifier() { + return wirelessTransmitterRangeModifier; + } + + @Override + public Optional getEnergyStorage(final ItemStack stack) { + return Platform.INSTANCE.getEnergyStorage(stack); + } + + @Override + public EnergyItemHelper getEnergyItemHelper() { + return energyItemHelper; + } + + @Override + public EnergyStorage asItemEnergyStorage(final EnergyStorage energyStorage, + final ItemStack stack) { + return new ItemEnergyStorage(stack, energyStorage); + } + + @Override + public NetworkBoundItemHelper getNetworkBoundItemHelper() { + return networkBoundItemHelper; + } + + @Override + public PlatformRegistry getSlotReferenceFactoryRegistry() { + return slotReferenceFactoryRegistry; + } + + @Override + public void writeSlotReference(final SlotReference slotReference, final FriendlyByteBuf buf) { + this.slotReferenceFactoryRegistry.getId(slotReference.getFactory()).ifPresentOrElse(id -> { + buf.writeBoolean(true); + buf.writeResourceLocation(id); + slotReference.writeToBuffer(buf); + }, () -> buf.writeBoolean(false)); + } + + @Override + public Optional getSlotReference(final FriendlyByteBuf buf) { + if (!buf.readBoolean()) { + return Optional.empty(); + } + final ResourceLocation id = buf.readResourceLocation(); + return slotReferenceFactoryRegistry.get(id).map(factory -> factory.create(buf)); + } + + @Override + public void addSlotReferenceProvider(final SlotReferenceProvider provider) { + slotReferenceProvider.addProvider(provider); + } + + @Override + public SlotReference createInventorySlotReference(final Player player, final InteractionHand hand) { + return InventorySlotReference.of(player, hand); + } + + @Override + public void useNetworkBoundItem(final Player player, final Item... items) { + final Set validItems = new HashSet<>(Arrays.asList(items)); + slotReferenceProvider.findForUse(player, items[0], validItems).ifPresent( + slotReference -> Platform.INSTANCE.getClientToServerCommunications().sendUseNetworkBoundItem(slotReference) + ); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java index cc86cbe36..9867803af 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/PlatformProxy.java @@ -3,7 +3,6 @@ import com.refinedmods.refinedstorage2.api.core.Action; import com.refinedmods.refinedstorage2.api.grid.view.GridResourceFactory; import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage; -import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionStrategyFactory; import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; @@ -122,8 +121,8 @@ public FluidRenderer getFluidRenderer() { } @Override - public Optional> convertToFluid(final ItemStack stack) { - return ensureLoaded().convertToFluid(stack); + public Optional getContainedFluid(final ItemStack stack) { + return ensureLoaded().getContainedFluid(stack); } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/StorageMonitorBlock.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/StorageMonitorBlock.java new file mode 100644 index 000000000..74a6fef2f --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/StorageMonitorBlock.java @@ -0,0 +1,101 @@ +package com.refinedmods.refinedstorage2.platform.common.block; + +import com.refinedmods.refinedstorage2.platform.common.block.direction.BiDirectionType; +import com.refinedmods.refinedstorage2.platform.common.block.direction.DirectionType; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.StorageMonitorBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.ticker.AbstractBlockEntityTicker; +import com.refinedmods.refinedstorage2.platform.common.block.ticker.NetworkNodeBlockEntityTicker; +import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.util.BiDirection; + +import javax.annotation.Nullable; + +import net.minecraft.core.BlockPos; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.InteractionResult; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.ClipContext; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.EntityBlock; +import net.minecraft.world.level.block.entity.BlockEntity; +import net.minecraft.world.level.block.entity.BlockEntityTicker; +import net.minecraft.world.level.block.entity.BlockEntityType; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import net.minecraft.world.phys.Vec3; + +public class StorageMonitorBlock extends AbstractDirectionalBlock implements EntityBlock { + private static final AbstractBlockEntityTicker TICKER = + new NetworkNodeBlockEntityTicker<>(BlockEntities.INSTANCE::getStorageMonitor); + + public StorageMonitorBlock() { + super(BlockConstants.PROPERTIES.strength(1.5F, 6.0F)); + } + + @Override + protected DirectionType getDirectionType() { + return BiDirectionType.INSTANCE; + } + + @Nullable + @Override + public BlockEntity newBlockEntity(final BlockPos pos, final BlockState state) { + return new StorageMonitorBlockEntity(pos, state); + } + + @Override + public BlockEntityTicker getTicker(final Level level, + final BlockState state, + final BlockEntityType type) { + return TICKER.get(level, type); + } + + @Override + public InteractionResult use(final BlockState state, + final Level level, + final BlockPos pos, + final Player player, + final InteractionHand hand, + final BlockHitResult hit) { + if (player.isCrouching()) { + return super.use(state, level, pos, player, hand, hit); + } + if (!level.isClientSide()) { + final BlockEntity blockEntity = level.getBlockEntity(pos); + if (blockEntity instanceof StorageMonitorBlockEntity storageMonitor) { + storageMonitor.insert(player, hand); + } + } + return InteractionResult.SUCCESS; + } + + @Override + @SuppressWarnings("deprecation") + public void attack(final BlockState state, final Level level, final BlockPos pos, final Player player) { + super.attack(state, level, pos, player); + if (level.isClientSide()) { + return; + } + if (!(level.getBlockEntity(pos) instanceof StorageMonitorBlockEntity storageMonitor)) { + return; + } + final BiDirection direction = getDirection(state); + if (direction == null) { + return; + } + final Vec3 base = player.getEyePosition(1.0F); + final Vec3 look = player.getLookAngle(); + final Vec3 target = base.add(look.x * 20, look.y * 20, look.z * 20); + final BlockHitResult hitResult = level.clip(new ClipContext( + base, + target, + ClipContext.Block.OUTLINE, + ClipContext.Fluid.NONE, + player + )); + if (hitResult.getDirection() != direction.asDirection()) { + return; + } + storageMonitor.extract(player); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java index b487a290f..f45ad0545 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ControllerBlockEntity.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.ControllerType; import com.refinedmods.refinedstorage2.platform.common.containermenu.ControllerContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.energy.CreativeEnergyStorage; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -28,8 +29,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class ControllerBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity implements ExtendedMenuProvider, EnergyBlockEntity { private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBlockEntity.class); @@ -106,10 +105,7 @@ public void load(final CompoundTag tag) { @Override public Component getDisplayName() { - return createTranslation( - "block", - type == ControllerType.CREATIVE ? "creative_controller" : "controller" - ); + return type == ControllerType.CREATIVE ? ContentNames.CREATIVE_CONTROLLER : ContentNames.CONTROLLER; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java index f283e7c8e..71b12cea2 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/ImporterBlockEntity.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; @@ -33,8 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class ImporterBlockEntity extends AbstractUpgradeableNetworkNodeContainerBlockEntity implements AmountOverride, ExtendedMenuProvider { @@ -127,7 +126,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("block", "importer"); + return ContentNames.IMPORTER; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/constructor/ConstructorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/constructor/ConstructorBlockEntity.java index 83bc15bcf..104736dc4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/constructor/ConstructorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/constructor/ConstructorBlockEntity.java @@ -13,6 +13,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.AbstractSchedulingNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.containermenu.ConstructorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; import java.util.ArrayList; @@ -30,8 +31,6 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class ConstructorBlockEntity extends AbstractSchedulingNetworkNodeContainerBlockEntity { private static final String TAG_DROP_ITEMS = "di"; @@ -127,7 +126,7 @@ public void setDropItems(final boolean dropItems) { @Override public Component getDisplayName() { - return createTranslation("block", "constructor"); + return ContentNames.CONSTRUCTOR; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/destructor/DestructorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/destructor/DestructorBlockEntity.java index 5cff0b162..f9e4f9aa9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/destructor/DestructorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/destructor/DestructorBlockEntity.java @@ -13,6 +13,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.FilterWithFuzzyMode; import com.refinedmods.refinedstorage2.platform.common.containermenu.DestructorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -32,8 +33,6 @@ import net.minecraft.world.inventory.AbstractContainerMenu; import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class DestructorBlockEntity extends AbstractUpgradeableNetworkNodeContainerBlockEntity implements ExtendedMenuProvider { private static final String TAG_FILTER_MODE = "fim"; @@ -116,7 +115,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("block", "destructor"); + return ContentNames.DESTRUCTOR; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/detector/DetectorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/detector/DetectorBlockEntity.java index 8932661d8..98afeed4f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/detector/DetectorBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/detector/DetectorBlockEntity.java @@ -13,6 +13,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.AbstractSingleAmountContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.detector.DetectorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -33,8 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class DetectorBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity implements ExtendedMenuProvider { private static final Logger LOGGER = LoggerFactory.getLogger(DetectorBlockEntity.class); @@ -140,7 +139,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("block", "detector"); + return ContentNames.DETECTOR; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java index f09eea6c8..2e99a8364 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/diskdrive/AbstractDiskDriveBlockEntity.java @@ -13,6 +13,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.storage.diskdrive.DiskDriveContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.storage.diskdrive.EmptyStorageDiskInfoAccessor; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; import com.refinedmods.refinedstorage2.platform.common.util.ContainerUtil; @@ -40,14 +41,11 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.properties.BooleanProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public abstract class AbstractDiskDriveBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity implements BlockEntityWithDrops, MultiStorageListener, ExtendedMenuProvider { @@ -110,7 +108,7 @@ public void updateDiskStateIfNecessaryInLevel() { private void sync() { if (level != null) { - level.sendBlockUpdated(worldPosition, this.getBlockState(), this.getBlockState(), Block.UPDATE_ALL); + level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), Block.UPDATE_ALL); } } @@ -222,12 +220,12 @@ private void fromClientTag(final CompoundTag tag) { } protected void onDriveStateUpdated() { - LevelUtil.updateBlock(level, worldPosition, this.getBlockState()); + LevelUtil.updateBlock(level, worldPosition, getBlockState()); } @Override public Packet getUpdatePacket() { - return ClientboundBlockEntityDataPacket.create(this, BlockEntity::getUpdateTag); + return ClientboundBlockEntityDataPacket.create(this); } @Override @@ -247,7 +245,7 @@ public CompoundTag getUpdateTag() { @Override public Component getDisplayName() { - return createTranslation("block", "disk_drive"); + return ContentNames.DISK_DRIVE; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/exporter/ExporterBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/exporter/ExporterBlockEntity.java index cd9be6ecb..1dd5071d4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/exporter/ExporterBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/exporter/ExporterBlockEntity.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.AbstractSchedulingNetworkNodeContainerBlockEntity; import com.refinedmods.refinedstorage2.platform.common.containermenu.ExporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.content.Items; import com.refinedmods.refinedstorage2.platform.common.internal.upgrade.UpgradeDestinations; @@ -29,8 +30,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class ExporterBlockEntity extends AbstractSchedulingNetworkNodeContainerBlockEntity implements AmountOverride { @@ -80,7 +79,7 @@ protected void setEnergyUsage(final long upgradeEnergyUsage) { @Override public Component getDisplayName() { - return createTranslation("block", "exporter"); + return ContentNames.EXPORTER; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/externalstorage/ExternalStorageBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/externalstorage/ExternalStorageBlockEntity.java index 81888eadd..94bebab8c 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/externalstorage/ExternalStorageBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/externalstorage/ExternalStorageBlockEntity.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.StorageConfigurationContainerImpl; import com.refinedmods.refinedstorage2.platform.common.containermenu.storage.ExternalStorageContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -33,8 +34,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class ExternalStorageBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity implements ExtendedMenuProvider { @@ -155,7 +154,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("block", "external_storage"); + return ContentNames.EXTERNAL_STORAGE; } @Nullable diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/CraftingGridBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/CraftingGridBlockEntity.java index 733451ef6..54900e49e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/CraftingGridBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/CraftingGridBlockEntity.java @@ -11,6 +11,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.CraftingGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; import com.refinedmods.refinedstorage2.platform.common.util.ContainerUtil; @@ -30,8 +31,6 @@ import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class CraftingGridBlockEntity extends AbstractGridBlockEntity { private static final String TAG_CRAFTING_MATRIX = "matrix"; @@ -101,7 +100,7 @@ public NonNullList getRemainingItems(final Player player) { @Override public Component getDisplayName() { - return createTranslation("block", "crafting_grid"); + return ContentNames.CRAFTING_GRID; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/GridBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/GridBlockEntity.java index 702ac5de2..5a31f7b21 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/GridBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/grid/GridBlockEntity.java @@ -4,6 +4,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.AbstractGridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.GridContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import javax.annotation.Nullable; @@ -13,8 +14,6 @@ import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class GridBlockEntity extends AbstractGridBlockEntity { public GridBlockEntity(final BlockPos pos, final BlockState state) { super(BlockEntities.INSTANCE.getGrid(), pos, state, Platform.INSTANCE.getConfig().getGrid().getEnergyUsage()); @@ -22,7 +21,7 @@ public GridBlockEntity(final BlockPos pos, final BlockState state) { @Override public Component getDisplayName() { - return createTranslation("block", "grid"); + return ContentNames.GRID; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/iface/InterfaceBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/iface/InterfaceBlockEntity.java index 61e921fd1..9edacdb05 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/iface/InterfaceBlockEntity.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/iface/InterfaceBlockEntity.java @@ -15,6 +15,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.FilterWithFuzzyMode; import com.refinedmods.refinedstorage2.platform.common.containermenu.InterfaceContainerMenu; import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -35,8 +36,6 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.state.BlockState; -import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; - public class InterfaceBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity implements ExtendedMenuProvider, BlockEntityWithDrops { @@ -157,7 +156,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("block", "interface"); + return ContentNames.INTERFACE; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorExtractionStrategy.java new file mode 100644 index 000000000..48472b1aa --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorExtractionStrategy.java @@ -0,0 +1,32 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; + +import java.util.ArrayList; +import java.util.List; + +import net.minecraft.world.entity.player.Player; + +public class CompositeStorageMonitorExtractionStrategy implements StorageMonitorExtractionStrategy { + private final List strategies = new ArrayList<>(); + + public void addStrategy(final StorageMonitorExtractionStrategy strategy) { + strategies.add(strategy); + } + + @Override + public boolean extract(final Object resource, + final boolean fullStack, + final Player player, + final Actor actor, + final Network network) { + for (final StorageMonitorExtractionStrategy strategy : strategies) { + if (strategy.extract(resource, fullStack, player, actor, network)) { + return true; + } + } + return false; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorInsertionStrategy.java new file mode 100644 index 000000000..95e98fdd1 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/CompositeStorageMonitorInsertionStrategy.java @@ -0,0 +1,31 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import net.minecraft.world.item.ItemStack; + +public class CompositeStorageMonitorInsertionStrategy implements StorageMonitorInsertionStrategy { + private final List strategies = new ArrayList<>(); + + public void addStrategy(final StorageMonitorInsertionStrategy strategy) { + strategies.add(strategy); + } + + @Override + public Optional insert( + final Object configuredResource, + final ItemStack stack, + final Actor actor, + final Network network + ) { + return strategies.stream() + .flatMap(strategy -> strategy.insert(configuredResource, stack, actor, network).stream()) + .findFirst(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorExtractionStrategy.java new file mode 100644 index 000000000..629dfc662 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorExtractionStrategy.java @@ -0,0 +1,42 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.api.storage.TransferHelper; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.BucketPlayerInventoryInsertableStorage; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; + +import net.minecraft.world.entity.player.Player; + +public class FluidStorageMonitorExtractionStrategy implements StorageMonitorExtractionStrategy { + @Override + public boolean extract(final Object resource, + final boolean fullStack, + final Player player, + final Actor actor, + final Network network) { + if (!(resource instanceof FluidResource fluidResource)) { + return false; + } + final BucketPlayerInventoryInsertableStorage target = new BucketPlayerInventoryInsertableStorage( + player.getInventory(), + network.getComponent(StorageNetworkComponent.class).getStorageChannel(StorageChannelTypes.ITEM), + true + ); + final StorageChannel source = network.getComponent(StorageNetworkComponent.class) + .getStorageChannel(StorageChannelTypes.FLUID); + return TransferHelper.transfer( + fluidResource, + Platform.INSTANCE.getBucketAmount(), + actor, + source, + target, + source + ) > 0; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorInsertionStrategy.java new file mode 100644 index 000000000..35a7ed952 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/FluidStorageMonitorInsertionStrategy.java @@ -0,0 +1,69 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.common.ContainedFluid; +import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; + +import java.util.Optional; +import javax.annotation.Nullable; + +import net.minecraft.world.item.ItemStack; + +public class FluidStorageMonitorInsertionStrategy implements StorageMonitorInsertionStrategy { + @Override + public Optional insert( + final Object configuredResource, + final ItemStack stack, + final Actor actor, + final Network network + ) { + if (!(configuredResource instanceof FluidResource configuredFluidResource)) { + return Optional.empty(); + } + final StorageChannel fluidStorageChannel = network.getComponent(StorageNetworkComponent.class) + .getStorageChannel(StorageChannelTypes.FLUID); + return Platform.INSTANCE.getContainedFluid(stack) + .map(extracted -> tryInsert(actor, configuredFluidResource, extracted, fluidStorageChannel)) + .map(extracted -> doInsert(actor, extracted, fluidStorageChannel)); + } + + @Nullable + private ContainedFluid tryInsert(final Actor actor, + final FluidResource configuredResource, + final ContainedFluid result, + final StorageChannel storageChannel) { + final ResourceAmount fluid = result.fluid(); + if (!fluid.getResource().equals(configuredResource)) { + return null; + } + final long insertedSimulated = storageChannel.insert( + fluid.getResource(), + fluid.getAmount(), + Action.SIMULATE, + actor + ); + final boolean insertedSuccessfully = insertedSimulated == fluid.getAmount(); + return insertedSuccessfully ? result : null; + } + + private ItemStack doInsert(final Actor actor, + final ContainedFluid extracted, + final StorageChannel storageChannel) { + final ResourceAmount fluid = extracted.fluid(); + storageChannel.insert( + fluid.getResource(), + fluid.getAmount(), + Action.EXECUTE, + actor + ); + return extracted.remainderContainer(); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/InsertTracker.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/InsertTracker.java new file mode 100644 index 000000000..87d42cdee --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/InsertTracker.java @@ -0,0 +1,37 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import com.mojang.authlib.GameProfile; +import net.minecraft.world.item.ItemStack; + +class InsertTracker { + private static final long MAX_DELAY = 500; + + private final Map entries = new HashMap<>(); + + public void trackInsertedItem(final GameProfile gameProfile, final ItemStack stack) { + entries.put(gameProfile.getId(), new Entry(System.currentTimeMillis(), ItemResource.ofItemStack(stack))); + } + + public Optional getLastInsertedItem(final GameProfile gameProfile) { + final Entry entry = entries.get(gameProfile.getId()); + if (entry == null) { + return Optional.empty(); + } + final long time = System.currentTimeMillis(); + if (time - entry.time > MAX_DELAY) { + entries.remove(gameProfile.getId()); + return Optional.empty(); + } + return Optional.of(entry.itemResource); + } + + private record Entry(long time, ItemResource itemResource) { + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorExtractionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorExtractionStrategy.java new file mode 100644 index 000000000..4338802e2 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorExtractionStrategy.java @@ -0,0 +1,36 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorExtractionStrategy; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; + +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.item.ItemStack; + +public class ItemStorageMonitorExtractionStrategy implements StorageMonitorExtractionStrategy { + @Override + public boolean extract(final Object resource, + final boolean fullStack, + final Player player, + final Actor actor, + final Network network) { + if (!(resource instanceof ItemResource itemResource)) { + return false; + } + final long extracted = network.getComponent(StorageNetworkComponent.class) + .getStorageChannel(StorageChannelTypes.ITEM) + .extract(itemResource, fullStack ? itemResource.item().getMaxStackSize() : 1, Action.EXECUTE, actor); + if (extracted > 0) { + final ItemStack stack = itemResource.toItemStack(extracted); + if (!player.getInventory().add(stack)) { + player.drop(stack, false); + } + return true; + } + return false; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorInsertionStrategy.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorInsertionStrategy.java new file mode 100644 index 000000000..297741a93 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/ItemStorageMonitorInsertionStrategy.java @@ -0,0 +1,37 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.platform.api.blockentity.storagemonitor.StorageMonitorInsertionStrategy; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; + +import java.util.Optional; + +import net.minecraft.world.item.ItemStack; + +public class ItemStorageMonitorInsertionStrategy implements StorageMonitorInsertionStrategy { + @Override + public Optional insert(final Object configuredResource, + final ItemStack stack, + final Actor actor, + final Network network) { + if (!(configuredResource instanceof ItemResource configuredItemResource)) { + return Optional.empty(); + } + final ItemResource resource = ItemResource.ofItemStack(stack); + if (!configuredItemResource.equals(resource)) { + return Optional.empty(); + } + final long inserted = network.getComponent(StorageNetworkComponent.class) + .getStorageChannel(StorageChannelTypes.ITEM) + .insert(resource, stack.getCount(), Action.EXECUTE, actor); + final long remainder = stack.getCount() - inserted; + if (remainder > 0) { + return Optional.of(resource.toItemStack(remainder)); + } + return Optional.of(ItemStack.EMPTY); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/StorageMonitorBlockEntity.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/StorageMonitorBlockEntity.java new file mode 100644 index 000000000..21586c41c --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/StorageMonitorBlockEntity.java @@ -0,0 +1,317 @@ +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.network.Network; +import com.refinedmods.refinedstorage2.api.network.component.StorageNetworkComponent; +import com.refinedmods.refinedstorage2.api.network.impl.node.SimpleNetworkNode; +import com.refinedmods.refinedstorage2.api.resource.ResourceAmount; +import com.refinedmods.refinedstorage2.api.storage.channel.StorageChannel; +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceContainer; +import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; +import com.refinedmods.refinedstorage2.platform.api.storage.channel.FuzzyStorageChannel; +import com.refinedmods.refinedstorage2.platform.common.Platform; +import com.refinedmods.refinedstorage2.platform.common.block.entity.AbstractInternalNetworkNodeContainerBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.entity.FilterWithFuzzyMode; +import com.refinedmods.refinedstorage2.platform.common.containermenu.StorageMonitorContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.content.BlockEntities; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; +import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; +import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; + +import javax.annotation.Nullable; + +import com.google.common.util.concurrent.RateLimiter; +import net.minecraft.core.BlockPos; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.network.protocol.game.ClientboundBlockEntityDataPacket; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.sounds.SoundEvents; +import net.minecraft.sounds.SoundSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.inventory.AbstractContainerMenu; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class StorageMonitorBlockEntity extends AbstractInternalNetworkNodeContainerBlockEntity + implements ExtendedMenuProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(StorageMonitorBlockEntity.class); + + private static final String TAG_CLIENT_FILTER = "cf"; + private static final String TAG_CLIENT_AMOUNT = "ca"; + private static final String TAG_CLIENT_ACTIVE = "cac"; + + private final FilterWithFuzzyMode filter; + private final RateLimiter displayUpdateRateLimiter = RateLimiter.create(0.25); + private final InsertTracker insertTracker = new InsertTracker(); + + private long currentAmount; + private boolean currentlyActive; + + public StorageMonitorBlockEntity(final BlockPos pos, final BlockState state) { + super(BlockEntities.INSTANCE.getStorageMonitor(), pos, state, new SimpleNetworkNode( + Platform.INSTANCE.getConfig().getStorageMonitor().getEnergyUsage() + )); + final ResourceContainer resourceContainer = ResourceContainerImpl.createForFilter(1); + this.filter = FilterWithFuzzyMode.create(resourceContainer, () -> { + setChanged(); + if (level != null) { + sendDisplayUpdate(level, getAmount(), getNode().isActive()); + } + }); + } + + @Override + public void doWork() { + super.doWork(); + if (level == null) { + return; + } + trySendDisplayUpdate(level); + } + + private void trySendDisplayUpdate(final Level level) { + final long amount = getAmount(); + final boolean active = getNode().isActive(); + if ((amount != currentAmount || active != currentlyActive) && displayUpdateRateLimiter.tryAcquire()) { + sendDisplayUpdate(level, amount, active); + } + } + + private long getAmount() { + final ResourceAmountTemplate template = filter.getFilterContainer().get(0); + if (template == null) { + return 0; + } + final Network network = getNode().getNetwork(); + if (network == null) { + return 0; + } + return getAmount(network, template); + } + + private long getAmount(final Network network, final ResourceAmountTemplate template) { + final StorageChannel storageChannel = network.getComponent(StorageNetworkComponent.class) + .getStorageChannel(template.getStorageChannelType()); + if (!filter.isFuzzyMode() || !(storageChannel instanceof FuzzyStorageChannel fuzzyStorageChannel)) { + return storageChannel.get(template.getResource()).map(ResourceAmount::getAmount).orElse(0L); + } + return fuzzyStorageChannel.getFuzzy(template.getResource()).stream().mapToLong(ResourceAmount::getAmount).sum(); + } + + public void extract(final Player player) { + if (level == null) { + return; + } + final Network network = getNode().getNetwork(); + if (network == null) { + return; + } + final ResourceAmountTemplate template = getFilteredResource(); + if (template == null) { + return; + } + extract(level, player, template.getResource(), network); + } + + private void extract( + final Level level, + final Player player, + final T template, + final Network network + ) { + final boolean success = PlatformApi.INSTANCE.getStorageMonitorExtractionStrategy().extract( + template, + !player.isShiftKeyDown(), + player, + new PlayerActor(player), + network + ); + if (!success) { + return; + } + sendDisplayUpdate(level, getAmount(), getNode().isActive()); + level.playSound( + null, + getBlockPos(), + SoundEvents.ITEM_PICKUP, + SoundSource.PLAYERS, + .2f, + ((level.random.nextFloat() - level.random.nextFloat()) * .7f + 1) * 2 + ); + } + + public void insert(final Player player, final InteractionHand hand) { + if (level != null && doInsert(player, hand)) { + sendDisplayUpdate(level, getAmount(), getNode().isActive()); + } + } + + private boolean doInsert(final Player player, final InteractionHand hand) { + final Network network = getNode().getNetwork(); + if (network == null) { + return false; + } + final ResourceAmountTemplate template = getFilteredResource(); + if (template == null) { + return false; + } + final ItemStack heldStack = player.getItemInHand(hand); + if (heldStack.isEmpty()) { + return doInsertAll(player); + } + return doInsert(player, hand, heldStack, template.getResource(), network); + } + + private boolean doInsert( + final Player player, + final InteractionHand hand, + final ItemStack heldStack, + final T template, + final Network network + ) { + return PlatformApi.INSTANCE.getStorageMonitorInsertionStrategy().insert( + template, + heldStack, + new PlayerActor(player), + network + ).map(result -> { + insertTracker.trackInsertedItem(player.getGameProfile(), heldStack); + player.setItemInHand(hand, result); + return true; + }).orElse(false); + } + + private boolean doInsertAll(final Player player) { + return insertTracker.getLastInsertedItem(player.getGameProfile()).map( + item -> doInsertAll(player, item) + ).orElse(false); + } + + private boolean doInsertAll(final Player player, final ItemResource lastInsertedItem) { + final Network network = getNode().getNetwork(); + if (network == null) { + return false; + } + final ResourceAmountTemplate template = getFilteredResource(); + if (template == null) { + return false; + } + boolean success = false; + for (int i = 0; i < player.getInventory().getContainerSize(); ++i) { + success |= tryInsertSlot(player, lastInsertedItem, i, template.getResource(), network); + } + return success; + } + + private boolean tryInsertSlot( + final Player player, + final ItemResource lastInsertedItem, + final int inventorySlotIndex, + final T template, + final Network network + ) { + final ItemStack slot = player.getInventory().getItem(inventorySlotIndex); + if (slot.isEmpty()) { + return false; + } + final ItemResource itemInSlot = ItemResource.ofItemStack(slot); + if (!itemInSlot.equals(lastInsertedItem)) { + return false; + } + return PlatformApi.INSTANCE.getStorageMonitorInsertionStrategy().insert( + template, + slot, + new PlayerActor(player), + network + ).map(result -> { + player.getInventory().setItem(inventorySlotIndex, result); + return true; + }).orElse(false); + } + + public boolean isFuzzyMode() { + return filter.isFuzzyMode(); + } + + public void setFuzzyMode(final boolean fuzzyMode) { + filter.setFuzzyMode(fuzzyMode); + } + + @Nullable + public ResourceAmountTemplate getFilteredResource() { + return filter.getFilterContainer().get(0); + } + + public long getCurrentAmount() { + return currentAmount; + } + + public boolean isCurrentlyActive() { + return currentlyActive; + } + + @Override + public void saveAdditional(final CompoundTag tag) { + super.saveAdditional(tag); + filter.save(tag); + } + + @Override + public void load(final CompoundTag tag) { + if (tag.contains(TAG_CLIENT_FILTER) && tag.contains(TAG_CLIENT_AMOUNT) && tag.contains(TAG_CLIENT_ACTIVE)) { + filter.getFilterContainer().fromTag(tag.getCompound(TAG_CLIENT_FILTER)); + currentAmount = tag.getLong(TAG_CLIENT_AMOUNT); + currentlyActive = tag.getBoolean(TAG_CLIENT_ACTIVE); + } else { + filter.load(tag); + } + super.load(tag); + } + + @Override + public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByteBuf buf) { + filter.getFilterContainer().writeToUpdatePacket(buf); + } + + @Override + public Component getDisplayName() { + return ContentNames.STORAGE_MONITOR; + } + + @Nullable + @Override + public AbstractContainerMenu createMenu(final int syncId, final Inventory inventory, final Player player) { + return new StorageMonitorContainerMenu(syncId, player, this, filter.getFilterContainer()); + } + + @Override + public ClientboundBlockEntityDataPacket getUpdatePacket() { + return ClientboundBlockEntityDataPacket.create(this); + } + + @Override + public CompoundTag getUpdateTag() { + final CompoundTag tag = new CompoundTag(); + tag.put(TAG_CLIENT_FILTER, filter.getFilterContainer().toTag()); + tag.putLong(TAG_CLIENT_AMOUNT, currentAmount); + tag.putBoolean(TAG_CLIENT_ACTIVE, currentlyActive); + return tag; + } + + private void sendDisplayUpdate(final Level level, final long amount, final boolean active) { + currentAmount = amount; + currentlyActive = active; + level.sendBlockUpdated(worldPosition, getBlockState(), getBlockState(), Block.UPDATE_ALL); + LOGGER.info("Sending display update for storage monitor {} with amount {}", worldPosition, amount); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/package-info.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/package-info.java new file mode 100644 index 000000000..acaf1c2fe --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/block/entity/storagemonitor/package-info.java @@ -0,0 +1,7 @@ +@ParametersAreNonnullByDefault +@FieldsAndMethodsAreNonnullByDefault +package com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor; + +import com.refinedmods.refinedstorage2.api.core.FieldsAndMethodsAreNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/StorageMonitorContainerMenu.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/StorageMonitorContainerMenu.java new file mode 100644 index 000000000..ab288c604 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/containermenu/StorageMonitorContainerMenu.java @@ -0,0 +1,54 @@ +package com.refinedmods.refinedstorage2.platform.common.containermenu; + +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceContainer; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.StorageMonitorBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ClientProperty; +import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyTypes; +import com.refinedmods.refinedstorage2.platform.common.containermenu.property.ServerProperty; +import com.refinedmods.refinedstorage2.platform.common.containermenu.slot.ResourceSlot; +import com.refinedmods.refinedstorage2.platform.common.content.Menus; +import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; +import com.refinedmods.refinedstorage2.platform.common.util.RedstoneMode; + +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.chat.Component; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createTranslation; + +public class StorageMonitorContainerMenu extends AbstractResourceContainerMenu { + private static final Component FILTER_HELP = createTranslation("gui", "storage_monitor.filter_help"); + + public StorageMonitorContainerMenu(final int syncId, final Inventory playerInventory, final FriendlyByteBuf buf) { + super(Menus.INSTANCE.getStorageMonitor(), syncId); + registerProperty(new ClientProperty<>(PropertyTypes.FUZZY_MODE, false)); + registerProperty(new ClientProperty<>(PropertyTypes.REDSTONE_MODE, RedstoneMode.IGNORE)); + addSlots(playerInventory, ResourceContainerImpl.createForFilter(1)); + initializeResourceSlots(buf); + } + + public StorageMonitorContainerMenu(final int syncId, + final Player player, + final StorageMonitorBlockEntity storageMonitor, + final ResourceContainer resourceContainer) { + super(Menus.INSTANCE.getStorageMonitor(), syncId, player); + registerProperty(new ServerProperty<>( + PropertyTypes.FUZZY_MODE, + storageMonitor::isFuzzyMode, + storageMonitor::setFuzzyMode + )); + registerProperty(new ServerProperty<>( + PropertyTypes.REDSTONE_MODE, + storageMonitor::getRedstoneMode, + storageMonitor::setRedstoneMode + )); + addSlots(player.getInventory(), resourceContainer); + } + + private void addSlots(final Inventory playerInventory, final ResourceContainer resourceContainer) { + addSlot(new ResourceSlot(resourceContainer, 0, FILTER_HELP, 80, 20)); + addPlayerInventory(playerInventory, 8, 55); + transferManager.addFilterTransfer(playerInventory); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/BlockEntities.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/BlockEntities.java index 9ca78ce92..2a0bee746 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/BlockEntities.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/BlockEntities.java @@ -14,6 +14,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.entity.iface.InterfaceBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.FluidStorageBlockBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.storage.ItemStorageBlockBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.StorageMonitorBlockEntity; import com.refinedmods.refinedstorage2.platform.common.block.entity.wirelesstransmitter.WirelessTransmitterBlockEntity; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.FluidStorageType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.type.ItemStorageType; @@ -61,6 +62,8 @@ public final class BlockEntities { private Supplier> constructor; @Nullable private Supplier> wirelessTransmitter; + @Nullable + private Supplier> storageMonitor; private BlockEntities() { } @@ -194,4 +197,12 @@ public BlockEntityType getWirelessTransmitter() public void setWirelessTransmitter(final Supplier> supplier) { this.wirelessTransmitter = supplier; } + + public BlockEntityType getStorageMonitor() { + return Objects.requireNonNull(storageMonitor).get(); + } + + public void setStorageMonitor(final Supplier> supplier) { + this.storageMonitor = supplier; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Blocks.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Blocks.java index c4da073cc..18c5e28d4 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Blocks.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Blocks.java @@ -14,6 +14,7 @@ import com.refinedmods.refinedstorage2.platform.common.block.InterfaceBlock; import com.refinedmods.refinedstorage2.platform.common.block.ItemStorageBlock; import com.refinedmods.refinedstorage2.platform.common.block.SimpleBlock; +import com.refinedmods.refinedstorage2.platform.common.block.StorageMonitorBlock; import com.refinedmods.refinedstorage2.platform.common.block.WirelessTransmitterBlock; import com.refinedmods.refinedstorage2.platform.common.block.grid.CraftingGridBlock; import com.refinedmods.refinedstorage2.platform.common.block.grid.GridBlock; @@ -129,6 +130,8 @@ public final class Blocks { new EnumMap<>(FluidStorageType.Variant.class); @Nullable private Supplier iface; + @Nullable + private Supplier storageMonitor; private Blocks() { } @@ -229,4 +232,12 @@ public BlockColorMap getConstructor() { public BlockColorMap getWirelessTransmitter() { return wirelessTransmitter; } + + public void setStorageMonitor(final Supplier supplier) { + this.storageMonitor = supplier; + } + + public StorageMonitorBlock getStorageMonitor() { + return Objects.requireNonNull(storageMonitor).get(); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java index 1ea0d646c..cd3f251c8 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentIds.java @@ -47,6 +47,7 @@ public final class ContentIds { public static final ResourceLocation WIRELESS_TRANSMITTER = createIdentifier("wireless_transmitter"); public static final ResourceLocation RANGE_UPGRADE = createIdentifier("range_upgrade"); public static final ResourceLocation CREATIVE_RANGE_UPGRADE = createIdentifier("creative_range_upgrade"); + public static final ResourceLocation STORAGE_MONITOR = createIdentifier("storage_monitor"); private ContentIds() { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentNames.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentNames.java index f4227d9d3..b1ac504ec 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentNames.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/ContentNames.java @@ -18,6 +18,10 @@ public final class ContentNames { public static final MutableComponent CREATIVE_CONTROLLER = createTranslation("block", "creative_controller"); public static final MutableComponent WIRELESS_GRID = createTranslation("item", "wireless_grid"); public static final MutableComponent WIRELESS_TRANSMITTER = createTranslation("block", "wireless_transmitter"); + public static final MutableComponent REGULATOR_UPGRADE = createTranslation("block", "regulator_upgrade"); + public static final MutableComponent STORAGE_MONITOR = createTranslation("block", "storage_monitor"); + public static final MutableComponent INTERFACE = createTranslation("block", "interface"); + public static final MutableComponent DISK_DRIVE = createTranslation("block", "disk_drive"); private ContentNames() { } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java index a4803c336..5af4cd217 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/CreativeModeTabItems.java @@ -46,6 +46,7 @@ private static void appendBlocks(final Consumer consumer) { )); itemConsumer.accept(Blocks.INSTANCE.getMachineCasing()); itemConsumer.accept(Blocks.INSTANCE.getQuartzEnrichedIronBlock()); + itemConsumer.accept(Blocks.INSTANCE.getStorageMonitor()); } private static void appendBlockColors(final Consumer consumer, final BlockColorMap map) { diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/DefaultEnergyUsage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/DefaultEnergyUsage.java index 86f47ed85..ba04bd65e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/DefaultEnergyUsage.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/DefaultEnergyUsage.java @@ -13,6 +13,8 @@ public final class DefaultEnergyUsage { public static final long CONSTRUCTOR = 3; public static final long DESTRUCTOR = 3; public static final long DISK_DRIVE_PER_DISK = 4; + public static final long STORAGE_MONITOR = 4; + public static final long CONTROLLER_CAPACITY = 1000; public static final long ONE_K_STORAGE_BLOCK = 2; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Menus.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Menus.java index 881c21eec..671b2ba41 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Menus.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/content/Menus.java @@ -7,6 +7,7 @@ import com.refinedmods.refinedstorage2.platform.common.containermenu.ImporterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.InterfaceContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.RegulatorUpgradeContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.containermenu.StorageMonitorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.WirelessTransmitterContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.detector.DetectorContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.grid.CraftingGridContainerMenu; @@ -58,6 +59,8 @@ public final class Menus { private Supplier> regulatorUpgrade; @Nullable private Supplier> wirelessTransmitter; + @Nullable + private Supplier> storageMonitor; private Menus() { } @@ -189,4 +192,12 @@ public MenuType getWirelessTransmitter() { public void setWirelessTransmitter(final Supplier> supplier) { this.wirelessTransmitter = supplier; } + + public MenuType getStorageMonitor() { + return Objects.requireNonNull(storageMonitor).get(); + } + + public void setStorageMonitor(final Supplier> supplier) { + this.storageMonitor = supplier; + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceFactory.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceFactory.java index 19b42aecd..ffe9b8705 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceFactory.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceFactory.java @@ -13,8 +13,8 @@ public class FluidResourceFactory implements ResourceFactory { @Override public Optional> create(final ItemStack stack) { - return Platform.INSTANCE.convertToFluid(stack).map(resourceAmount -> new ResourceAmountTemplate<>( - resourceAmount.getResource(), + return Platform.INSTANCE.getContainedFluid(stack).map(result -> new ResourceAmountTemplate<>( + result.fluid().getResource(), Platform.INSTANCE.getBucketAmount(), StorageChannelTypes.FLUID )); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceRendering.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceRendering.java index f01109dbf..d004a4336 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceRendering.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/FluidResourceRendering.java @@ -6,12 +6,18 @@ import java.util.List; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.network.chat.Component; +import net.minecraft.world.level.Level; public class FluidResourceRendering implements ResourceRendering { @Override - public String getDisplayedAmount(final long amount) { + public String getDisplayedAmount(final long amount, final boolean withUnits) { + if (!withUnits) { + return Platform.INSTANCE.getBucketAmountFormatter().format(amount); + } return Platform.INSTANCE.getBucketAmountFormatter().formatWithUnits(amount); } @@ -29,4 +35,13 @@ public List getTooltip(final FluidResource resource) { public void render(final FluidResource resource, final GuiGraphics graphics, final int x, final int y) { Platform.INSTANCE.getFluidRenderer().render(graphics.pose(), x, y, resource); } + + @Override + public void render(final FluidResource resource, + final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final int light, + final Level level) { + Platform.INSTANCE.getFluidRenderer().render(poseStack, renderTypeBuffer, light, resource); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ItemResourceRendering.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ItemResourceRendering.java index 07aac7529..e54703dbc 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ItemResourceRendering.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ItemResourceRendering.java @@ -10,13 +10,21 @@ import java.util.List; import java.util.Map; +import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiGraphics; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.network.chat.Component; +import net.minecraft.util.Mth; +import net.minecraft.world.item.ItemDisplayContext; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.level.Level; +import org.joml.Matrix4f; public class ItemResourceRendering implements ResourceRendering { + public static final Matrix4f IN_WORLD_SCALE = new Matrix4f().scale(0.3F, 0.3F, 0.001f); private final Map stackCache = new HashMap<>(); private ItemStack getStack(final ItemResource itemResource) { @@ -24,7 +32,10 @@ private ItemStack getStack(final ItemResource itemResource) { } @Override - public String getDisplayedAmount(final long amount) { + public String getDisplayedAmount(final long amount, final boolean withUnits) { + if (!withUnits) { + return AmountFormatting.format(amount); + } if (amount == 1) { return ""; } @@ -51,4 +62,25 @@ public void render(final ItemResource resource, final GuiGraphics graphics, fina graphics.renderItem(stack, x, y); graphics.renderItemDecorations(Minecraft.getInstance().font, stack, x, y); } + + @Override + public void render(final ItemResource resource, + final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final int light, + final Level level) { + final ItemStack itemStack = getStack(resource); + poseStack.mulPoseMatrix(IN_WORLD_SCALE); + poseStack.last().normal().rotateX(Mth.DEG_TO_RAD * -45f); + Minecraft.getInstance().getItemRenderer().renderStatic( + itemStack, + ItemDisplayContext.GUI, + light, + OverlayTexture.NO_OVERLAY, + poseStack, + renderTypeBuffer, + level, + 0 + ); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ResourceContainerImpl.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ResourceContainerImpl.java index 00f7353ee..944ee6d36 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ResourceContainerImpl.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/resource/ResourceContainerImpl.java @@ -267,6 +267,7 @@ public void fromTag(final CompoundTag tag) { for (int i = 0; i < size(); ++i) { final String key = "s" + i; if (!tag.contains(key)) { + removeSilently(i); continue; } final CompoundTag item = tag.getCompound(key); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/storage/BucketPlayerInventoryInsertableStorage.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/storage/BucketPlayerInventoryInsertableStorage.java new file mode 100644 index 000000000..f102d74e2 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/internal/storage/BucketPlayerInventoryInsertableStorage.java @@ -0,0 +1,89 @@ +package com.refinedmods.refinedstorage2.platform.common.internal.storage; + +import com.refinedmods.refinedstorage2.api.core.Action; +import com.refinedmods.refinedstorage2.api.storage.Actor; +import com.refinedmods.refinedstorage2.api.storage.InsertableStorage; +import com.refinedmods.refinedstorage2.api.storage.Storage; +import com.refinedmods.refinedstorage2.platform.api.resource.FluidResource; +import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; +import com.refinedmods.refinedstorage2.platform.common.Platform; + +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.Items; + +public class BucketPlayerInventoryInsertableStorage implements InsertableStorage { + private static final ItemStack EMPTY_BUCKET_STACK = new ItemStack(Items.BUCKET); + private static final ItemResource EMPTY_BUCKET_RESOURCE = ItemResource.ofItemStack(EMPTY_BUCKET_STACK); + + private final Inventory playerInventory; + private final Storage emptyBucketStorage; + private final boolean mayDropFilledBucket; + + public BucketPlayerInventoryInsertableStorage(final Inventory playerInventory, + final Storage emptyBucketStorage, + final boolean mayDropFilledBucket) { + this.playerInventory = playerInventory; + this.emptyBucketStorage = emptyBucketStorage; + this.mayDropFilledBucket = mayDropFilledBucket; + } + + @Override + public long insert(final FluidResource resource, final long amount, final Action action, final Actor actor) { + if (amount != Platform.INSTANCE.getBucketAmount()) { + return 0; + } + return Platform.INSTANCE.convertToBucket(resource).map( + filledBucketStack -> insert(filledBucketStack, amount, action, actor) + ).orElse(0L); + } + + private long insert(final ItemStack filledBucketStack, final long amount, final Action action, final Actor actor) { + if (extractBucketFromInventory(action)) { + return insert(filledBucketStack, amount, action, this::returnBucketToInventory); + } else if (extractBucketFromStorage(action, actor)) { + return insert(filledBucketStack, amount, action, () -> returnBucketToStorage(actor)); + } + return 0L; + } + + private long insert(final ItemStack filledBucketStack, + final long amount, + final Action action, + final Runnable rollbackAction) { + if (action == Action.EXECUTE && !playerInventory.add(filledBucketStack)) { + if (mayDropFilledBucket) { + playerInventory.player.drop(filledBucketStack, false); + } else { + rollbackAction.run(); + return 0; + } + } + return amount; + } + + private boolean extractBucketFromInventory(final Action action) { + for (int i = 0; i < playerInventory.getContainerSize(); ++i) { + final ItemStack stack = playerInventory.getItem(i); + if (stack.getItem() == Items.BUCKET) { + if (action == Action.EXECUTE) { + playerInventory.removeItem(i, 1); + } + return true; + } + } + return false; + } + + private void returnBucketToInventory() { + playerInventory.add(EMPTY_BUCKET_STACK); + } + + private boolean extractBucketFromStorage(final Action action, final Actor actor) { + return emptyBucketStorage.extract(EMPTY_BUCKET_RESOURCE, 1, action, actor) == 1; + } + + private void returnBucketToStorage(final Actor actor) { + emptyBucketStorage.insert(EMPTY_BUCKET_RESOURCE, 1, Action.EXECUTE, actor); + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java index 1443590bb..19ec7a354 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/item/RegulatorUpgradeItem.java @@ -9,6 +9,7 @@ import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.containermenu.AbstractSingleAmountContainerMenu; import com.refinedmods.refinedstorage2.platform.common.containermenu.RegulatorUpgradeContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.content.ContentNames; import com.refinedmods.refinedstorage2.platform.common.internal.resource.ResourceContainerImpl; import com.refinedmods.refinedstorage2.platform.common.menu.ExtendedMenuProvider; @@ -139,7 +140,7 @@ public void writeScreenOpeningData(final ServerPlayer player, final FriendlyByte @Override public Component getDisplayName() { - return createTranslation("item", "regulator_upgrade"); + return ContentNames.REGULATOR_UPGRADE; } @Override diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/FluidRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/FluidRenderer.java index ebf502c26..eb4deace0 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/FluidRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/FluidRenderer.java @@ -5,11 +5,14 @@ import java.util.List; import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.network.chat.Component; public interface FluidRenderer { void render(PoseStack poseStack, int x, int y, FluidResource fluidResource); + void render(PoseStack poseStack, MultiBufferSource renderTypeBuffer, int light, FluidResource fluidResource); + List getTooltip(FluidResource fluidResource); Component getDisplayName(FluidResource fluidResource); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/entity/StorageMonitorBlockEntityRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/entity/StorageMonitorBlockEntityRenderer.java new file mode 100644 index 000000000..b1bf7d150 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/entity/StorageMonitorBlockEntityRenderer.java @@ -0,0 +1,137 @@ +package com.refinedmods.refinedstorage2.platform.common.render.entity; + +import com.refinedmods.refinedstorage2.platform.api.PlatformApi; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceAmountTemplate; +import com.refinedmods.refinedstorage2.platform.api.resource.ResourceRendering; +import com.refinedmods.refinedstorage2.platform.common.block.StorageMonitorBlock; +import com.refinedmods.refinedstorage2.platform.common.block.direction.BiDirectionType; +import com.refinedmods.refinedstorage2.platform.common.block.entity.storagemonitor.StorageMonitorBlockEntity; +import com.refinedmods.refinedstorage2.platform.common.util.BiDirection; + +import javax.annotation.Nullable; + +import com.mojang.blaze3d.vertex.PoseStack; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Font; +import net.minecraft.client.renderer.LightTexture; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; +import net.minecraft.util.Mth; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.state.BlockState; +import org.joml.Quaternionf; + +public class StorageMonitorBlockEntityRenderer implements BlockEntityRenderer { + private static final Quaternionf ROTATE_TO_FRONT = new Quaternionf().rotationY(Mth.DEG_TO_RAD * 180); + private static final float FONT_SPACING = -0.23f; + + @Override + public void render(final StorageMonitorBlockEntity blockEntity, + final float tickDelta, + final PoseStack poseStack, + final MultiBufferSource vertexConsumers, + final int light, + final int overlay) { + final Level level = blockEntity.getLevel(); + if (level == null) { + return; + } + final BiDirection direction = getDirection(blockEntity, level); + if (direction == null) { + return; + } + if (!blockEntity.isCurrentlyActive()) { + return; + } + final ResourceAmountTemplate template = blockEntity.getFilteredResource(); + if (template == null) { + return; + } + doRender( + blockEntity.getLevel(), + poseStack, + vertexConsumers, + direction, + template, + blockEntity.getCurrentAmount() + ); + } + + private void doRender(final Level level, + final PoseStack poseStack, + final MultiBufferSource vertexConsumers, + final BiDirection direction, + final ResourceAmountTemplate template, + final long amount) { + final ResourceRendering resourceRendering = PlatformApi.INSTANCE.getResourceRendering( + template.getResource() + ); + doRender( + poseStack, + vertexConsumers, + direction.getQuaternion(), + resourceRendering.getDisplayedAmount(amount, false), + level, + resourceRendering, + template.getResource() + ); + } + + private void doRender(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final Quaternionf rotation, + final String amount, + final Level level, + final ResourceRendering resourceRendering, + final T resource) { + poseStack.pushPose(); + + poseStack.translate(0.5, 0.5, 0.5); + poseStack.mulPose(rotation); + poseStack.mulPose(ROTATE_TO_FRONT); + poseStack.translate(0, 0.05, 0.5); + + poseStack.pushPose(); + renderAmount(poseStack, renderTypeBuffer, amount); + poseStack.popPose(); + + poseStack.pushPose(); + poseStack.translate(0, 0, 0.01f); + resourceRendering.render(resource, poseStack, renderTypeBuffer, LightTexture.FULL_BRIGHT, level); + poseStack.popPose(); + + poseStack.popPose(); + } + + private void renderAmount(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final String amount) { + final Font font = Minecraft.getInstance().font; + final float width = font.width(amount); + poseStack.translate(0.0f, FONT_SPACING, 0.02f); + poseStack.scale(1.0f / 62.0f, -1.0f / 62.0f, 1.0f / 62.0f); + poseStack.scale(0.5f, 0.5f, 0); + poseStack.translate(-0.5f * width, 0.0f, 0.5f); + font.drawInBatch( + amount, + 0, + 0, + 0xFFFFFF, + false, + poseStack.last().pose(), + renderTypeBuffer, + Font.DisplayMode.NORMAL, + 0, + LightTexture.FULL_BRIGHT + ); + } + + @Nullable + private BiDirection getDirection(final StorageMonitorBlockEntity blockEntity, final Level level) { + final BlockState state = level.getBlockState(blockEntity.getBlockPos()); + if (state.getBlock() instanceof StorageMonitorBlock) { + return state.getValue(BiDirectionType.INSTANCE.getProperty()); + } + return null; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/AbstractFluidRenderer.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/AbstractFluidRenderer.java index 225fe296e..091d8b592 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/AbstractFluidRenderer.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/render/model/AbstractFluidRenderer.java @@ -7,8 +7,12 @@ import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.Tesselator; +import com.mojang.blaze3d.vertex.VertexConsumer; import com.mojang.blaze3d.vertex.VertexFormat; import net.minecraft.client.renderer.GameRenderer; +import net.minecraft.client.renderer.MultiBufferSource; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; public abstract class AbstractFluidRenderer implements FluidRenderer { @@ -44,4 +48,47 @@ protected void render(final PoseStack poseStack, .color(r, g, b, 255).endVertex(); tesselator.end(); } + + protected void render(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final int light, + final int packedRgb, + final TextureAtlasSprite sprite) { + final VertexConsumer buffer = renderTypeBuffer.getBuffer(RenderType.text(sprite.atlasLocation())); + final float scale = 0.3F; + // y is flipped here + final var x0 = -scale / 2; + final var y0 = scale / 2; + final var x1 = scale / 2; + final var y1 = -scale / 2; + final var transform = poseStack.last().pose(); + buffer.vertex(transform, x0, y1, 0) + .color(packedRgb) + .uv(sprite.getU0(), sprite.getV1()) + .overlayCoords(OverlayTexture.NO_OVERLAY) + .uv2(light) + .normal(0, 0, 1) + .endVertex(); + buffer.vertex(transform, x1, y1, 0) + .color(packedRgb) + .uv(sprite.getU1(), sprite.getV1()) + .overlayCoords(OverlayTexture.NO_OVERLAY) + .uv2(light) + .normal(0, 0, 1) + .endVertex(); + buffer.vertex(transform, x1, y0, 0) + .color(packedRgb) + .uv(sprite.getU1(), sprite.getV0()) + .overlayCoords(OverlayTexture.NO_OVERLAY) + .uv2(light) + .normal(0, 0, 1) + .endVertex(); + buffer.vertex(transform, x0, y0, 0) + .color(packedRgb) + .uv(sprite.getU0(), sprite.getV0()) + .overlayCoords(OverlayTexture.NO_OVERLAY) + .uv2(light) + .normal(0, 0, 1) + .endVertex(); + } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/AbstractBaseScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/AbstractBaseScreen.java index e4bbf303d..fee620d19 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/AbstractBaseScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/AbstractBaseScreen.java @@ -134,7 +134,7 @@ private void renderResourceSlotAmount(final GuiGraphics graphics, graphics, x, y, - rendering.getDisplayedAmount(amount), + rendering.getDisplayedAmount(amount, true), Objects.requireNonNullElse(ChatFormatting.WHITE.getColor(), 15), true ); diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/StorageMonitorScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/StorageMonitorScreen.java new file mode 100644 index 000000000..47b5cf231 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/StorageMonitorScreen.java @@ -0,0 +1,41 @@ +package com.refinedmods.refinedstorage2.platform.common.screen; + +import com.refinedmods.refinedstorage2.platform.common.containermenu.StorageMonitorContainerMenu; +import com.refinedmods.refinedstorage2.platform.common.containermenu.property.PropertyTypes; +import com.refinedmods.refinedstorage2.platform.common.screen.widget.FuzzyModeSideButtonWidget; +import com.refinedmods.refinedstorage2.platform.common.screen.widget.RedstoneModeSideButtonWidget; + +import net.minecraft.network.chat.Component; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.entity.player.Inventory; + +import static com.refinedmods.refinedstorage2.platform.common.util.IdentifierUtil.createIdentifier; + +public class StorageMonitorScreen extends AbstractBaseScreen { + private static final ResourceLocation TEXTURE = createIdentifier("textures/gui/storage_monitor.png"); + + public StorageMonitorScreen(final StorageMonitorContainerMenu menu, + final Inventory playerInventory, + final Component text) { + super(menu, playerInventory, text); + + this.inventoryLabelY = 43; + this.imageWidth = 211; + this.imageHeight = 137; + } + + @Override + protected void init() { + super.init(); + addSideButton(new RedstoneModeSideButtonWidget(getMenu().getProperty(PropertyTypes.REDSTONE_MODE))); + addSideButton(new FuzzyModeSideButtonWidget( + getMenu().getProperty(PropertyTypes.FUZZY_MODE), + FuzzyModeSideButtonWidget.Type.GENERIC + )); + } + + @Override + protected ResourceLocation getTexture() { + return TEXTURE; + } +} diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/amount/DetectorScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/amount/DetectorScreen.java index 0983ec549..f631c035f 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/amount/DetectorScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/amount/DetectorScreen.java @@ -18,7 +18,7 @@ protected void init() { super.init(); addSideButton(new FuzzyModeSideButtonWidget( getMenu().getProperty(PropertyTypes.FUZZY_MODE), - FuzzyModeSideButtonWidget.Type.DETECTOR + FuzzyModeSideButtonWidget.Type.GENERIC )); addSideButton(new DetectorModeSideButtonWidget(getMenu().getProperty(PropertyTypes.DETECTOR_MODE))); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/hint/FluidGridInsertionHint.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/hint/FluidGridInsertionHint.java index a11b1d503..a2f806c31 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/hint/FluidGridInsertionHint.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/hint/FluidGridInsertionHint.java @@ -1,6 +1,7 @@ package com.refinedmods.refinedstorage2.platform.common.screen.grid.hint; import com.refinedmods.refinedstorage2.platform.api.grid.GridInsertionHint; +import com.refinedmods.refinedstorage2.platform.common.ContainedFluid; import com.refinedmods.refinedstorage2.platform.common.Platform; import com.refinedmods.refinedstorage2.platform.common.screen.tooltip.MouseWithIconClientTooltipComponent; @@ -12,17 +13,21 @@ public class FluidGridInsertionHint implements GridInsertionHint { @Override public Optional getHint(final ItemStack carried) { - return Platform.INSTANCE.convertToFluid(carried).map(resourceAmount -> new MouseWithIconClientTooltipComponent( + return Platform.INSTANCE.getContainedFluid(carried).map(this::createComponent); + } + + private MouseWithIconClientTooltipComponent createComponent(final ContainedFluid result) { + return new MouseWithIconClientTooltipComponent( MouseWithIconClientTooltipComponent.Type.RIGHT, (graphics, x, y) -> Platform.INSTANCE.getFluidRenderer().render( graphics.pose(), x, y, - resourceAmount.getResource() + result.fluid().getResource() ), - resourceAmount.getAmount() == Platform.INSTANCE.getBucketAmount() + result.fluid().getAmount() == Platform.INSTANCE.getBucketAmount() ? null - : Platform.INSTANCE.getBucketAmountFormatter().format(resourceAmount.getAmount()) - )); + : Platform.INSTANCE.getBucketAmountFormatter().format(result.fluid().getAmount()) + ); } } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/tooltip/ResourceClientTooltipComponent.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/tooltip/ResourceClientTooltipComponent.java index 78011bd6e..686af7f05 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/tooltip/ResourceClientTooltipComponent.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/tooltip/ResourceClientTooltipComponent.java @@ -52,7 +52,7 @@ private static Component getNameWithAmount(final ResourceAmountTemplate r final ResourceRendering rendering = PlatformApi.INSTANCE.getResourceRendering( resourceAmount.getResource() ); - final String amount = rendering.getDisplayedAmount(resourceAmount.getAmount()); + final String amount = rendering.getDisplayedAmount(resourceAmount.getAmount(), true); final Component displayName = rendering.getDisplayName(resourceAmount.getResource()); if (amount.isEmpty()) { return displayName; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/widget/FuzzyModeSideButtonWidget.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/widget/FuzzyModeSideButtonWidget.java index 9859b2eac..411ad017e 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/widget/FuzzyModeSideButtonWidget.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/widget/FuzzyModeSideButtonWidget.java @@ -54,7 +54,7 @@ protected Component getHelpText() { public enum Type { STORAGE, - DETECTOR, + GENERIC, EXTRACTING_STORAGE_NETWORK, EXTRACTING_SOURCE; diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/BiDirection.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/BiDirection.java index aea34f2ac..264943074 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/BiDirection.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/util/BiDirection.java @@ -9,24 +9,25 @@ import org.joml.Vector3f; public enum BiDirection implements StringRepresentable { - NORTH(new Vector3f(0, 0, 0)), - EAST(new Vector3f(0, -90, 0)), - SOUTH(new Vector3f(0, 180, 0)), - WEST(new Vector3f(0, 90, 0)), - UP_NORTH(new Vector3f(90, 0, 180)), - UP_EAST(new Vector3f(90, 0, -90)), - UP_SOUTH(new Vector3f(90, 0, 0)), - UP_WEST(new Vector3f(90, 0, 90)), - DOWN_NORTH(new Vector3f(-90, 0, 0)), - DOWN_EAST(new Vector3f(-90, 0, -90)), - DOWN_SOUTH(new Vector3f(-90, 0, 180)), - DOWN_WEST(new Vector3f(-90, 0, 90)); + NORTH(new Vector3f(0, 0, 0), Direction.NORTH), + EAST(new Vector3f(0, -90, 0), Direction.EAST), + SOUTH(new Vector3f(0, 180, 0), Direction.SOUTH), + WEST(new Vector3f(0, 90, 0), Direction.WEST), + UP_NORTH(new Vector3f(90, 0, 180), Direction.UP), + UP_EAST(new Vector3f(90, 0, -90), Direction.UP), + UP_SOUTH(new Vector3f(90, 0, 0), Direction.UP), + UP_WEST(new Vector3f(90, 0, 90), Direction.UP), + DOWN_NORTH(new Vector3f(-90, 0, 0), Direction.DOWN), + DOWN_EAST(new Vector3f(-90, 0, -90), Direction.DOWN), + DOWN_SOUTH(new Vector3f(-90, 0, 180), Direction.DOWN), + DOWN_WEST(new Vector3f(-90, 0, 90), Direction.DOWN); private final Vector3f vec; private final String name; private final Quaternionf quaternion; + private final Direction direction; - BiDirection(final Vector3f vec) { + BiDirection(final Vector3f vec, final Direction direction) { this.vec = vec; this.name = name().toLowerCase(Locale.ROOT); this.quaternion = new Quaternionf().rotateXYZ( @@ -34,6 +35,7 @@ public enum BiDirection implements StringRepresentable { vec.y() * Mth.DEG_TO_RAD, vec.z() * Mth.DEG_TO_RAD ); + this.direction = direction; } public static BiDirection forHorizontal(final Direction horizontalDirection) { @@ -95,4 +97,8 @@ public String getSerializedName() { public Quaternionf getQuaternion() { return quaternion; } + + public Direction asDirection() { + return direction; + } } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/blockstates/storage_monitor.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/blockstates/storage_monitor.json new file mode 100644 index 000000000..01d572529 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/blockstates/storage_monitor.json @@ -0,0 +1,57 @@ +{ + "variants": { + "direction=down_east": { + "model": "refinedstorage2:block/storage_monitor", + "x": 90, + "y": -90 + }, + "direction=down_north": { + "model": "refinedstorage2:block/storage_monitor", + "x": 90 + }, + "direction=down_south": { + "model": "refinedstorage2:block/storage_monitor", + "x": 90, + "y": 180 + }, + "direction=down_west": { + "model": "refinedstorage2:block/storage_monitor", + "x": 90, + "y": 90 + }, + "direction=east": { + "model": "refinedstorage2:block/storage_monitor", + "y": 90 + }, + "direction=north": { + "model": "refinedstorage2:block/storage_monitor" + }, + "direction=south": { + "model": "refinedstorage2:block/storage_monitor", + "y": 180 + }, + "direction=up_east": { + "model": "refinedstorage2:block/storage_monitor", + "x": -90, + "y": -90 + }, + "direction=up_north": { + "model": "refinedstorage2:block/storage_monitor", + "x": -90, + "y": 180 + }, + "direction=up_south": { + "model": "refinedstorage2:block/storage_monitor", + "x": -90 + }, + "direction=up_west": { + "model": "refinedstorage2:block/storage_monitor", + "x": -90, + "y": 90 + }, + "direction=west": { + "model": "refinedstorage2:block/storage_monitor", + "y": 270 + } + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json index e02294bde..59ef8d0bb 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/lang/en_us.json @@ -27,6 +27,7 @@ "block.refinedstorage2.constructor": "Constructor", "block.refinedstorage2.destructor": "Destructor", "block.refinedstorage2.wireless_transmitter": "Wireless Transmitter", + "block.refinedstorage2.storage_monitor": "Storage Monitor", "gui.refinedstorage2.controller.redstone_mode_help": "When this device is inactive, the storage network will not be able to use this device as an energy source.", "gui.refinedstorage2.disk_drive.disks": "Disks", "gui.refinedstorage2.storage.redstone_mode_help": "When this device is inactive, the contained storage will no longer be accessible from within the storage network.", @@ -83,6 +84,7 @@ "gui.refinedstorage2.importer.filter_mode.allow.help": "Only allow resources into the storage network that are configured in the filters.", "gui.refinedstorage2.importer.filter_mode.block.help": "Disallow resources into the storage network that are configured in the filters.", "gui.refinedstorage2.wireless_transmitter.distance": "%d block(s)", + "gui.refinedstorage2.storage_monitor.filter_help": "The resource to display.", "gui.refinedstorage2.redstone_mode": "Redstone mode", "gui.refinedstorage2.redstone_mode.ignore": "Ignore", "gui.refinedstorage2.redstone_mode.ignore.help": "This device will always be active, regardless of redstone signal.", @@ -108,12 +110,12 @@ "gui.refinedstorage2.fuzzy_mode": "Fuzzy mode", "gui.refinedstorage2.fuzzy_mode.on": "On", "gui.refinedstorage2.fuzzy_mode.on.storage_help": "Match the filters for the allowlist or blocklist exactly.", - "gui.refinedstorage2.fuzzy_mode.on.detector_help": "Match the filter exactly.", + "gui.refinedstorage2.fuzzy_mode.on.generic_help": "Match the filter exactly.", "gui.refinedstorage2.fuzzy_mode.on.extracting_storage_network_help": "Match the filters when extracting from the storage network exactly.", "gui.refinedstorage2.fuzzy_mode.on.extracting_source_help": "Match the filters when extracting from the source exactly.", "gui.refinedstorage2.fuzzy_mode.off": "Off", "gui.refinedstorage2.fuzzy_mode.off.storage_help": "Match the filters for the allowlist or blocklist without comparing NBT tags.", - "gui.refinedstorage2.fuzzy_mode.off.detector_help": "Match the filter without comparing NBT tags.", + "gui.refinedstorage2.fuzzy_mode.off.generic_help": "Match the filter without comparing NBT tags.", "gui.refinedstorage2.fuzzy_mode.off.extracting_storage_network_help": "Match the filters when extracting from the storage network without comparing NBT tags.", "gui.refinedstorage2.fuzzy_mode.off.extracting_source_help": "Match the filters when extracting from the source without comparing NBT tags.", "gui.refinedstorage2.access_mode": "Access mode", @@ -290,6 +292,7 @@ "text.autoconfig.refinedstorage2.option.wirelessTransmitter": "Wireless Transmitter", "text.autoconfig.refinedstorage2.option.wirelessTransmitter.energyUsage": "Energy usage", "text.autoconfig.refinedstorage2.option.wirelessTransmitter.baseRange": "Base range", + "text.autoconfig.refinedstorage2.option.storageMonitor.energyUsage": "Energy usage", "advancements.refinedstorage2.root.description": "Use one or multiple Controllers in a network to provide your network with energy", "advancements.refinedstorage2.connecting": "Connecting", "advancements.refinedstorage2.connecting.description": "Use Cable to connect devices with each other, or place devices against each other", @@ -320,5 +323,7 @@ "advancements.refinedstorage2.destruction": "Destruction", "advancements.refinedstorage2.destruction.description": "Get blocks from in the world into the storage network with a Destructor", "advancements.refinedstorage2.wireless": "Wireless", - "advancements.refinedstorage2.wireless.description": "Access your resources wirelessly with a Wireless Grid." + "advancements.refinedstorage2.wireless.description": "Access your resources wirelessly with a Wireless Grid.", + "advancements.refinedstorage2.better_than_a_barrel": "Better than a barrel", + "advancements.refinedstorage2.better_than_a_barrel.description": "Craft a Storage Monitor to view, insert or extract resources in a storage network" } diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk.json index 9e2a90de0..3b5925d4b 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk.json @@ -1,6 +1,6 @@ { "textures": { - "base": "refinedstorage2:block/disk" + "base": "refinedstorage2:block/disk_drive/disk" }, "elements": [ { diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_drive_base.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_drive_base.json index c23ba436a..fd97de0e7 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_drive_base.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_drive_base.json @@ -1,11 +1,11 @@ { "parent": "block/block", "textures": { - "particle": "refinedstorage2:block/disk_drive", - "front": "refinedstorage2:block/disk_drive", - "bottom": "refinedstorage2:block/disk_drive_bottom", - "top": "refinedstorage2:block/disk_drive_top", - "side": "refinedstorage2:block/disk_drive_side" + "particle": "refinedstorage2:block/disk_drive/front", + "front": "refinedstorage2:block/disk_drive/front", + "bottom": "refinedstorage2:block/disk_drive/bottom", + "top": "refinedstorage2:block/disk_drive/top", + "side": "refinedstorage2:block/disk_drive/side" }, "elements": [ { diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_inactive.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_inactive.json index 773f835f2..ffac12be9 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_inactive.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/disk_inactive.json @@ -1,6 +1,6 @@ { "textures": { - "base": "refinedstorage2:block/disk" + "base": "refinedstorage2:block/disk_drive/disk" }, "elements": [ { diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_active.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_active.json index d1e503c0c..d1b902270 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_active.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_active.json @@ -1,6 +1,6 @@ { "parent": "block/cube_all", "textures": { - "all": "refinedstorage2:block/interface_active" + "all": "refinedstorage2:block/interface/active" } } \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_inactive.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_inactive.json index 7b07d961a..43d2d258d 100644 --- a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_inactive.json +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/interface_inactive.json @@ -1,6 +1,6 @@ { "parent": "block/cube_all", "textures": { - "all": "refinedstorage2:block/interface_inactive" + "all": "refinedstorage2:block/interface/inactive" } } \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/storage_monitor.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/storage_monitor.json new file mode 100644 index 000000000..422b44501 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/block/storage_monitor.json @@ -0,0 +1,12 @@ +{ + "parent": "block/cube", + "textures": { + "particle": "refinedstorage2:block/side", + "north": "refinedstorage2:block/storage_monitor/front", + "east": "refinedstorage2:block/storage_monitor/left", + "south": "refinedstorage2:block/storage_monitor/back", + "west": "refinedstorage2:block/storage_monitor/right", + "up": "refinedstorage2:block/storage_monitor/top", + "down": "refinedstorage2:block/bottom" + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/storage_monitor.json b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/storage_monitor.json new file mode 100644 index 000000000..90256ac6c --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/models/item/storage_monitor.json @@ -0,0 +1,3 @@ +{ + "parent": "refinedstorage2:block/storage_monitor" +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_bottom.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/bottom.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_bottom.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/bottom.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/disk.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/disk.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/front.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/front.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_side.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/side.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_side.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/side.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_top.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/top.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive_top.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/disk_drive/top.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface_active.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface/active.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface_active.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface/active.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface_inactive.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface/inactive.png similarity index 100% rename from refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface_inactive.png rename to refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/interface/inactive.png diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/side.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/side.png new file mode 100644 index 0000000000000000000000000000000000000000..fb581557600370be2d35233c4c00c6690ad6aa6e GIT binary patch literal 15349 zcmeI3e{37&8OPrsKp_)T!lcomF*#RNKsEb*IOo_`$EA%E5>#iEo3trIT`zaKEpE1KBEG_LU%=smabJ`VfR!_gDJg2n%$F4%hXhM zsr{&srRD^bEhEus7?D7>TsP+L-qGBgDNo1kTlAP}B+WbgY-vidaEfj)C|fXq3ftr4 z1*hQcoW|CEwc!Ug9*M{;Qjc8jq1$QUf9AbmyZooY-WvK_+h^lPK z%W}cBi+w^NsXb;|a!i5k!2p`OOV?FN^JqRO_b5&`ukp?vwV}}|ivn~u@(o@eFK9}m zSItavarzSLprH)fg_N^ak+sm++9(J-C$9I3Jm2D3C$#ulMW1iID0)4f25;ULOI>OU z6Z#IQwkC{dW{=0^gbD4f)5PTWPT^3<6+&k7N&3>MX77g!R=%Glsm1$2=KgHAT4|gUcs+}xr_yN6UYq>)25qf{|sT{+w-;$*G+I> zacjOKqAzn{3d@6zG)Y$MV>@8VXmR~)=9tU36>ln=VGooQlv&f|mG6@D%3~z^V9eg` zm9}cuDx<1wVj7y2loN1WFWM2yIf=5ai_NLsv>DdA}U(}Ju3G?HXiHsv&F{ZnEt|Vfz)h7j08H-V8HEX%Qa(J_OF0l z-w2hQDGJ`tE@>;(ciX!^GMLdf3LLu7LkGHYsd#s3>ej2L;@zdG#muglZUuzgXeG^9 zmi<$eg|P`ep22`e6y2hqEp0B%*r=yqq&uji1J$&*3Gd0}ly;O&+*&CS>&PW$O96Y3 z%2Z0W6+Nb*Cq%aJh`6|j3VZV#4vI7ShK+GMItWgK7*kwCM7V(B!f6m=ii?N{7f@U{ z4Ps1j5fR}6iVLSfj43W6B3wXm;WUUb#YIGf3n(s}1~I0%h=_0j#f8%##uOJ35iX#( za2mvz;vyo#1r!%fgBVj>L`1lN;=*YVV~UH22p3RXI1OSar$LObimRsh(j|csl^negJMZ_WtCZRsgF0&>mdZnR?H^_jpI7zP9E3 zb-O>B7}&ny@-2V5vUdI}aNDubEr0yJ_s%Zg(Z6n8b@cb|O&>k};X`S&!@ZIL)%6qi zE!+xfN5{H;I(Bko>^d-a_N+2ucGL}}Qn!!q3-^qC`PRahbN4*Se?He-{qy&q0^3Ih zezk4q!sPI~!?S-m`PJ_G4gUInz542H!ONE~M-Cra{mzQ2zkl+HbNpJc^YEP?fOEU% zer&$|PjBs~pM5qx{aCt31M$F%{fE!Le(3YLx`C%(QZ}GhS1--9r`v*jE3zHs3vF{@^#G;hRRU)J@iaJH~zgJ}@>GRNHT;-xof8gt_^Z$*1|}#I99A z|MMO7*SdG^+I8=Jbps=>ADCFp>`Bk8e0k#I|L#eT@7uR`W@=B+lAhmxY4+T}FV_5W zjeF{t_MG{G>9Xn$O}}}1ef9iXJKC7N;s0H{_~$pD8dFBJ? h_W!Q_<+D}bA7J;u=zs3rY`>V>-qI0#ZT}G literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/back.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/back.png new file mode 100644 index 0000000000000000000000000000000000000000..ffb76f755fa9a787972cd4c17b1c3dca2b1ab4b1 GIT binary patch literal 1415 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61SBU+%rFB|k|nMYCBgY=CFO}lsSJ)O`AMk? zp1FzXsX?iUDV2pMQ*9U+nDa72B1$5BeXNr6bM+EIYV;~{3xK*A7;Nk-3KEmEQ%e+* zQqwc@Y?a>c-mj#PnPRIHZt82`Ti~3Uk?B!Ylp0*+7m{3+ootz+WN)WnQ(*-(AUCxn zQK2F?C$HG5!d3}vt`(3C64qBz04piUwpD^SD#ABF!8yMuRl!uxOgGuk&``nLQqR!T z!q~`EN5ROz&{W^RQs2-(*TB%q(7?*bKmiJrfVLH-q*(>IxIyg#@@$ndN=gc>^!3Zj z%k|2Q_413-^$jg8E%gnI^o@*kfhu&1EAvVcD|GXUm0>2hq!uR^WfqiV=I1GZOiWD5 zFD#PU%0_}#n6BP2AO_EVu8M)o`HUDF34YC)x{-2sR(CaRb3oXS&*t9 zlv|9-O^tOeQ%y{DEmM*#b&U;;4N_AQ%`FU*4PfSA({E{RVd~;)WME-p4oIBp4nO9trn3tRivpW-LH$<phIbtAf7XZzyuX?y}6TK
    js(5`t?UIDBps zydCLndOza&&3)TX$$#Ntw($~PaQ$RTQ)AU-lRSy4?42*SJ0GsFxmdA9qgk$bnWoZb zMK@VnzIL^xYOW?3hx(5@Uplo(g}2{>{pby*Tuw=v7q4Ll)rDvtlj$EKMOWD+zsT?&%D#q zZSuvzUsL5n%iaGq8`gzspZGIlE89VbhDqlqTc7{@waRx&(7)?D;?{3+O?r`dBOqvk j%+JG(r;1Me=Q3c({@o?*e|U}qsA%+b^>bP0l+XkKE;Id| literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/front.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/front.png new file mode 100644 index 0000000000000000000000000000000000000000..d7a267815296bbeb4a5fa9a3f4bff269b0b43590 GIT binary patch literal 1273 zcmbVMZEO=|96#|TrWrcX4-U{A2aYXrZ@pgIyY!e_uN#f)+)8C-WXSdI>3ZAluDyFk z+etzqbEdv!ATe_x1U>-CG-&vuvJj^v5>e0~zJw*ZEEpwxz$_$u7%x88wbKs^AH3xL z&&&OO|M&luIy>4{dRBWd3|kr9BFE8M>%Nb!Kyqw<#*dad7)ipdRvP9N8(__vl>&Iw zQ2Ia|C|WW14G3Y_gS+)a5+-BqqG}nG;$oBE=kkPjc+hFT(M?xJQPz8->+Kh(^B2r)gsNe--&~(ItM3nW4XzyOr1YU-~ z0f|_2DjDmBtno*(S%BYG@bQT4Ki?4ThBt>GI3X< zlCp-NL?BNWLol+j*pgz?sU!-ej4miynxz=pFx@Ix`luoQ##l!{Kt(@rG{Q)U3SI=$2_QY8lx2ZlJZ=mVuY^ zEb7bnAOsi^4CFHH(6r;#WsR$v5;1DckjyUp^S=BZwxj&!$6 zqks-e!vst;K{gtdbyxSsFzkW4sN9?=T!9C!d-gFkug~;Yvs~ld%iTB6?5S1GPA&8& z8{T~;d12zvh7%=Y=I5TN8wuG~KQ=P|SZ;3o z$mCa4?8nQur1lRQ-cz2~{>k6dZ*oqeQxdrT8|96#|@napPDHr?xXFb5gES6kX%D5msUD6}k#Sy1na8#<1Rgh$ z{bpoBRH?H7whAJE^=O91Ll6XPFrkFrs3rC3Fo_d-3^!o}uE7b4z$p@kCm%%dCbC|t zh_+AqQdVZfC(A(!!$P4D8q%VIxEdo&CKHB}7)fdr3yoCE%S>3qOUZEt8b}_I3(B0p z!!bt2Ev%8vh@y1j3W1>0IYrD%lYvq~hJ~3RMxZzr2*mC+ZY{}0;9nWjT1&3lAi#=% zB&-oVN~ocDr%_LL{3QxQ%wt=H37iO4%&<;Cn(FYl$&(B39nYC(QEZu zjS1-V8WZa_X|#kE2P|VS5*|FxGaX*1H<1KxH`qy?l^|>xmTZ!+8w|8wYalGNO&`ZP zcu8h>4~YBb6yKBBj7MTAs|Xlb5M6>$9j}4{pCAj8PYA+R>v-1T)Dn(og^-jMOVh-y zX&`cM0@f}H0eC#l6gQ0qqb);=XV`5<9chp0&n9fPY@I&aK;l-DK}#c(SazD&O=9i; zi^UW%Sgc6?Q#A1{r4nP)sTNQcQ%wYTrE^53MHbvZqYyOXyo0v5!k1QTKGJprS8r(U z8ve$1r~pn)RWI6lct-U2!dpvkUvQ~jY*4Fw=$YQ(VI;qwzLFmqi z_lvSX@2c76SsMqE+dSWYy#rTeeu4~Rt<5L?tUL0s6?u9?Zeh|u(D-rjdm!)A^r(Np z(Ry}gi6P?C-G6G}82yo^{+VZI|9Y`)X2)m#Enr!+nSDqX?x}$KK5yaF)*A2pujZ}Y z+tZKsocZqZ`6Tj9)Ic|#%4&@`tm zb?=G0EtOSOYIA4g)a|hc5f|Eb^2)J4#&XaniQ=8tcdh?<-O)YKcV^6iK73f&>Y*NA Q75jZUZ29!Q?8?S}0J$~}(*OVf literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/right.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/block/storage_monitor/right.png new file mode 100644 index 0000000000000000000000000000000000000000..8a7d7d2c5163a961f5894538593765666c83c340 GIT binary patch literal 1443 zcmaJ>eNYr-9A1?WP0S%Q4RV%+;lsGwkNe zEktb;YesBzz=mczC!L`Qh-fIvQDK~9Gz^O&aGGSawD_8$h7=sz1CIKG+?n0?>-Rjr z=ly-`5nKLq(QBVx3qeq{WxLTXjT=I5)Jo}ltii38hApDWAr^3@qMzmgq-QuMfGr-n z4A=q9?5XSnSrD|!%N9CBhc%CMaUMAxvXKWoJ_!v$Svdh8?J5T%>;z@3SBFe}c^-jT zMu!xsteDkD0XMt7h6e>T`Gu~Ua+j7tasRuF@z7RXR*yxC+IzD2~Z6oWwDbz~IFPk-YIt zDQP#F7kx=99pV;6ABm!VzhCZG$T_|Y#kE>3iV-M5$RrDyu*WOX0hw1w3^N#k;Nn@I z$Z}pd#7H~2Dp7|>N*Au+@mZ})#9m=BP*TXy0PRC@Ifi;Xp?l3+3!)wTD`Qz}p>U56 zpmrc|RlG~eM`>ahEXD58jzWf#8geJkN=czBjGU{=1H7Wes6(U^Im0rflW;omQiW2c zQm7O%El{dtTE?lBDR2b_7&=3PyRb0Na(D%$RO>Sg1~Z|gaNMLeXiRE~FyR?`gULu? ziZIsV6-3(W0%6~*SP5p1V z8xDQf+`n_|a^9pt95w8X?5h9!{p_PtH|@noqPF#%&{$HE`-jptCm#!Tcjq@341W0H zM=BB*$12A-ufV+vsm7BW1{9bXc1v@ew8nJ2o76Ww$A4jaEFp4B&uq@MU4uPw zrl0yhd;Vfwdoa~T#IL7eYnLZZ+~?v8^I5Inl#+x?wpU3%`=nKcRP zdd~{CH}*HwVlg9=is02%b+yMGLGch3zq=}__@(m7PUcDk*A=&GPHAm=Vx0r+ZM-u* zJT=pY*J^yLE6C=$r`qrSa+u0L38Gwv+UNwi`n~9E|KYiPg#P|yX5*WhVBV?Tz1e4> z;p?@3=B`1KF8gL?&!w1R#vgW!2eSTfbT;gJgZO!T?Adp2T`b8>85-NzjwZzQ+-Z4@ zXo`4d)L+z=x+5oeX1^zE>yxWb-vh7S)yA(U4nz*7jwR=}{V;v+ZFS4+D>YeLiO+{C zl3%}cx;-(u{z5@x)NS}db^4~qn+|*xc_|Q4LIlqrm1RCmya3&gFGd*Q>dnw^(_+du Jwi-(6{sCeM}Q)96o_%LPA!FOvR5J$C5dqy{}&F-CCgZ=;)wGY9n>(#Mh59TFz@7M2n ze$V^+xaRV*S5i|lQXmLQwHLEab<{-P)d}kN_z9mu9X2RMZe@p5rGz*cKo(x|0NC#5 zs(}-5eEt3*V1l4TQE<5xx1*HtN`4&|wb6zB0Tm5Fru=Y#^VR?b_JC?ZG$Rkc97JG& zHzO6419Jqdz$X+p$Y4i9nakTyjcdbRkkF$<-)M(=>_^C_!jd3vIAoRJgEK3}(d{SP=BeLO>BD z5sor)9;r?-BdXG+EBFHr$1<@Pj0H*!85-sSD6Yd$zdw4fMeCsA1pmrd(K_g=4*=8& zf>NFARr67m6$h)ad%B~jp{j=2E(>Z>xLQ{7*7<>`*jY28p6GaiXFP<*gIAGyEk#nK zmIiuCOYg0Soi4Y4x>#-^AgY}st1Yr{a%~R;t!lHg7FYO3(}%;|O_=7$`>iwW z{lDweb`JbuZdAsvMp~MiYxcIU?wC6`%?`ld-a1R(zj^#@*+t=WtMgX>3-&AXkzJ?W z8XVU<`uBZe*G^_mbUhg8y!`OVg{__8;zOC>*xgqTZ2HDD((}WmcYZxM*anjE)=_uO z!j1Ix9g)gCroRHl-{zm(lap^ptVaTghd+8eyKuGm((J;fxi#i39}HJzMHEfROgh;& z=I62-aORXdZXnlTfyJV+n+jz&j}jk`wO}2BU2+e z?cO=(hR&q<2Y({xduH-RdP8F~`Stgk3Oh8jjd{rv*SVBcyOT!0n4a1rO^-LU+}Zaz zvEO)eB5az}l)8VqC!eqk_5SkQ#f=pU4n8~K@w!Ur4X5SMn>ps(=r7P-RK|7}RyO?u Dom}%M literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/gui/storage_monitor.png b/refinedstorage2-platform-common/src/main/resources/assets/refinedstorage2/textures/gui/storage_monitor.png new file mode 100644 index 0000000000000000000000000000000000000000..df26907155a169347a8fd3871468a1eb4eabe30c GIT binary patch literal 1816 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K58911MRQ8&P5D>38$lZxy-8q?;Kn_c~qpu?a z!^VE@KZ&di49pAxJ|V6^adUI?(9qEC?(Sp9j{X1tA1E>kMnhnPgh10{aTQRmDGBlm z1}6TI3>bpHv#SE5owL9rvY3H^?=T269?xHq0u+=iag8Vm&QB{TPb^AhC`ioAE78kK zEm1JhGte_Ma%RbX!@$5);OXKRQW5v|)@v_jM*-G{rqjRIKe;-i$o)YSnS}kX5%)Ru!e(x3T8s?Z~C00|p?=V#SYG4s?V0afhje&_n zfx%yX0+2qi_q31$1EUwCot*V&M^9mfbNo~7Vi_1&9^6aiRA^ve`tW5E%Y*NBLJj<0 zAcZ^1Bbhh?xC{3E*FL`f$ATq{40}P!?(EiK1Q|ZhP60?aR8Ln0YUMa^nf(gK0sAd$ z&b@gx-+vclMQeFU?RH_XN+e|(2&0mfwQYvfFonmNiInDma)OSjn2O z+qT^2D?_}!O|?@r`+>L721|c0)y}SXvW6ugS-7Fsm%+@8@y3mz$JtW*pJgLkYbfg( R)+A72<>~6@vd$@?2>`Z}7mNS^ literal 0 HcmV?d00001 diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/better_than_a_barrel.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/better_than_a_barrel.json new file mode 100644 index 000000000..a05321c59 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/advancements/better_than_a_barrel.json @@ -0,0 +1,28 @@ +{ + "display": { + "icon": { + "item": "refinedstorage2:storage_monitor" + }, + "title": { + "translate": "advancements.refinedstorage2.better_than_a_barrel" + }, + "description": { + "translate": "advancements.refinedstorage2.better_than_a_barrel.description" + } + }, + "parent": "refinedstorage2:root", + "criteria": { + "storage_monitor_in_inventory": { + "trigger": "minecraft:inventory_changed", + "conditions": { + "items": [ + { + "items": [ + "refinedstorage2:storage_monitor" + ] + } + ] + } + } + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/loot_tables/blocks/storage_monitor.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/loot_tables/blocks/storage_monitor.json new file mode 100644 index 000000000..f097506cd --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/loot_tables/blocks/storage_monitor.json @@ -0,0 +1,19 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "rolls": 1, + "entries": [ + { + "type": "minecraft:item", + "name": "refinedstorage2:storage_monitor" + } + ], + "conditions": [ + { + "condition": "minecraft:survives_explosion" + } + ] + } + ] +} \ No newline at end of file diff --git a/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/storage_monitor.json b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/storage_monitor.json new file mode 100644 index 000000000..ac7b229d1 --- /dev/null +++ b/refinedstorage2-platform-common/src/main/resources/data/refinedstorage2/recipes/storage_monitor.json @@ -0,0 +1,31 @@ +{ + "type": "minecraft:crafting_shaped", + "pattern": [ + "PCG", + "EMG", + "PDG" + ], + "key": { + "P": { + "item": "refinedstorage2:basic_processor" + }, + "C": { + "item": "refinedstorage2:construction_core" + }, + "G": { + "item": "minecraft:glass" + }, + "E": { + "item": "refinedstorage2:quartz_enriched_iron" + }, + "M": { + "item": "refinedstorage2:machine_casing" + }, + "D": { + "item": "refinedstorage2:destruction_core" + } + }, + "result": { + "item": "refinedstorage2:storage_monitor" + } +} \ No newline at end of file diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java index 88b9851f9..1073aec9e 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ClientModInitializerImpl.java @@ -12,6 +12,7 @@ import com.refinedmods.refinedstorage2.platform.common.content.KeyMappings; import com.refinedmods.refinedstorage2.platform.common.item.RegulatorUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.render.NetworkItemItemPropertyFunction; +import com.refinedmods.refinedstorage2.platform.common.render.entity.StorageMonitorBlockEntityRenderer; import com.refinedmods.refinedstorage2.platform.common.render.model.ControllerModelPredicateProvider; import com.refinedmods.refinedstorage2.platform.common.screen.tooltip.CompositeClientTooltipComponent; import com.refinedmods.refinedstorage2.platform.common.screen.tooltip.HelpClientTooltipComponent; @@ -239,6 +240,10 @@ private void registerBlockEntityRenderers() { BlockEntities.INSTANCE.getDiskDrive(), ctx -> new DiskDriveBlockEntityRendererImpl<>() ); + BlockEntityRenderers.register( + BlockEntities.INSTANCE.getStorageMonitor(), + ctx -> new StorageMonitorBlockEntityRenderer() + ); } private void registerCustomModels() { diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java index b65a123ac..49f8c4428 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/ConfigImpl.java @@ -70,6 +70,11 @@ public class ConfigImpl implements ConfigData, com.refinedmods.refinedstorage2.p @ConfigEntry.Gui.CollapsibleObject private WirelessTransmitterEntryImpl wirelessTransmitter = new WirelessTransmitterEntryImpl(); + @ConfigEntry.Gui.CollapsibleObject + private SimpleEnergyUsageEntryImpl storageMonitor = new SimpleEnergyUsageEntryImpl( + DefaultEnergyUsage.STORAGE_MONITOR + ); + public static ConfigImpl get() { return AutoConfig.getConfigHolder(ConfigImpl.class).getConfig(); } @@ -159,6 +164,11 @@ public WirelessTransmitterEntry getWirelessTransmitter() { return wirelessTransmitter; } + @Override + public SimpleEnergyUsageEntry getStorageMonitor() { + return storageMonitor; + } + private static class GridEntryImpl implements GridEntry { private boolean largeFont = false; diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java index 877849b91..273f7e10f 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/PlatformImpl.java @@ -8,6 +8,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; +import com.refinedmods.refinedstorage2.platform.common.ContainedFluid; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketAmountFormatting; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; @@ -22,8 +23,7 @@ import com.refinedmods.refinedstorage2.platform.fabric.packet.c2s.ClientToServerCommunicationsImpl; import com.refinedmods.refinedstorage2.platform.fabric.packet.s2c.ServerToClientCommunicationsImpl; import com.refinedmods.refinedstorage2.platform.fabric.render.FluidVariantFluidRenderer; -import com.refinedmods.refinedstorage2.platform.fabric.util.BucketSingleStackStorage; -import com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil; +import com.refinedmods.refinedstorage2.platform.fabric.util.SingleStackStorageImpl; import java.util.List; import java.util.Optional; @@ -88,6 +88,7 @@ import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.Vec3; +import static com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil.ofFluidVariant; import static com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil.toFluidVariant; import static com.refinedmods.refinedstorage2.platform.fabric.util.VariantUtil.toItemVariant; @@ -147,11 +148,24 @@ public GridResourceFactory getFluidGridResourceFactory() { } @Override - public Optional> convertToFluid(final ItemStack stack) { + public Optional getContainedFluid(final ItemStack stack) { if (stack.isEmpty()) { return Optional.empty(); } - return convertNonEmptyToFluid(stack); + final SingleStackStorageImpl interceptingStorage = new SingleStackStorageImpl(stack); + final Storage storage = FluidStorage.ITEM.find(stack, ContainerItemContext.ofSingleSlot( + interceptingStorage + )); + try (Transaction tx = Transaction.openOuter()) { + final var extracted = StorageUtil.extractAny(storage, Long.MAX_VALUE, tx); + if (extracted == null) { + return Optional.empty(); + } + return Optional.of(new ContainedFluid( + interceptingStorage.getStack(), + new ResourceAmount<>(ofFluidVariant(extracted.resource()), extracted.amount()) + )); + } } @Override @@ -167,7 +181,7 @@ public Optional convertJeiIngredientToFluid(final Object ingredie @Override public Optional convertToBucket(final FluidResource fluidResource) { - final BucketSingleStackStorage interceptingStorage = new BucketSingleStackStorage(); + final SingleStackStorageImpl interceptingStorage = SingleStackStorageImpl.forEmptyBucket(); final Storage destination = FluidStorage.ITEM.find( interceptingStorage.getStack(), ContainerItemContext.ofSingleSlot(interceptingStorage) @@ -181,18 +195,6 @@ public Optional convertToBucket(final FluidResource fluidResource) { } } - private Optional> convertNonEmptyToFluid(final ItemStack stack) { - final Storage storage = FluidStorage.ITEM.find( - stack, - new ConstantContainerItemContext(ItemVariant.of(stack), 1) - ); - return Optional.ofNullable(StorageUtil.findExtractableContent(storage, null)) - .map(content -> new ResourceAmount<>( - VariantUtil.ofFluidVariant(content.resource()), - content.amount() - )); - } - @Override public TransferManager createTransferManager(final AbstractContainerMenu containerMenu) { return new TransferManager(containerMenu, ContainerTransferDestination::new); diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridExtractionStrategy.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridExtractionStrategy.java index a38915a68..074b53eec 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridExtractionStrategy.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/internal/grid/FluidGridExtractionStrategy.java @@ -12,7 +12,7 @@ import com.refinedmods.refinedstorage2.platform.api.storage.PlayerActor; import com.refinedmods.refinedstorage2.platform.api.storage.channel.PlatformStorageChannelType; import com.refinedmods.refinedstorage2.platform.common.internal.storage.channel.StorageChannelTypes; -import com.refinedmods.refinedstorage2.platform.fabric.util.BucketSingleStackStorage; +import com.refinedmods.refinedstorage2.platform.fabric.util.SingleStackStorageImpl; import net.fabricmc.fabric.api.transfer.v1.context.ContainerItemContext; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidStorage; @@ -65,7 +65,7 @@ public boolean onExtract(final PlatformStorageChannelType storageChannelT private void extractWithBucketInStorage(final FluidResource fluidResource, final GridExtractMode mode, final boolean cursor) { - final BucketSingleStackStorage interceptingStorage = new BucketSingleStackStorage(); + final SingleStackStorageImpl interceptingStorage = SingleStackStorageImpl.forEmptyBucket(); final net.fabricmc.fabric.api.transfer.v1.storage.Storage destination = FluidStorage.ITEM.find( interceptingStorage.getStack(), ContainerItemContext.ofSingleSlot(interceptingStorage) @@ -94,7 +94,7 @@ private void extractWithBucketInInventory(final FluidResource fluidResource, final boolean cursor) { try (Transaction tx = Transaction.openOuter()) { playerInventoryStorage.extract(BUCKET_ITEM_VARIANT, 1, tx); - final BucketSingleStackStorage interceptingStorage = new BucketSingleStackStorage(); + final SingleStackStorageImpl interceptingStorage = SingleStackStorageImpl.forEmptyBucket(); final net.fabricmc.fabric.api.transfer.v1.storage.Storage dest = FluidStorage.ITEM.find( interceptingStorage.getStack(), ContainerItemContext.ofSingleSlot(interceptingStorage) @@ -123,7 +123,7 @@ private void extractWithBucketInInventory(final FluidResource fluidResource, } } - private boolean insertResultingBucketIntoInventory(final BucketSingleStackStorage interceptingStorage, + private boolean insertResultingBucketIntoInventory(final SingleStackStorageImpl interceptingStorage, final boolean cursor, final Transaction innerTx) { final net.fabricmc.fabric.api.transfer.v1.storage.Storage relevantStorage = cursor diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/FluidVariantFluidRenderer.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/FluidVariantFluidRenderer.java index 4852d21a6..85d9db524 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/FluidVariantFluidRenderer.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/render/FluidVariantFluidRenderer.java @@ -13,6 +13,7 @@ import net.fabricmc.fabric.api.transfer.v1.fluid.FluidVariant; import net.fabricmc.fabric.api.transfer.v1.fluid.FluidVariantAttributes; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.network.chat.Component; import net.minecraft.world.item.TooltipFlag; @@ -31,10 +32,25 @@ public void render(final PoseStack poseStack, final FluidResource fluidResource) { final FluidVariant fluidVariant = getFluidVariantFromCache(fluidResource); final TextureAtlasSprite sprite = FluidVariantRendering.getSprite(fluidVariant); - if (sprite != null) { - final int packedRgb = FluidVariantRendering.getColor(fluidVariant); - render(poseStack, x, y, packedRgb, sprite); + if (sprite == null) { + return; } + final int packedRgb = FluidVariantRendering.getColor(fluidVariant); + render(poseStack, x, y, packedRgb, sprite); + } + + @Override + public void render(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final int light, + final FluidResource fluidResource) { + final FluidVariant fluidVariant = getFluidVariantFromCache(fluidResource); + final TextureAtlasSprite sprite = FluidVariantRendering.getSprite(fluidVariant); + if (sprite == null) { + return; + } + final int packedRgb = FluidVariantRendering.getColor(fluidVariant); + render(poseStack, renderTypeBuffer, light, packedRgb, sprite); } @Override diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/BucketSingleStackStorage.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/SingleStackStorageImpl.java similarity index 54% rename from refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/BucketSingleStackStorage.java rename to refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/SingleStackStorageImpl.java index eee423e36..34289db78 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/BucketSingleStackStorage.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/util/SingleStackStorageImpl.java @@ -4,8 +4,16 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; -public class BucketSingleStackStorage extends SingleStackStorage { - private ItemStack stack = new ItemStack(Items.BUCKET); +public final class SingleStackStorageImpl extends SingleStackStorage { + private ItemStack stack; + + public SingleStackStorageImpl(final ItemStack stack) { + this.stack = stack; + } + + public static SingleStackStorageImpl forEmptyBucket() { + return new SingleStackStorageImpl(new ItemStack(Items.BUCKET)); + } @Override public ItemStack getStack() { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java index 8005d9c8c..49d796b16 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ClientModInitializer.java @@ -10,6 +10,7 @@ import com.refinedmods.refinedstorage2.platform.common.content.KeyMappings; import com.refinedmods.refinedstorage2.platform.common.item.RegulatorUpgradeItem; import com.refinedmods.refinedstorage2.platform.common.render.NetworkItemItemPropertyFunction; +import com.refinedmods.refinedstorage2.platform.common.render.entity.StorageMonitorBlockEntityRenderer; import com.refinedmods.refinedstorage2.platform.common.render.model.ControllerModelPredicateProvider; import com.refinedmods.refinedstorage2.platform.common.screen.tooltip.CompositeClientTooltipComponent; import com.refinedmods.refinedstorage2.platform.common.screen.tooltip.HelpClientTooltipComponent; @@ -141,6 +142,10 @@ private static void registerBlockEntityRenderer() { BlockEntities.INSTANCE.getDiskDrive(), ctx -> new DiskDriveBlockEntityRendererImpl<>() ); + BlockEntityRenderers.register( + BlockEntities.INSTANCE.getStorageMonitor(), + ctx -> new StorageMonitorBlockEntityRenderer() + ); } private static void registerGridSynchronizers() { diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java index e249e5ae6..782b8fd36 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/ConfigImpl.java @@ -35,6 +35,7 @@ public class ConfigImpl implements Config { private final SimpleEnergyUsageEntry constructor; private final WirelessGridEntry wirelessGrid; private final WirelessTransmitterEntry wirelessTransmitter; + private final SimpleEnergyUsageEntry storageMonitor; public ConfigImpl() { cable = new SimpleEnergyUsageEntryImpl("cable", "Cable", DefaultEnergyUsage.CABLE); @@ -58,6 +59,11 @@ public ConfigImpl() { constructor = new SimpleEnergyUsageEntryImpl("constructor", "Constructor", DefaultEnergyUsage.CONSTRUCTOR); wirelessGrid = new WirelessGridEntryImpl(); wirelessTransmitter = new WirelessTransmitterEntryImpl(); + storageMonitor = new SimpleEnergyUsageEntryImpl( + "storageMonitor", + "Storage Monitor", + DefaultEnergyUsage.STORAGE_MONITOR + ); spec = builder.build(); } @@ -150,6 +156,11 @@ public WirelessTransmitterEntry getWirelessTransmitter() { return wirelessTransmitter; } + @Override + public SimpleEnergyUsageEntry getStorageMonitor() { + return storageMonitor; + } + private class SimpleEnergyUsageEntryImpl implements SimpleEnergyUsageEntry { private final ForgeConfigSpec.LongValue energyUsage; diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java index 56ea8b0f1..29213daac 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/PlatformImpl.java @@ -8,6 +8,7 @@ import com.refinedmods.refinedstorage2.platform.api.resource.ItemResource; import com.refinedmods.refinedstorage2.platform.common.AbstractPlatform; import com.refinedmods.refinedstorage2.platform.common.Config; +import com.refinedmods.refinedstorage2.platform.common.ContainedFluid; import com.refinedmods.refinedstorage2.platform.common.containermenu.transfer.TransferManager; import com.refinedmods.refinedstorage2.platform.common.util.BucketAmountFormatting; import com.refinedmods.refinedstorage2.platform.common.util.CustomBlockPlaceContext; @@ -69,6 +70,7 @@ import net.minecraftforge.common.util.FakePlayerFactory; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.level.BlockEvent; +import net.minecraftforge.fluids.FluidActionResult; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidType; import net.minecraftforge.fluids.FluidUtil; @@ -142,14 +144,22 @@ public GridResourceFactory getFluidGridResourceFactory() { } @Override - public Optional> convertToFluid(final ItemStack stack) { - return stack - .getCapability(ForgeCapabilities.FLUID_HANDLER_ITEM, null) - .map(handler -> handler.getFluidInTank(0)) - .map(contents -> contents.isEmpty() ? null : new ResourceAmount<>( - new FluidResource(contents.getFluid(), contents.getTag()), - contents.getAmount()) - ); + public Optional getContainedFluid(final ItemStack stack) { + final FluidTank tank = new FluidTank(Integer.MAX_VALUE); + final FluidActionResult result = FluidUtil.tryEmptyContainer( + stack, + tank, + Integer.MAX_VALUE, + null, + true + ); + if (!result.isSuccess() || tank.isEmpty()) { + return Optional.empty(); + } + return Optional.of(new ContainedFluid( + result.getResult(), + new ResourceAmount<>(ofFluidStack(tank.getFluid()), tank.getFluidAmount()) + )); } @Override diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/FluidStackFluidRenderer.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/FluidStackFluidRenderer.java index 00a597c67..64bf8246e 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/FluidStackFluidRenderer.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/render/FluidStackFluidRenderer.java @@ -10,6 +10,7 @@ import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.Minecraft; +import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; @@ -42,6 +43,22 @@ public void render(final PoseStack poseStack, final int x, final int y, final Fl render(poseStack, x, y, packedRgb, sprite); } + @Override + public void render(final PoseStack poseStack, + final MultiBufferSource renderTypeBuffer, + final int light, + final FluidResource fluidResource) { + final FluidStack stack = getFluidStackFromCache(fluidResource); + final Fluid fluid = fluidResource.fluid(); + + final IClientFluidTypeExtensions renderProperties = IClientFluidTypeExtensions.of(fluid); + + final int packedRgb = renderProperties.getTintColor(stack); + final TextureAtlasSprite sprite = getStillFluidSprite(renderProperties, stack); + + render(poseStack, renderTypeBuffer, light, packedRgb, sprite); + } + @Override public Component getDisplayName(final FluidResource fluidResource) { return fluidResource.fluid().getFluidType().getDescription(); diff --git a/refinedstorage2-platform-forge/src/main/resources/assets/refinedstorage2/textures/slot/curios.png b/refinedstorage2-platform-forge/src/main/resources/assets/refinedstorage2/textures/slot/curios.png index 90fb5ee2eb92322229c786daabac7a9df8483bd7..e48e77d76e78650f34caaa5a2dbaac6061ebb668 100644 GIT binary patch delta 192 zcmV;x06+hQ0)YaMNq@os01m?r3`KR>puu;3jdoS+vI)O%4LMa7ej0X)xLI_~3rO^c@xXn4Y z6a-`Vnw|U|TB4jYP`9CKfWh3zJ@8pXH362vjoc$#kZB-+F*$rqca7R(d6H6Unuxcc ui6)(J&|s#xG&g*vRT=#F$bY|4#+Vbt;AiHq<4^kl00007#FJ-i_uz>P_0Av6RODZT43=ohSWIb5D08)evL#0sw z&M Date: Mon, 30 Oct 2023 20:11:00 +0100 Subject: [PATCH 10/11] fix: prevent out of bounds crashes in grid Prefer using GridResource instances instead of an integer value that can change after checking. --- CHANGELOG.md | 4 ++ .../jei/GridGuiContainerHandler.java | 2 +- .../screen/grid/AbstractGridScreen.java | 45 +++++++++++-------- .../rei/GridFocusedStackProvider.java | 2 +- .../rei/GridFocusedStackProvider.java | 2 +- 5 files changed, 34 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 584a35d3c..ed7f65922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - You can now recharge the Controller in item form. +### Fixed + +- Fixed a random Grid crash. + ### Removed - The `useEnergy` config option for the Wireless Grid. If you do not wish to use energy, use the diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/integration/recipemod/jei/GridGuiContainerHandler.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/integration/recipemod/jei/GridGuiContainerHandler.java index ecd820b43..2cf862cb3 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/integration/recipemod/jei/GridGuiContainerHandler.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/integration/recipemod/jei/GridGuiContainerHandler.java @@ -27,7 +27,7 @@ public Optional> getClickableIngredientUnderMouse( final double mouseX, final double mouseY ) { - final GridResource resource = screen.getHoveredGridResource(); + final GridResource resource = screen.getCurrentGridResource(); if (resource == null) { return Optional.empty(); } diff --git a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/AbstractGridScreen.java b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/AbstractGridScreen.java index b85597730..6b295bda9 100644 --- a/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/AbstractGridScreen.java +++ b/refinedstorage2-platform-common/src/main/java/com/refinedmods/refinedstorage2/platform/common/screen/grid/AbstractGridScreen.java @@ -67,7 +67,7 @@ public abstract class AbstractGridScreen ex private ScrollbarWidget scrollbar; private int totalRows; private int visibleRows; - private int gridSlotNumber; + private int currentGridSlotIndex; protected AbstractGridScreen(final T menu, final Inventory playerInventory, @@ -207,7 +207,7 @@ protected void renderBg(final GuiGraphics graphics, final float delta, final int graphics.blit(getTexture(), x, y + TOP_HEIGHT + (18 * visibleRows), 0, 73, imageWidth - 34, bottomHeight); - gridSlotNumber = -1; + currentGridSlotIndex = -1; graphics.enableScissor(x + 7, y + TOP_HEIGHT, x + 7 + (18 * COLUMNS), y + TOP_HEIGHT + (visibleRows * 18)); for (int row = 0; row < Math.max(totalRows, visibleRows); ++row) { @@ -284,7 +284,7 @@ private void renderSlot(final GuiGraphics graphics, if (inBounds && isOverStorageArea(mouseX, mouseY)) { renderSelection(graphics, slotX, slotY); if (resource != null) { - gridSlotNumber = idx; + currentGridSlotIndex = idx; } } } @@ -343,8 +343,9 @@ protected void renderTooltip(final GuiGraphics graphics, final int x, final int } private void renderOverStorageAreaTooltip(final GuiGraphics graphics, final int x, final int y) { - if (gridSlotNumber != -1) { - renderHoveredResourceTooltip(graphics, x, y); + final GridResource resource = getCurrentGridResource(); + if (resource != null) { + renderHoveredResourceTooltip(graphics, x, y, resource); return; } final ItemStack carried = getMenu().getCarried(); @@ -355,13 +356,14 @@ private void renderOverStorageAreaTooltip(final GuiGraphics graphics, final int Platform.INSTANCE.renderTooltip(graphics, hints, x, y); } - private void renderHoveredResourceTooltip(final GuiGraphics graphics, final int mouseX, final int mouseY) { - final GridView view = getMenu().getView(); - final GridResource resource = view.getViewList().get(gridSlotNumber); + private void renderHoveredResourceTooltip(final GuiGraphics graphics, + final int mouseX, + final int mouseY, + final GridResource resource) { if (!(resource instanceof PlatformGridResource platformResource)) { return; } - renderHoveredResourceTooltip(graphics, mouseX, mouseY, view, platformResource); + renderHoveredResourceTooltip(graphics, mouseX, mouseY, getMenu().getView(), platformResource); } private void renderHoveredResourceTooltip(final GuiGraphics graphics, @@ -428,11 +430,15 @@ private boolean isModifiedJustNow(final LastModified lastModified) { @Nullable - public GridResource getHoveredGridResource() { - if (this.gridSlotNumber == -1) { + public GridResource getCurrentGridResource() { + if (currentGridSlotIndex < 0) { return null; } - return menu.getView().getViewList().get(this.gridSlotNumber); + final List viewList = menu.getView().getViewList(); + if (currentGridSlotIndex >= viewList.size()) { + return null; + } + return viewList.get(currentGridSlotIndex); } @Override @@ -453,9 +459,10 @@ public boolean mouseClicked(final double mouseX, final double mouseY, final int } final ItemStack carriedStack = getMenu().getCarried(); + final GridResource resource = getCurrentGridResource(); - if (!getMenu().getView().getViewList().isEmpty() && gridSlotNumber >= 0 && carriedStack.isEmpty()) { - mouseClickedInGrid(clickedButton, getMenu().getView().getViewList().get(gridSlotNumber)); + if (resource != null && carriedStack.isEmpty()) { + mouseClickedInGrid(clickedButton, resource); return true; } @@ -514,8 +521,11 @@ public boolean mouseReleased(final double mx, final double my, final int button) public boolean mouseScrolled(final double x, final double y, final double delta) { final boolean up = delta > 0; - if (isOverStorageArea((int) x, (int) y) && gridSlotNumber >= 0) { - mouseScrolledInGrid(up); + if (isOverStorageArea((int) x, (int) y)) { + final GridResource resource = getCurrentGridResource(); + if (resource != null) { + mouseScrolledInGrid(up, resource); + } } else if (hoveredSlot != null && hoveredSlot.hasItem() && !(hoveredSlot instanceof DisabledSlot)) { mouseScrolledInInventory(up, hoveredSlot); } @@ -544,13 +554,12 @@ private void mouseScrolledInInventory(final boolean up, final ItemStack stack, f ); } - private void mouseScrolledInGrid(final boolean up) { + private void mouseScrolledInGrid(final boolean up, final GridResource resource) { getMenu().getView().setPreventSorting(true); final GridScrollMode scrollMode = getScrollModeWhenScrollingOnGridArea(up); if (scrollMode == null) { return; } - final GridResource resource = getMenu().getView().getViewList().get(gridSlotNumber); if (!(resource instanceof PlatformGridResource platformGridResource)) { return; } diff --git a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/GridFocusedStackProvider.java b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/GridFocusedStackProvider.java index 05dcca8c0..d58b0ec7c 100644 --- a/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/GridFocusedStackProvider.java +++ b/refinedstorage2-platform-fabric/src/main/java/com/refinedmods/refinedstorage2/platform/fabric/integration/recipemod/rei/GridFocusedStackProvider.java @@ -22,7 +22,7 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractGridScreen gridScreen)) { return CompoundEventResult.pass(); } - final GridResource resource = gridScreen.getHoveredGridResource(); + final GridResource resource = gridScreen.getCurrentGridResource(); if (resource == null) { return CompoundEventResult.pass(); } diff --git a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/GridFocusedStackProvider.java b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/GridFocusedStackProvider.java index 45bd62fbb..660d56625 100644 --- a/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/GridFocusedStackProvider.java +++ b/refinedstorage2-platform-forge/src/main/java/com/refinedmods/refinedstorage2/platform/forge/integration/recipemod/rei/GridFocusedStackProvider.java @@ -22,7 +22,7 @@ public CompoundEventResult> provide(final Screen screen, final Poi if (!(screen instanceof AbstractGridScreen gridScreen)) { return CompoundEventResult.pass(); } - final GridResource resource = gridScreen.getHoveredGridResource(); + final GridResource resource = gridScreen.getCurrentGridResource(); if (resource == null) { return CompoundEventResult.pass(); } From f0ad4d0115b372dad1fb0136f8fd5f67f4bdbff8 Mon Sep 17 00:00:00 2001 From: raoulvdberge Date: Mon, 30 Oct 2023 19:28:03 +0000 Subject: [PATCH 11/11] chore: prepare release v2.0.0-milestone.3.1 --- CHANGELOG.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed7f65922..e8b229e26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [2.0.0-milestone.3.1] - 2023-10-30 + ### Added - "Open Wireless Grid" keybinding. @@ -475,7 +477,9 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - The Grid can now use smooth scrolling. - The Grid now has syntax highlighting for the search query. -[Unreleased]: https://github.com/refinedmods/refinedstorage2/compare/v2.0.0-milestone.3.0...HEAD +[Unreleased]: https://github.com/refinedmods/refinedstorage2/compare/v2.0.0-milestone.3.1...HEAD + +[2.0.0-milestone.3.1]: https://github.com/refinedmods/refinedstorage2/compare/v2.0.0-milestone.3.0...v2.0.0-milestone.3.1 [2.0.0-milestone.3.0]: https://github.com/refinedmods/refinedstorage2/compare/v2.0.0-milestone.2.14...v2.0.0-milestone.3.0