Compare commits

..

1 Commits

Author SHA1 Message Date
Salomão 76ae078d24 push patterns in round-robin 2021-04-29 21:19:07 -03:00
44 changed files with 1468 additions and 1869 deletions
-47
View File
@@ -1,47 +0,0 @@
Changes so far :
Design changes/breakages:
- Interfaces no longer spill items of one pattern on other faces
- Interfaces now push patterns in round-robin (Interfaces, then sides)
Fixes:
- Fix gregtech machines appearing with 'unnamed' or 'draconium lens' on the interface terminal on specific situations.
- Add memorycard support for fluid interfaces, import/export/storage busses and level emitters ( this fix was upstreamed to AE2 for MC 1.16)
- Storage busses now hide/show inaccessible items as configured.
- Exclusive Blocking mode for GTCE ( shapes, molds and configured circuits do not block GTCE machines )
- Blocking modes default to block on any item in the iventory the entity exposes
- Fuzzy includes items that report that they're damageable, but report a maxDamage of 0 ( auto-crafting of basic capacitors -> resonant capacitors is now possible ) <- Broken item implementation.
Performance:
- Added @talchas fixes for insane channelless AE networks.
- Implemented StorageDrawers slotless itemrepository.
- Removed CraftedEvent calls (really bad lag with craftweaker versions before CraftTweaker2-1.12-4.1.20.626)
- Count items set in interfaces before queuing crafting for them needlessly
- Backported b7ca98d ( Avoid copying items on simulated item extraction )
- Cache some level emitters functions
QOL:
- added highlight interface button to interface terminal ("?" button on the left of the interface slots)
- Added bar on the interface terminal that search by inputs ( The one on the LEFT, also searchs by interface name )
- Shortcut to molecular assemblers with free slots on the terminal interface by @Theisyat
- Toggle button on interface terminal to hide full interfaces
- JEI "U""R" and "A" (Usages/Recipes/Bookmark) now work on the Crafting Status GUI. ( the one that shows the total items to craft, and whats missing)
- Patterns can now be made with items currently showing on JEI. ( This is overriden by Just Enough Energistics. )
- Added multiplier buttons to processing pattern gui
- Switched crafting terminal JEI search to fuzzy mode. If the recipe uses a damageable item, AE will try to grab it ( damaged tools )
- Encoded patterns stack up to 64 ( holding shift and clicking the encode arrow will transfer the encoded pattern to the player inventory)
- Encoded patterns can be draggred on the interface terminal.
- Storage Monitor and Conversion Monitor now also ccepts fluids
- Draggable JEI ghost items (also works on bookmarked items. SHIFT + Click will move the hovered item into the first free target slot)
-JEI auto switches between crafting and processing patterns
HOTKEYS:
- Implemented mousetweaks API. AE2 custom keybinds now work. (Try right clicking and use the scroll-wheel on the terminals)
- Holding SHIFT and scrolling UP and DOWN will increase the items set on the configured slots of Interfaces and Pattern Terminal (Processing mode)
+10 -6
View File
@@ -19,6 +19,11 @@
repositories { repositories {
mavenLocal() mavenLocal()
maven {
name = "storagedrawers"
url = "https://dl.bintray.com/jaquadro/dev/"
}
maven { maven {
name "Mobius" name "Mobius"
url "http://mobiusstrip.eu/maven" url "http://mobiusstrip.eu/maven"
@@ -34,11 +39,6 @@ repositories {
url "http://maven.mcmoddev.com" url "http://maven.mcmoddev.com"
} }
maven {
name "Ellpeck"
url "https://maven.ellpeck.de"
}
maven { maven {
name = "IC2 repo" name = "IC2 repo"
url = "http://maven.ic2.player.to" url = "http://maven.ic2.player.to"
@@ -59,6 +59,11 @@ repositories {
url "http://maven.k-4u.nl/" url "http://maven.k-4u.nl/"
} }
maven { // Hwyla
name 'tehnut'
url "http://tehnut.info/maven"
}
maven { // CraftTweaker maven { // CraftTweaker
name 'jared maven' name 'jared maven'
url "http://maven.blamejared.com/" url "http://maven.blamejared.com/"
@@ -97,7 +102,6 @@ dependencies {
compileOnly "CraftTweaker2:CraftTweaker2-API:${crafttweaker_version}" compileOnly "CraftTweaker2:CraftTweaker2-API:${crafttweaker_version}"
compileOnly "inventory-tweaks:InventoryTweaks:${inventorytweaks_version}:api" compileOnly "inventory-tweaks:InventoryTweaks:${inventorytweaks_version}:api"
compileOnly "team.chisel.ctm:CTM:${ctm_version}" compileOnly "team.chisel.ctm:CTM:${ctm_version}"
compileOnly "de.ellpeck.actuallyadditions:ActuallyAdditions:1.12.2-r152.16:api"
// at runtime, use the full JEI jar // at runtime, use the full JEI jar
runtime "mezz.jei:jei_${minecraft_version}:${jei_version}" runtime "mezz.jei:jei_${minecraft_version}:${jei_version}"
@@ -112,13 +112,4 @@ public interface IAEItemStack extends IAEStack<IAEItemStack>
* @return definition stack * @return definition stack
*/ */
ItemStack getDefinition(); ItemStack getDefinition();
/**
* Compare this AE item stack to another item stack, but ignores
* the amount. It checks the item type, NBT and damage values.
*
* @param is An item stack
*/
boolean equals(ItemStack is);
} }
@@ -25,7 +25,6 @@ import java.util.*;
import appeng.api.config.ActionItems; import appeng.api.config.ActionItems;
import appeng.api.config.Settings; import appeng.api.config.Settings;
import appeng.client.gui.widgets.GuiImgButton; import appeng.client.gui.widgets.GuiImgButton;
import appeng.core.worlddata.IWorldPlayerMapping;
import appeng.util.BlockPosUtils; import appeng.util.BlockPosUtils;
import com.google.common.collect.HashMultimap; import com.google.common.collect.HashMultimap;
@@ -50,7 +49,6 @@ import appeng.util.Platform;
import net.minecraft.nbt.NBTUtil; import net.minecraft.nbt.NBTUtil;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.DimensionManager;
import org.lwjgl.input.Mouse; import org.lwjgl.input.Mouse;
@@ -81,7 +79,6 @@ public class GuiInterfaceTerminal extends AEBaseGui
private PartInterfaceTerminal partInterfaceTerminal; private PartInterfaceTerminal partInterfaceTerminal;
private GuiButton guiButtonHide; private GuiButton guiButtonHide;
private GuiButton guiButtonNextAssembler; private GuiButton guiButtonNextAssembler;
private HashMap<ClientDCInternalInv,Integer> dimHashMap = new HashMap<>();
public GuiInterfaceTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te ) public GuiInterfaceTerminal( final InventoryPlayer inventoryPlayer, final PartInterfaceTerminal te )
{ {
@@ -220,17 +217,9 @@ public class GuiInterfaceTerminal extends AEBaseGui
{ {
BlockPos blockPos = blockPosHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); BlockPos blockPos = blockPosHashMap.get( guiButtonHashMap.get( this.selectedButton ) );
BlockPos blockPos2 = mc.player.getPosition(); BlockPos blockPos2 = mc.player.getPosition();
int playerDim = mc.world.provider.getDimension(); int dimension = mc.world.provider.getDimension();
int interfaceDim = dimHashMap.get( guiButtonHashMap.get( this.selectedButton ) ); hilightBlock( blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance(blockPos, blockPos2), dimension );
if( playerDim != interfaceDim ) mc.player.sendStatusMessage( new TextComponentString( "The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ() ), false );
{
mc.player.sendStatusMessage( new TextComponentString( "Interface located at dimension: " + interfaceDim + " [" + DimensionManager.getWorld( interfaceDim ).provider.getDimensionType().getName() + "] and cant be highlighted" ), false );
}
else
{
hilightBlock( blockPos, System.currentTimeMillis() + 500 * BlockPosUtils.getDistance( blockPos, blockPos2 ), playerDim );
mc.player.sendStatusMessage( new TextComponentString( "The interface is now highlighted at " + "X: " + blockPos.getX() + " Y: " + blockPos.getY() + " Z: " + blockPos.getZ() ), false );
}
mc.player.closeScreen(); mc.player.closeScreen();
} }
@@ -336,7 +325,6 @@ public class GuiInterfaceTerminal extends AEBaseGui
final NBTTagCompound invData = in.getCompoundTag( key ); final NBTTagCompound invData = in.getCompoundTag( key );
final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) ); final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) );
blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" )) ); blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" )) );
dimHashMap.put( current, invData.getInteger( "dim" ));
for( int x = 0; x < current.getInventory().getSlots(); x++ ) for( int x = 0; x < current.getInventory().getSlots(); x++ )
{ {
@@ -159,58 +159,56 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH
@Override @Override
public void detectAndSendChanges() public void detectAndSendChanges()
{ {
if( Platform.isServer() && this.getMonitor() != null ) if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() )
{ {
if( this.getEstimatedTime() >= 0 ) try
{ {
final long elapsedTime = this.getMonitor().getElapsedTime(); if( this.getEstimatedTime() >= 0 )
final double remainingItems = this.getMonitor().getRemainingItemCount();
final double startItems = this.getMonitor().getStartItemCount();
final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems );
this.setEstimatedTime( eta );
}
if( !this.list.isEmpty() )
{
try
{ {
final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 ); final long elapsedTime = this.getMonitor().getElapsedTime();
final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 ); final double remainingItems = this.getMonitor().getRemainingItemCount();
final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 ); final double startItems = this.getMonitor().getStartItemCount();
final long eta = (long) ( elapsedTime / Math.max( 1d, ( startItems - remainingItems ) ) * remainingItems );
this.setEstimatedTime( eta );
}
for( final IAEItemStack out : this.list ) final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 );
final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 );
final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 );
for( final IAEItemStack out : this.list )
{
a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) );
b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) );
c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) );
}
this.list.resetStatus();
for( final Object g : this.listeners )
{
if( g instanceof EntityPlayer )
{ {
a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) ); if( !a.isEmpty() )
b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) );
c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) );
}
this.list.resetStatus();
for( final Object g : this.listeners )
{
if( g instanceof EntityPlayer )
{ {
if( !a.isEmpty() ) NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g );
{ }
NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g );
}
if( !b.isEmpty() ) if( !b.isEmpty() )
{ {
NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g ); NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g );
} }
if( !c.isEmpty() ) if( !c.isEmpty() )
{ {
NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g ); NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g );
}
} }
} }
} }
catch( final IOException e ) }
{ catch( final IOException e )
// :P {
} // :P
} }
} }
super.detectAndSendChanges(); super.detectAndSendChanges();
@@ -403,8 +403,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
{ {
tag.setLong( "sortBy", inv.sortBy ); tag.setLong( "sortBy", inv.sortBy );
tag.setString( "un", inv.unlocalizedName ); tag.setString( "un", inv.unlocalizedName );
tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) ); tag.setTag("pos", NBTUtil.createPosTag( inv.pos ) );
tag.setInteger( "dim", inv.dim );
} }
for( int x = 0; x < length; x++ ) for( int x = 0; x < length; x++ )
@@ -436,7 +435,6 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
private final IItemHandler client; private final IItemHandler client;
private final IItemHandler server; private final IItemHandler server;
private final BlockPos pos; private final BlockPos pos;
private final int dim;
public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName ) public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName )
{ {
@@ -445,7 +443,6 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
this.unlocalizedName = unlocalizedName; this.unlocalizedName = unlocalizedName;
this.sortBy = dual.getSortValue(); this.sortBy = dual.getSortValue();
this.pos = dual.getLocation().getPos(); this.pos = dual.getLocation().getPos();
this.dim = dual.getLocation().getWorld().provider.getDimension();
} }
} }
@@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import appeng.container.slot.*;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
@@ -52,6 +51,12 @@ import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.container.ContainerNull; import appeng.container.ContainerNull;
import appeng.container.guisync.GuiSync; import appeng.container.guisync.GuiSync;
import appeng.container.slot.IOptionalSlotHost;
import appeng.container.slot.OptionalSlotFake;
import appeng.container.slot.SlotFakeCraftingMatrix;
import appeng.container.slot.SlotPatternOutputs;
import appeng.container.slot.SlotPatternTerm;
import appeng.container.slot.SlotRestrictedInput;
import appeng.core.sync.packets.PacketPatternSlot; import appeng.core.sync.packets.PacketPatternSlot;
import appeng.helpers.IContainerCraftingPacket; import appeng.helpers.IContainerCraftingPacket;
import appeng.items.storage.ItemViewCell; import appeng.items.storage.ItemViewCell;
@@ -127,28 +132,6 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA
this.updateOrderOfOutputSlots(); this.updateOrderOfOutputSlots();
} }
@Override
public ItemStack transferStackInSlot( final EntityPlayer p, final int idx )
{
if( Platform.isClient() )
{
return ItemStack.EMPTY;
}
if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar )
{
final AppEngSlot clickSlot = ( AppEngSlot ) this.inventorySlots.get( idx ); // require AE SLots!
ItemStack itemStack = clickSlot.getStack();
if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) )
{
IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" );
ItemStack remainder = patternInv.insertItem( 0, itemStack, false );
clickSlot.putStack( remainder );
}
}
return super.transferStackInSlot( p, idx );
}
private void updateOrderOfOutputSlots() private void updateOrderOfOutputSlots()
{ {
if( !this.isCraftingMode() ) if( !this.isCraftingMode() )
@@ -164,6 +164,7 @@ public enum AEFeature
PATTERNS( "Patterns", Constants.CATEGORY_CRAFTING_FEATURES ), PATTERNS( "Patterns", Constants.CATEGORY_CRAFTING_FEATURES ),
CRAFTING_CPU( "CraftingCPU", Constants.CATEGORY_CRAFTING_FEATURES ), CRAFTING_CPU( "CraftingCPU", Constants.CATEGORY_CRAFTING_FEATURES ),
CRAFTING_MANAGER_FALLBACK( "CraftingManagerFallback", Constants.CATEGORY_CRAFTING_FEATURES, "Use CraftingManager to find an alternative recipe, after a pattern rejected an ingredient. Should be enabled to avoid issues, but can have a minor performance impact." ), CRAFTING_MANAGER_FALLBACK( "CraftingManagerFallback", Constants.CATEGORY_CRAFTING_FEATURES, "Use CraftingManager to find an alternative recipe, after a pattern rejected an ingredient. Should be enabled to avoid issues, but can have a minor performance impact." ),
INSANE_BLOCKING_MODE( "InsaneBlockingMode", Constants.CATEGORY_CRAFTING_FEATURES, "Use the default AE2 blocking mode that doesn't work on any machines" ),
BASIC_CARDS( "BasicCards", Constants.CATEGORY_UPGRADES ), BASIC_CARDS( "BasicCards", Constants.CATEGORY_UPGRADES ),
ADVANCED_CARDS( "AdvancedCards", Constants.CATEGORY_UPGRADES ), ADVANCED_CARDS( "AdvancedCards", Constants.CATEGORY_UPGRADES ),
@@ -20,7 +20,6 @@ package appeng.core.sync.packets;
import java.io.IOException; import java.io.IOException;
import java.util.Collections;
import appeng.api.storage.data.IAEFluidStack; import appeng.api.storage.data.IAEFluidStack;
import appeng.container.slot.IJEITargetSlot; import appeng.container.slot.IJEITargetSlot;
@@ -225,9 +224,7 @@ public class PacketInventoryAction extends AppEngPacket
IAEFluidStack aefs = AEFluidStack.fromNBT( this.slotItem.getDefinition().getTagCompound() ); IAEFluidStack aefs = AEFluidStack.fromNBT( this.slotItem.getDefinition().getTagCompound() );
if( aefs != null ) if( aefs != null )
{ {
aefs.setStackSize( 1000 );
( (ContainerFluidConfigurable) sender.openContainer ).getFluidConfigInventory().setFluidInSlot( this.slot, aefs ); ( (ContainerFluidConfigurable) sender.openContainer ).getFluidConfigInventory().setFluidInSlot( this.slot, aefs );
NetworkHandler.instance().sendToServer( new PacketFluidSlot( Collections.singletonMap( this.slot, aefs ) ) );
} }
} }
} }
@@ -215,7 +215,7 @@ public class PacketJEIRecipe extends AppEngPacket
IAEItemStack mostDamaged = null; IAEItemStack mostDamaged = null;
for( IAEItemStack is : outList ) for( IAEItemStack is : outList )
{ {
if( !is.isCraftable() ) if( !is.isCraftable() && is.getItem().isDamageable() )
{ {
if( mostDamaged == null || mostDamaged.getItemDamage() < is.getItemDamage() ) if( mostDamaged == null || mostDamaged.getItemDamage() < is.getItemDamage() )
{ {
@@ -285,7 +285,6 @@ public class PacketJEIRecipe extends AppEngPacket
IItemHandler outputSlots = cct.getInventoryByName( "output" ); IItemHandler outputSlots = cct.getInventoryByName( "output" );
for( int i = 0; i < this.output.length; ++i ) for( int i = 0; i < this.output.length; ++i )
{ {
if( this.output[i] == null ) continue;
ItemHandlerUtil.setStackInSlot( outputSlots, i, this.output[i] ); ItemHandlerUtil.setStackInSlot( outputSlots, i, this.output[i] );
} }
} }
@@ -28,9 +28,7 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.me.helpers.PlayerSource;
import appeng.util.inv.ItemListIgnoreCrafting; import appeng.util.inv.ItemListIgnoreCrafting;
import net.minecraft.util.text.TextComponentString;
public class MECraftingInventory implements IMEInventory<IAEItemStack> public class MECraftingInventory implements IMEInventory<IAEItemStack>
@@ -309,15 +307,8 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
if( result == null || result.getStackSize() != extra.getStackSize() ) if( result == null || result.getStackSize() != extra.getStackSize() )
{ {
if( src.player().isPresent() )
{
if( result == null )
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getDisplayName() + " available but could not extract anything" ), false );
else
src.player().get().sendStatusMessage( new TextComponentString( "System reported " + extra.getStackSize() + " " + extra.getDefinition().getDisplayName() + " available but could only extract " + result.getStackSize() ), false );
}
failed = true; failed = true;
if( !src.player().isPresent() ) break; break;
} }
} }
} }
@@ -264,20 +264,19 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
@Override @Override
public void postChange( final IBaseMonitor<IAEFluidStack> monitor, final Iterable<IAEFluidStack> change, final IActionSource source ) public void postChange( final IBaseMonitor<IAEFluidStack> monitor, final Iterable<IAEFluidStack> change, final IActionSource source )
{ {
if( source == this.source || source.machine().map( machine -> machine == this ).orElse( false ) ) try
{ {
try if( this.getProxy().isActive() )
{ {
if( this.getProxy().isActive() ) this.getProxy()
{ .getStorage()
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source ); .postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
}
catch( final GridAccessException e )
{
// :(
} }
} }
catch( final GridAccessException e )
{
// :(
}
} }
public MEInventoryHandler<IAEFluidStack> getInternalHandler() public MEInventoryHandler<IAEFluidStack> getInternalHandler()
@@ -19,22 +19,22 @@
package appeng.helpers; package appeng.helpers;
import java.util.*; import java.util.ArrayList;
import java.util.stream.Collectors; import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.integration.modules.gregtech.GTCEInventoryAdaptor; import appeng.integration.modules.gregtech.GTCEInventoryAdaptor;
import appeng.util.*; import appeng.util.*;
import appeng.util.inv.*;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import de.ellpeck.actuallyadditions.api.tile.IPhantomTile;
import gregtech.api.block.machines.BlockMachine; import gregtech.api.block.machines.BlockMachine;
import gregtech.api.metatileentity.MetaTileEntity; import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.metatileentity.MetaTileEntityHolder;
import gregtech.api.metatileentity.TieredMetaTileEntity;
import gregtech.api.metatileentity.WorkableTieredMetaTileEntity;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Items; import net.minecraft.init.Items;
@@ -93,6 +93,8 @@ import appeng.api.util.AEPartLocation;
import appeng.api.util.DimensionalCoord; import appeng.api.util.DimensionalCoord;
import appeng.api.util.IConfigManager; import appeng.api.util.IConfigManager;
import appeng.capabilities.Capabilities; import appeng.capabilities.Capabilities;
import appeng.core.AEConfig;
import appeng.core.features.AEFeature;
import appeng.core.settings.TickRates; import appeng.core.settings.TickRates;
import appeng.me.GridAccessException; import appeng.me.GridAccessException;
import appeng.me.helpers.AENetworkProxy; import appeng.me.helpers.AENetworkProxy;
@@ -104,6 +106,10 @@ import appeng.parts.automation.StackUpgradeInventory;
import appeng.parts.automation.UpgradeInventory; import appeng.parts.automation.UpgradeInventory;
import appeng.tile.inventory.AppEngInternalAEInventory; import appeng.tile.inventory.AppEngInternalAEInventory;
import appeng.tile.inventory.AppEngInternalInventory; import appeng.tile.inventory.AppEngInternalInventory;
import appeng.util.inv.AdaptorItemHandler;
import appeng.util.inv.IAEAppEngInventory;
import appeng.util.inv.IInventoryDestination;
import appeng.util.inv.InvOperation;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import static gregtech.api.block.machines.BlockMachine.getMetaTileEntity; import static gregtech.api.block.machines.BlockMachine.getMetaTileEntity;
@@ -142,9 +148,8 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
private IMEInventory<IAEItemStack> destination; private IMEInventory<IAEItemStack> destination;
private int isWorking = -1; private int isWorking = -1;
private final Accessor accessor = new Accessor(); private final Accessor accessor = new Accessor();
private EnumSet<EnumFacing> visitedFaces = EnumSet.noneOf( EnumFacing.class );
private EnumMap<EnumFacing,List<ItemStack>> waitingToSendFacing = new EnumMap<>(EnumFacing.class);
private GTCEInventoryAdaptor GTad; private GTCEInventoryAdaptor GTad;
EnumSet<EnumFacing> visitedFaces = EnumSet.noneOf( EnumFacing.class );
public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih ) public DualityInterface( final AENetworkProxy networkProxy, final IInterfaceHost ih )
{ {
@@ -238,27 +243,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
data.setTag( "waitingToSend", waitingToSend ); data.setTag( "waitingToSend", waitingToSend );
NBTTagCompound sidedWaitList = new NBTTagCompound();
if (this.waitingToSendFacing != null)
{
for( EnumFacing s : this.iHost.getTargets() )
{
NBTTagList waitingListSided = new NBTTagList();
if (this.waitingToSendFacing.containsKey( s ))
{
for( final ItemStack is : this.waitingToSendFacing.get( s ) )
{
final NBTTagCompound item = new NBTTagCompound();
is.writeToNBT( item );
waitingListSided.appendTag( item );
}
sidedWaitList.setTag( s.name(), waitingListSided );
}
}
}
data.setTag( "sidedWaitList", sidedWaitList );
} }
public void readFromNBT( final NBTTagCompound data ) public void readFromNBT( final NBTTagCompound data )
@@ -278,23 +262,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
this.waitingToSendFacing = null;
final NBTTagCompound waitingListSided = data.getCompoundTag("sidedWaitList");
for (EnumFacing s : EnumFacing.values())
if (waitingListSided.hasKey( s.name() )) {
NBTTagList w = waitingListSided.getTagList( s.name(), 10 );
for( int x = 0; x < w.tagCount(); x++ )
{
final NBTTagCompound c = w.getCompoundTagAt( x );
if( c != null )
{
final ItemStack is = new ItemStack( c );
this.addToSendListFacing( is , EnumFacing.getFront( s.getIndex() ) );
}
}
}
this.craftingTracker.readFromNBT( data ); this.craftingTracker.readFromNBT( data );
this.upgrades.readFromNBT( data, "upgrades" ); this.upgrades.readFromNBT( data, "upgrades" );
this.config.readFromNBT( data, "config" ); this.config.readFromNBT( data, "config" );
@@ -330,30 +297,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
private void addToSendListFacing( final ItemStack is, EnumFacing f )
{
if( is.isEmpty() )
{
return;
}
if (this.waitingToSendFacing == null){
this.waitingToSendFacing = new EnumMap<>(EnumFacing.class);
}
this.waitingToSendFacing.computeIfAbsent( f, k -> new ArrayList<>() );
this.waitingToSendFacing.get( f ).add( is );
try
{
this.gridProxy.getTick().wakeDevice( this.gridProxy.getNode() );
}
catch( final GridAccessException e )
{
// :P
}
}
private void readConfig() private void readConfig()
{ {
this.hasConfig = false; this.hasConfig = false;
@@ -451,22 +394,24 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
private boolean hasWorkToDo() { private boolean hasWorkToDo()
{
if (hasItemsToSend()){ if( this.hasItemsToSend() )
{
return true; return true;
} }
else
if(hasItemsToSendFacing()){ {
return true; for( final IAEItemStack requiredWork : this.requireWork )
} {
if( requiredWork != null )
for (final IAEItemStack requiredWork : this.requireWork) { {
if (requiredWork != null) { return true;
return true; }
} }
return false;
} }
return false;
} }
private void updatePlan( final int slot ) private void updatePlan( final int slot )
@@ -571,21 +516,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return this.waitingToSend != null && !this.waitingToSend.isEmpty(); return this.waitingToSend != null && !this.waitingToSend.isEmpty();
} }
private boolean hasItemsToSendFacing()
{
if (waitingToSendFacing != null)
{
for( EnumFacing enumFacing : waitingToSendFacing.keySet() )
{
if( !waitingToSendFacing.get( enumFacing ).isEmpty() )
{
return true;
}
}
}
return false;
}
@Override @Override
public boolean canInsert( final ItemStack stack ) public boolean canInsert( final ItemStack stack )
{ {
@@ -657,21 +587,11 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return TickRateModulation.SLEEP; return TickRateModulation.SLEEP;
} }
//Previous version might have items saved in this list
//recover them
if( this.hasItemsToSend() ) if( this.hasItemsToSend() )
{ {
this.pushItemsOut( this.iHost.getTargets() ); this.pushItemsOut( this.iHost.getTargets() );
} }
if (hasItemsToSendFacing())
{
for( EnumFacing enumFacing : waitingToSendFacing.keySet() )
{
this.pushItemsOut( enumFacing );
}
}
final boolean couldDoWork = this.updateStorage(); final boolean couldDoWork = this.updateStorage();
return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP; return this.hasWorkToDo() ? ( couldDoWork ? TickRateModulation.URGENT : TickRateModulation.SLOWER ) : TickRateModulation.SLEEP;
} }
@@ -732,47 +652,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
private void pushItemsOut( final EnumFacing s )
{
if (!this.waitingToSendFacing.containsKey(s) ||
(this.waitingToSendFacing.containsKey(s) && this.waitingToSendFacing.get( s ).isEmpty())) {
return;
}
final TileEntity tile = this.iHost.getTileEntity();
final World w = tile.getWorld();
final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) );
if( te == null )
{
return;
}
final Iterator<ItemStack> i = this.waitingToSendFacing.get( s ).iterator();
while ( i.hasNext() )
{
ItemStack whatToSend = i.next();
final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() );
if( ad != null )
{
final ItemStack result = ad.addItems( whatToSend );
if( !result.isEmpty() )
{
whatToSend.setCount( whatToSend.getCount() - ( whatToSend.getCount() - result.getCount() ) );
}
else
{
i.remove();
}
}
}
if( this.waitingToSendFacing.get( s ).isEmpty() )
{
this.waitingToSendFacing.remove( s );
}
}
private boolean updateStorage() private boolean updateStorage()
{ {
boolean didSomething = false; boolean didSomething = false;
@@ -1035,9 +914,13 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}; };
} }
private boolean invIsBlocked( InventoryAdaptor inv ) private static boolean invIsBlocked( InventoryAdaptor inv )
{ {
return (inv.containsItems()); if( AEConfig.instance().isFeatureEnabled( AEFeature.INSANE_BLOCKING_MODE ) )
{
return !inv.simulateRemove( 1, ItemStack.EMPTY, null ).isEmpty();
}
else return inv.containsItems();
} }
private static boolean invIsBlockedGTCE( GTCEInventoryAdaptor inv ) private static boolean invIsBlockedGTCE( GTCEInventoryAdaptor inv )
@@ -1048,7 +931,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
@Override @Override
public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table ) public boolean pushPattern( final ICraftingPatternDetails patternDetails, final InventoryCrafting table )
{ {
if( this.hasItemsToSend() || this.hasItemsToSendFacing() || !this.gridProxy.isActive() || !this.craftingList.contains( patternDetails ) ) if( this.hasItemsToSend() || !this.gridProxy.isActive() || !this.craftingList.contains( patternDetails ) )
{ {
return false; return false;
} }
@@ -1056,13 +939,13 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
final TileEntity tile = this.iHost.getTileEntity(); final TileEntity tile = this.iHost.getTileEntity();
final World w = tile.getWorld(); final World w = tile.getWorld();
if( this.visitedFaces.isEmpty() ) final EnumSet<EnumFacing> possibleDirections = this.iHost.getTargets();
{
this.visitedFaces = this.iHost.getTargets();
}
for( final EnumFacing s : visitedFaces ) for( final EnumFacing s : possibleDirections )
{ {
if (visitedFaces.contains( s ))
continue;
final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) );
if( te instanceof IInterfaceHost ) if( te instanceof IInterfaceHost )
{ {
@@ -1070,7 +953,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
{ {
if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) ) if( ( (IInterfaceHost) te ).getInterfaceDuality().sameGrid( this.gridProxy.getGrid() ) )
{ {
visitedFaces.remove( s );
continue; continue;
} }
} }
@@ -1085,9 +967,9 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
final ICraftingMachine cm = (ICraftingMachine) te; final ICraftingMachine cm = (ICraftingMachine) te;
if( cm.acceptsPlans() ) if( cm.acceptsPlans() )
{ {
visitedFaces.remove( s );
if( cm.pushPattern( patternDetails, table, s.getOpposite() ) ) if( cm.pushPattern( patternDetails, table, s.getOpposite() ) )
{ {
visitedFaces.add( s );
return true; return true;
} }
continue; continue;
@@ -1099,67 +981,55 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
{ {
if( this.isBlocking() ) if( this.isBlocking() )
{ {
IPhantomTile phantomTE = null; if( te.getBlockType().getRegistryName().getResourceDomain().equals( "gregtech" ) )
if( Loader.isModLoaded( "actuallyadditions" ) && Loader.isModLoaded( "gregtech" ) && te instanceof IPhantomTile )
{ {
phantomTE = ( (IPhantomTile) te ); GTad = GTCEInventoryAdaptor.getAdaptor( te, s.getOpposite() );
if( phantomTE.hasBoundPosition() ) if( invIsBlockedGTCE( GTad ) )
{ {
TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() );
if( phantom instanceof MetaTileEntityHolder && isGTCEblocked( phantom, s ) )
{
visitedFaces.remove( s );
continue;
}
}
}
else if( Loader.isModLoaded( "gregtech" ) && te instanceof MetaTileEntityHolder )
{
if( isGTCEblocked( te, s ) )
{
visitedFaces.remove( s );
continue; continue;
} }
} }
else
else if( invIsBlocked( ad ) )
{ {
visitedFaces.remove( s ); if( invIsBlocked( ad ) )
continue; {
continue;
}
} }
} }
if( this.acceptsItems( ad, table ) ) if( this.acceptsItems( ad, table ) )
{ {
visitedFaces.remove( s );
for( int x = 0; x < table.getSizeInventory(); x++ ) for( int x = 0; x < table.getSizeInventory(); x++ )
{ {
final ItemStack is = table.getStackInSlot( x ); final ItemStack is = table.getStackInSlot( x );
if( !is.isEmpty() ) if( !is.isEmpty() )
{ {
addToSendListFacing( is, s ); final ItemStack added = ad.addItems( is );
this.addToSendList( added );
} }
} }
pushItemsOut( s ); this.pushItemsOut( possibleDirections );
visitedFaces.add( s );
return true; return true;
} }
} }
visitedFaces.remove( s );
} }
visitedFaces.clear();
return false; return false;
} }
@Override @Override
public boolean isBusy() public boolean isBusy()
{ {
boolean busy = false; if( this.hasItemsToSend() )
if( this.hasItemsToSend() || hasItemsToSendFacing() )
{ {
return true; return true;
} }
boolean busy = false;
if( this.isBlocking() ) if( this.isBlocking() )
{ {
final EnumSet<EnumFacing> possibleDirections = this.iHost.getTargets(); final EnumSet<EnumFacing> possibleDirections = this.iHost.getTargets();
@@ -1171,38 +1041,27 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
for( final EnumFacing s : possibleDirections ) for( final EnumFacing s : possibleDirections )
{ {
final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) ); final TileEntity te = w.getTileEntity( tile.getPos().offset( s ) );
IPhantomTile phantomTE = null;
final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() ); final InventoryAdaptor ad = InventoryAdaptor.getAdaptor( te, s.getOpposite() );
if( ad != null ) if( ad != null )
{ {
if( Loader.isModLoaded( "actuallyadditions") && Loader.isModLoaded( "gregtech" ) && te instanceof IPhantomTile ) if( te.getBlockType().getRegistryName().getResourceDomain().equals( "gregtech" ) )
{ {
phantomTE = ( (IPhantomTile) te ); GTad = GTCEInventoryAdaptor.getAdaptor( te, s.getOpposite() );
if( phantomTE.hasBoundPosition() ) if( !invIsBlockedGTCE( GTad ) )
{
TileEntity phantom = w.getTileEntity( phantomTE.getBoundPosition() );
if( phantom instanceof MetaTileEntityHolder && !isGTCEblocked( phantom, s ) )
{
allAreBusy = false;
break;
}
}
}
else if( Loader.isModLoaded( "gregtech" ) && te instanceof MetaTileEntityHolder )
{
if( !isGTCEblocked( te, s ) )
{ {
allAreBusy = false; allAreBusy = false;
break; break;
} }
} }
else
else if( !invIsBlocked( ad ) )
{ {
allAreBusy = false; if( !invIsBlocked( ad ) )
break; {
allAreBusy = false;
break;
}
} }
} }
} }
@@ -1211,12 +1070,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return busy; return busy;
} }
boolean isGTCEblocked(TileEntity te, EnumFacing s)
{
GTad = GTCEInventoryAdaptor.getAdaptor( te, s.getOpposite() );
return invIsBlockedGTCE( GTad );
}
private boolean sameGrid( final IGrid grid ) throws GridAccessException private boolean sameGrid( final IGrid grid ) throws GridAccessException
{ {
return grid == this.gridProxy.getGrid(); return grid == this.gridProxy.getGrid();
@@ -1272,20 +1125,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
} }
} }
if( this.waitingToSendFacing != null )
{
for (List<ItemStack> itemList : waitingToSendFacing.values())
{
for (final ItemStack is : itemList)
{
if (!is.isEmpty())
{
drops.add(is);
}
}
}
}
for( final ItemStack is : this.upgrades ) for( final ItemStack is : this.upgrades )
{ {
if( !is.isEmpty() ) if( !is.isEmpty() )
@@ -62,7 +62,6 @@ public class HighlighterHandler
tessellator.draw(); tessellator.draw();
GlStateManager.enableTexture2D(); GlStateManager.enableTexture2D();
GlStateManager.enableDepth();
GlStateManager.popMatrix(); GlStateManager.popMatrix();
} }
@@ -1,26 +1,26 @@
package appeng.integration.modules.gregtech; package appeng.integration.modules.gregtech;
import appeng.util.inv.ItemSlot; import appeng.util.inv.ItemSlot;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing;
import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
public abstract class GTCEInventoryAdaptor implements Iterable<ItemSlot> public abstract class GTCEInventoryAdaptor implements Iterable<ItemSlot>
{ {
public static GTCEInventoryAdaptor getAdaptor(final TileEntity te, final EnumFacing d) public static GTCEInventoryAdaptor getAdaptor(final TileEntity te, final EnumFacing d)
{ {
if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d)) if (te != null && te.hasCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d))
{ {
// Attempt getting an IItemHandler for the given side via caps // Attempt getting an IItemHandler for the given side via caps
IItemHandler itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d); IItemHandler itemHandler = te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, d);
if (itemHandler != null) if (itemHandler != null)
{ {
return new GTCEItemHandler(itemHandler); return new GTCEItemHandler(itemHandler);
} }
} }
return null; return null;
} }
public abstract boolean canRemoveAllExceptCircuits(); public abstract boolean canRemoveAllExceptCircuits();
} }
@@ -1,58 +1,57 @@
package appeng.integration.modules.gregtech; package appeng.integration.modules.gregtech;
import appeng.util.inv.ItemHandlerIterator; import appeng.util.inv.ItemSlot;
import appeng.util.inv.ItemSlot; import net.minecraft.item.Item;
import net.minecraft.item.Item; import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler;
import net.minecraftforge.items.IItemHandler;
import java.util.ArrayList;
import java.util.ArrayList; import java.util.Arrays;
import java.util.Arrays; import java.util.Iterator;
import java.util.Iterator;
public class GTCEItemHandler extends GTCEInventoryAdaptor
public class GTCEItemHandler extends GTCEInventoryAdaptor {
{ ArrayList<Integer> GTCElenses = new ArrayList<>(Arrays.asList(15085,15214,15092,15111,15113,15219,15218,15243,15244,15209,15117,15206,15216,15331,15212,15213,15154,15122,15157,15190,15247));
ArrayList<Integer> GTCElenses = new ArrayList<>(Arrays.asList(15085,15214,15092,15111,15113,15219,15218,15243,15244,15209,15117,15206,15216,15331,15212,15213,15154,15122,15157,15190,15247)); ArrayList<Integer> GTCEmolds = new ArrayList<>(Arrays.asList(32301,32303,32304,32305,32306,32307,32308,32309,32313,32314,32315,32317,32350,32351,32352,32353,32354,32355,32356,32358,32359,32360,32361,32363,32364,32365,32366,32367,32368,32369,32370,32371,32372,32373));
ArrayList<Integer> GTCEmolds = new ArrayList<>(Arrays.asList(32301,32303,32304,32305,32306,32307,32308,32309,32313,32314,32315,32317,32350,32351,32352,32353,32354,32355,32356,32358,32359,32360,32361,32363,32364,32365,32366,32367,32368,32369,32370,32371,32372,32373)); Item smallGearExtruderShape = Item.getByNameOrId("contenttweaker:smallgearextrudershape");
Item smallGearExtruderShape = Item.getByNameOrId("contenttweaker:smallgearextrudershape"); Item creativePortableTankMold = Item.getByNameOrId("contenttweaker:creativeportabletankmold");
Item creativePortableTankMold = Item.getByNameOrId("contenttweaker:creativeportabletankmold");
protected final IItemHandler itemHandler;
protected final IItemHandler itemHandler;
public GTCEItemHandler(IItemHandler itemHandler)
public GTCEItemHandler(IItemHandler itemHandler) {
{ this.itemHandler = itemHandler;
this.itemHandler = itemHandler; }
}
boolean isBlockableItem(ItemStack stack)
boolean isBlockableItem(ItemStack stack) {
{ if ( stack.getItem() == Item.getByNameOrId("gregtech:meta_item_1") ) {
if ( stack.getItem() == Item.getByNameOrId("gregtech:meta_item_1") ) { int metadata = stack.getItemDamage();
int metadata = stack.getItemDamage(); if ( metadata == 32766 || GTCElenses.contains(metadata) || GTCEmolds.contains(metadata)) {
if ( metadata == 32766 || GTCElenses.contains(metadata) || GTCEmolds.contains(metadata)) { return false;
return false; }
} }
} if ( stack.getItem() == smallGearExtruderShape ) return false;
if ( stack.getItem() == smallGearExtruderShape ) return false; if ( stack.getItem() == creativePortableTankMold) return false;
if ( stack.getItem() == creativePortableTankMold) return false; return true;
return true; }
}
@Override
@Override public boolean canRemoveAllExceptCircuits()
public boolean canRemoveAllExceptCircuits() {
{ int slots = this.itemHandler.getSlots();
int slots = this.itemHandler.getSlots(); for ( int slot = 0; slot < slots; slot++ ) {
for ( int slot = 0; slot < slots; slot++ ) { ItemStack is = this.itemHandler.getStackInSlot(slot);
ItemStack is = this.itemHandler.getStackInSlot(slot); if ( is.isEmpty() || !isBlockableItem(is) ) continue;
if ( is.isEmpty() || !isBlockableItem(is) ) continue;
return false;
return false; }
} return true;
return true; }
}
@Override
@Override public Iterator<ItemSlot> iterator()
public Iterator<ItemSlot> iterator() {
{ return null;
return new ItemHandlerIterator( this.itemHandler ); }
} }
}
@@ -27,7 +27,6 @@ import java.util.Map;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.container.implementations.ContainerPatternTerm; import appeng.container.implementations.ContainerPatternTerm;
import appeng.core.sync.packets.PacketValueConfig;
import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import mezz.jei.api.recipe.VanillaRecipeCategoryUid;
import mezz.jei.transfer.RecipeTransferErrorInternal; import mezz.jei.transfer.RecipeTransferErrorInternal;
import mezz.jei.transfer.RecipeTransferErrorTooltip; import mezz.jei.transfer.RecipeTransferErrorTooltip;
@@ -74,7 +73,24 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
{ {
final String recipeType = recipeLayout.getRecipeCategory().getUid(); final String recipeType = recipeLayout.getRecipeCategory().getUid();
if (recipeType.equals( VanillaRecipeCategoryUid.INFORMATION) || recipeType.equals(VanillaRecipeCategoryUid.FUEL)) if (!recipeType.equals( VanillaRecipeCategoryUid.INFORMATION) && !recipeType.equals(VanillaRecipeCategoryUid.FUEL))
{
if( container instanceof ContainerPatternTerm )
{
if( !( (ContainerPatternTerm) container ).isCraftingMode() )
{
if( recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) )
{
return new RecipeTransferErrorTooltip( I18n.format( "gui.appliedenergistics2.CraftingPattern" ) );
}
}
else if( !recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) )
{
return new RecipeTransferErrorTooltip( I18n.format( "gui.appliedenergistics2.ProcessingPattern" ) );
}
}
}
else
{ {
return RecipeTransferErrorInternal.INSTANCE; return RecipeTransferErrorInternal.INSTANCE;
} }
@@ -84,30 +100,6 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
return null; return null;
} }
if( container instanceof ContainerPatternTerm )
{
try
{
if( !( (ContainerPatternTerm) container ).isCraftingMode() )
{
if( recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) )
{
NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", "1" ) );
}
}
else if( !recipeType.equals( VanillaRecipeCategoryUid.CRAFTING ) )
{
NetworkHandler.instance().sendToServer( new PacketValueConfig( "PatternTerminal.CraftMode", "0" ) );
}
}
catch( IOException e )
{
e.printStackTrace();
}
}
Map<Integer, ? extends IGuiIngredient<ItemStack>> ingredients = recipeLayout.getItemStacks().getGuiIngredients(); Map<Integer, ? extends IGuiIngredient<ItemStack>> ingredients = recipeLayout.getItemStacks().getGuiIngredients();
final NBTTagCompound recipe = new NBTTagCompound(); final NBTTagCompound recipe = new NBTTagCompound();
+2 -2
View File
@@ -633,10 +633,10 @@ public class GridNode implements IGridNode, IPathItem
this.usedChannels = 0; this.usedChannels = 0;
} }
final int idx = this.connections.indexOf( (IGridConnection) fast ); final int idx = this.connections.indexOf( fast );
if( idx > 0 ) if( idx > 0 )
{ {
this.connections.remove( (IGridConnection) fast ); this.connections.remove( fast );
this.connections.add( 0, (IGridConnection) fast ); this.connections.add( 0, (IGridConnection) fast );
} }
} }
+10 -18
View File
@@ -42,10 +42,6 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectRBTreeSet;
import it.unimi.dsi.fastutil.objects.ObjectSet;
import net.minecraft.world.World; import net.minecraft.world.World;
import appeng.api.AEApi; import appeng.api.AEApi;
@@ -109,8 +105,8 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
private final Set<ICraftingProvider> craftingProviders = new HashSet<>(); private final Set<ICraftingProvider> craftingProviders = new HashSet<>();
private final Map<IGridNode, ICraftingWatcher> craftingWatchers = new HashMap<>(); private final Map<IGridNode, ICraftingWatcher> craftingWatchers = new HashMap<>();
private final IGrid grid; private final IGrid grid;
private final Object2ObjectMap<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new Object2ObjectOpenHashMap<>(); private final Map<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new HashMap<>();
private final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new Object2ObjectOpenHashMap<>(); private final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new HashMap<>();
private final Set<IAEItemStack> emitableItems = new HashSet<>(); private final Set<IAEItemStack> emitableItems = new HashSet<>();
private final Map<String, CraftingLinkNexus> craftingLinks = new HashMap<>(); private final Map<String, CraftingLinkNexus> craftingLinks = new HashMap<>();
private final Multimap<IAEStack, CraftingWatcher> interests = HashMultimap.create(); private final Multimap<IAEStack, CraftingWatcher> interests = HashMultimap.create();
@@ -164,11 +160,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
{ {
if( machine instanceof ICraftingWatcherHost ) if( machine instanceof ICraftingWatcherHost )
{ {
final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( gridNode ); final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine );
if( craftingWatcher != null ) if( craftingWatcher != null )
{ {
craftingWatcher.reset(); craftingWatcher.reset();
this.craftingWatchers.remove( gridNode ); this.craftingWatchers.remove( machine );
} }
} }
@@ -274,7 +270,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
return; return;
} }
final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = this.craftableItems; final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = this.craftableItems;
// erase list. // erase list.
this.craftingMethods.clear(); this.craftingMethods.clear();
@@ -291,7 +287,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
provider.provideCrafting( this ); provider.provideCrafting( this );
} }
final Object2ObjectMap<IAEItemStack, ObjectSet<ICraftingPatternDetails>> tmpCraft = new Object2ObjectOpenHashMap<>(); final Map<IAEItemStack, Set<ICraftingPatternDetails>> tmpCraft = new HashMap<>();
// new craftables! // new craftables!
for( final ICraftingPatternDetails details : this.craftingMethods.keySet() ) for( final ICraftingPatternDetails details : this.craftingMethods.keySet() )
@@ -302,11 +298,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
out.reset(); out.reset();
out.setCraftable( true ); out.setCraftable( true );
ObjectSet<ICraftingPatternDetails> methods = tmpCraft.get( out ); Set<ICraftingPatternDetails> methods = tmpCraft.get( out );
if( methods == null ) if( methods == null )
{ {
tmpCraft.put( out, methods = new ObjectRBTreeSet<>( COMPARATOR ) ); tmpCraft.put( out, methods = new TreeSet<>( COMPARATOR ) );
} }
methods.add( details ); methods.add( details );
@@ -314,7 +310,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
} }
// make them immutable // make them immutable
for( final Entry<IAEItemStack, ObjectSet<ICraftingPatternDetails>> e : tmpCraft.entrySet() ) for( final Entry<IAEItemStack, Set<ICraftingPatternDetails>> e : tmpCraft.entrySet() )
{ {
this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) ); this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) );
} }
@@ -639,11 +635,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
public boolean hasCpu( final ICraftingCPU cpu ) public boolean hasCpu( final ICraftingCPU cpu )
{ {
if (cpu instanceof CraftingCPUCluster) return this.craftingCPUClusters.contains( cpu );
{
return this.craftingCPUClusters.contains( (CraftingCPUCluster) cpu );
}
return false;
} }
public GenericInterestManager<CraftingWatcher> getInterestManager() public GenericInterestManager<CraftingWatcher> getInterestManager()
+24 -153
View File
@@ -30,7 +30,6 @@ import java.util.PriorityQueue;
import java.util.Queue; import java.util.Queue;
import java.util.Set; import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultiset; import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset; import com.google.common.collect.Multiset;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
@@ -64,7 +63,7 @@ import appeng.me.energy.EnergyWatcher;
public class EnergyGridCache implements IEnergyGrid public class EnergyGridCache implements IEnergyGrid
{ {
private static final double MAX_BUFFER_STORAGE = 800; private static final double MAX_BUFFER_STORAGE = 200;
private static final Comparator<IEnergyGridProvider> COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(), private static final Comparator<IEnergyGridProvider> COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(),
o1.getProviderStoredEnergy() ); o1.getProviderStoredEnergy() );
@@ -77,24 +76,9 @@ public class EnergyGridCache implements IEnergyGrid
}; };
private final NavigableSet<EnergyThreshold> interests = Sets.newTreeSet(); private final NavigableSet<EnergyThreshold> interests = Sets.newTreeSet();
// Should only be modified from the add/remove methods below to guard against
// concurrent modifications
private final double averageLength = 40.0; private final double averageLength = 40.0;
private final Set<IAEPowerStorage> providers = new LinkedHashSet<>(); private final Set<IAEPowerStorage> providers = new LinkedHashSet<>();
// Used to track whether an extraction is currently in progress, to fail fast
// when something externally
// modifies the energy grid.
private boolean ongoingExtractOperation = false;
// Should only be modified from the add/remove methods below to guard against
// concurrent modifications
private final Set<IAEPowerStorage> requesters = new LinkedHashSet<>(); private final Set<IAEPowerStorage> requesters = new LinkedHashSet<>();
// Used to track whether an injection is currently in progress, to fail fast
// when something externally
// modifies the energy grid.
private boolean ongoingInjectOperation = false;
private final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create(); private final Multiset<IEnergyGridProvider> energyGridProviders = HashMultiset.create();
private final IGrid myGrid; private final IGrid myGrid;
private final HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<>(); private final HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<>();
@@ -126,10 +110,6 @@ public class EnergyGridCache implements IEnergyGrid
private double lastStoredPower = -1; private double lastStoredPower = -1;
private final GridPowerStorage localStorage = new GridPowerStorage(); private final GridPowerStorage localStorage = new GridPowerStorage();
private Set<IAEPowerStorage> providerToRemove = new HashSet<>();
private Set<IAEPowerStorage> requesterToRemove = new HashSet<>();
private Set<IAEPowerStorage> providersToAdd = new HashSet<>();
private Set<IAEPowerStorage> requesterToAdd = new HashSet<>();
public EnergyGridCache( final IGrid g ) public EnergyGridCache( final IGrid g )
{ {
@@ -163,32 +143,18 @@ public class EnergyGridCache implements IEnergyGrid
{ {
if( ev.storage.isAEPublicPowerStorage() ) if( ev.storage.isAEPublicPowerStorage() )
{ {
switch ( ev.type ) switch( ev.type )
{ {
case PROVIDE_POWER: case PROVIDE_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.WRITE ) if( ev.storage.getPowerFlow() != AccessRestriction.WRITE )
{ {
if( !ongoingExtractOperation ) this.providers.add( ev.storage );
{
addProvider( ev.storage );
}
else
{
this.providersToAdd.add( ev.storage );
}
} }
break; break;
case REQUEST_POWER: case REQUEST_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.READ ) if( ev.storage.getPowerFlow() != AccessRestriction.READ )
{ {
if( !ongoingInjectOperation ) this.requesters.add( ev.storage );
{
addRequester( ev.storage );
}
else
{
this.requesterToAdd.add( ev.storage );
}
} }
break; break;
} }
@@ -202,23 +168,6 @@ public class EnergyGridCache implements IEnergyGrid
@Override @Override
public void onUpdateTick() public void onUpdateTick()
{ {
if (!providerToRemove.isEmpty() && !ongoingExtractOperation) {
this.providers.removeIf( p -> providerToRemove.contains( p ) );
providerToRemove.clear();
}
if (!requesterToRemove.isEmpty() && !ongoingInjectOperation) {
this.requesters.removeIf( r -> providerToRemove.contains( r ) );
requesterToRemove.clear();
}
if (!providersToAdd.isEmpty() && !ongoingExtractOperation) {
this.providers.addAll(providersToAdd);
providersToAdd.clear();
}
if( !requesterToAdd.isEmpty() && !ongoingInjectOperation){
this.requesters.addAll(requesterToAdd);
requesterToAdd.clear();
}
if( !this.interests.isEmpty() ) if( !this.interests.isEmpty() )
{ {
final double oldPower = this.lastStoredPower; final double oldPower = this.lastStoredPower;
@@ -354,30 +303,18 @@ public class EnergyGridCache implements IEnergyGrid
final Iterator<IAEPowerStorage> it = this.providers.iterator(); final Iterator<IAEPowerStorage> it = this.providers.iterator();
ongoingExtractOperation = true; while( extractedPower < amt && it.hasNext() )
try
{ {
while ( extractedPower < amt && it.hasNext() ) final IAEPowerStorage node = it.next();
final double req = amt - extractedPower;
final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req && mode == Actionable.MODULATE )
{ {
final IAEPowerStorage node = it.next(); it.remove();
if ( providerToRemove.contains( node )) {
it.remove();
providerToRemove.remove( node );
continue;
}
final double req = amt - extractedPower;
final double newPower = node.extractAEPower( req, mode, PowerMultiplier.ONE );
extractedPower += newPower;
if( newPower < req && mode == Actionable.MODULATE )
{
it.remove();
}
} }
} finally {
ongoingExtractOperation = false;
} }
final double result = Math.min( extractedPower, amt ); final double result = Math.min( extractedPower, amt );
@@ -403,29 +340,15 @@ public class EnergyGridCache implements IEnergyGrid
final Iterator<IAEPowerStorage> it = this.requesters.iterator(); final Iterator<IAEPowerStorage> it = this.requesters.iterator();
ongoingInjectOperation = true; while( amt > 0 && it.hasNext() )
try
{ {
while ( amt > 0 && it.hasNext() ) final IAEPowerStorage node = it.next();
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
{ {
final IAEPowerStorage node = it.next(); it.remove();
if ( requesterToRemove.contains( node )) {
it.remove();
requesterToRemove.remove( node );
continue;
}
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
{
it.remove();
}
} }
} finally
{
ongoingInjectOperation = false;
} }
final double overflow = Math.max( 0.0, amt ); final double overflow = Math.max( 0.0, amt );
@@ -582,22 +505,9 @@ public class EnergyGridCache implements IEnergyGrid
this.globalMaxPower -= ps.getAEMaxPower(); this.globalMaxPower -= ps.getAEMaxPower();
this.globalAvailablePower -= ps.getAECurrentPower(); this.globalAvailablePower -= ps.getAECurrentPower();
} }
if( !ongoingExtractOperation )
{ this.providers.remove( ps );
removeProvider( ps ); this.requesters.remove( ps );
}
else
{
this.providerToRemove.add( ps );
}
if( !ongoingInjectOperation )
{
removeRequester( ps );
}
else
{
this.requesterToRemove.add( ps );
}
} }
} }
@@ -613,31 +523,6 @@ public class EnergyGridCache implements IEnergyGrid
} }
} }
private void addRequester(IAEPowerStorage requester) {
Preconditions.checkState(!ongoingInjectOperation,
"Cannot modify energy requesters while energy is being injected.");
this.requesters.add(requester);
}
private void removeRequester(IAEPowerStorage requester) {
Preconditions.checkState(!ongoingInjectOperation,
"Cannot modify energy requesters while energy is being injected.");
this.requesters.remove(requester);
}
private void addProvider(IAEPowerStorage provider) {
Preconditions.checkState(!ongoingExtractOperation,
"Cannot modify energy providers while energy is being extracted.");
this.providers.add(provider);
}
private void removeProvider(IAEPowerStorage provider) {
Preconditions.checkState(!ongoingExtractOperation,
"Cannot modify energy providers while energy is being extracted.");
this.providers.remove(provider);
}
@Override @Override
public void addNode( final IGridNode node, final IGridHost machine ) public void addNode( final IGridNode node, final IGridHost machine )
{ {
@@ -669,26 +554,12 @@ public class EnergyGridCache implements IEnergyGrid
if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE ) if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE )
{ {
this.globalAvailablePower += current; this.globalAvailablePower += current;
if( !ongoingExtractOperation ) this.providers.add( ps );
{
addProvider( ps );
}
else
{
this.providersToAdd.add( ps );
}
} }
if( current < max && ps.getPowerFlow() != AccessRestriction.READ ) if( current < max && ps.getPowerFlow() != AccessRestriction.READ )
{ {
if( !ongoingInjectOperation ) this.requesters.add( ps );
{
addRequester( ps );
}
else
{
this.requesterToAdd.add( ps );
}
} }
} }
} }
+2 -2
View File
@@ -101,12 +101,12 @@ public class GridStorageCache implements IStorageGrid
if( machine instanceof IStackWatcherHost ) if( machine instanceof IStackWatcherHost )
{ {
final IStackWatcher myWatcher = this.watchers.get( node ); final IStackWatcher myWatcher = this.watchers.get( machine );
if( myWatcher != null ) if( myWatcher != null )
{ {
myWatcher.reset(); myWatcher.reset();
this.watchers.remove( node ); this.watchers.remove( machine );
} }
} }
} }
+2 -4
View File
@@ -44,8 +44,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.data.IAEStack; import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.me.storage.ItemWatcher; import appeng.me.storage.ItemWatcher;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T> public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
@@ -60,7 +58,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
@Nonnull @Nonnull
private final IItemList<T> cachedList; private final IItemList<T> cachedList;
@Nonnull @Nonnull
private final Object2ObjectMap<IMEMonitorHandlerReceiver<T>, Object> listeners; private final Map<IMEMonitorHandlerReceiver<T>, Object> listeners;
private boolean sendEvent = false; private boolean sendEvent = false;
private boolean hasChanged = false; private boolean hasChanged = false;
@@ -72,7 +70,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
this.myGridCache = cache; this.myGridCache = cache;
this.myChannel = chan; this.myChannel = chan;
this.cachedList = chan.createList(); this.cachedList = chan.createList();
this.listeners = new Object2ObjectOpenHashMap<>(); this.listeners = new HashMap<>();
} }
@Override @Override
+1 -1
View File
@@ -314,7 +314,7 @@ public class PathGridCache implements IPathingGrid
int depth = 0; int depth = 0;
for( final IGridNode nodes : this.requireChannels ) for( final IGridNode nodes : this.requireChannels )
{ {
if( !this.semiOpen.contains( (IPathItem) nodes ) ) if( !this.semiOpen.contains( nodes ) )
{ {
final IGridBlock gb = nodes.getGridBlock(); final IGridBlock gb = nodes.getGridBlock();
final EnumSet<GridFlags> flags = gb.getFlags(); final EnumSet<GridFlags> flags = gb.getFlags();
@@ -19,11 +19,14 @@
package appeng.me.cluster.implementations; package appeng.me.cluster.implementations;
import java.util.*; import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.Collectors;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import net.minecraft.inventory.InventoryCrafting; import net.minecraft.inventory.InventoryCrafting;
@@ -31,6 +34,8 @@ import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World; import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
import appeng.api.AEApi; import appeng.api.AEApi;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
@@ -88,7 +93,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private final List<TileCraftingTile> storage = new ArrayList<>(); private final List<TileCraftingTile> storage = new ArrayList<>();
private final List<TileCraftingMonitorTile> status = new ArrayList<>(); private final List<TileCraftingMonitorTile> status = new ArrayList<>();
private final HashMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>(); private final HashMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>();
private final Map<ICraftingPatternDetails, Queue<ICraftingMedium>> visitedMediums = new HashMap<>(); private final Map<ICraftingPatternDetails,List<ICraftingMedium>> visitedMediums = new HashMap<>();
private ICraftingLink myLastLink; private ICraftingLink myLastLink;
private String myName = ""; private String myName = "";
private boolean isDestroyed = false; private boolean isDestroyed = false;
@@ -234,9 +239,8 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src ) public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src )
{ {
// also stop accepting items when the job is complete, i.e. to prevent re-insertion when pushing out if( !( input instanceof IAEItemStack ) )
// items during storeItems {
if (input == null || isComplete) {
return input; return input;
} }
@@ -294,7 +298,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{ {
is.decStackSize( what.getStackSize() ); is.decStackSize( what.getStackSize() );
this.updateRemainingItemCount( what ); this.updateElapsedTime( what );
this.markDirty(); this.markDirty();
this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) ); this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) );
@@ -433,11 +437,6 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
AELog.crafting( LOG_MARK_AS_COMPLETE, logStack ); AELog.crafting( LOG_MARK_AS_COMPLETE, logStack );
} }
// Waiting for can potentially contain items at this point, if the user has a 64xplank->64xbutton processing
// recipe for example, but only requested 1xbutton. We just ignore the rest since it will be dumped
// back into the network inventory regardless. For this to work it's important that injectItems in this CPU
// does not accept any further items if isComplete is true.
this.waitingFor.resetStatus();
this.remainingItemCount = 0; this.remainingItemCount = 0;
this.startItemCount = 0; this.startItemCount = 0;
this.lastTime = 0; this.lastTime = 0;
@@ -648,22 +647,31 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{ {
InventoryCrafting ic = null; InventoryCrafting ic = null;
if (!visitedMediums.containsKey( details ) || visitedMediums.get( details ).isEmpty()) for( final ICraftingMedium m : cc.getMediums( e.getKey() ) )
{ {
visitedMediums.put( details, new ArrayDeque<>( cc.getMediums( details ).stream().filter( Objects::nonNull ).collect( Collectors.toList()) ) );
}
while (!visitedMediums.get( details ).isEmpty())
{
ICraftingMedium m = visitedMediums.get( details ).poll();
if( e.getValue().value <= 0 ) if( e.getValue().value <= 0 )
{ {
continue; continue;
} }
if( m != null && !m.isBusy() ) if (visitedMediums.containsKey( details ))
{
if( visitedMediums.get( details ).containsAll( cc.getMediums( e.getKey() ) ) )
{
visitedMediums.clear();
visitedMediums.put( details, new ArrayList<>() );
}
}
visitedMediums.putIfAbsent( details, new ArrayList<>() );
if( visitedMediums.get( details ).contains( m ) )
{
continue;
}
visitedMediums.get( details ).add( m );
if( !m.isBusy() )
{ {
if( ic == null ) if( ic == null )
{ {
@@ -835,7 +843,6 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private void storeItems() private void storeItems()
{ {
Preconditions.checkState(isComplete, "CPU should be complete to prevent re-insertion when dumping items");
final IGrid g = this.getGrid(); final IGrid g = this.getGrid();
if( g == null ) if( g == null )
@@ -846,24 +853,23 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
final IStorageGrid sg = g.getCache( IStorageGrid.class ); final IStorageGrid sg = g.getCache( IStorageGrid.class );
final IMEInventory<IAEItemStack> ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ); final IMEInventory<IAEItemStack> ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) );
IItemList<IAEItemStack> itemList = this.inventory.getItemList(); for( IAEItemStack is : this.inventory.getItemList() )
for( IAEItemStack is : itemList )
{ {
this.postChange( is, this.machineSrc ); is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc );
IAEItemStack remainder = ii.injectItems( is.copy(), Actionable.MODULATE, this.machineSrc );
// The network was unable to receive all of the items, i.e. no or not enough storage space left if( is != null )
if( remainder != null )
{ {
is.setStackSize( remainder.getStackSize() ); this.postChange( is, this.machineSrc );
is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc );
} }
else
if( is != null )
{ {
is.reset(); this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc );
} }
} }
if( itemList.isEmpty() ) if( this.inventory.getItemList().isEmpty() )
{ {
this.inventory = new MECraftingInventory(); this.inventory = new MECraftingInventory();
} }
@@ -948,13 +954,14 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
@Override @Override
public boolean isBusy() public boolean isBusy()
{ {
final Iterator<Entry<ICraftingPatternDetails, TaskProgress>> i = this.tasks.entrySet().iterator();
this.tasks.entrySet().removeIf( while( i.hasNext() )
taskProgressEntry -> taskProgressEntry.getValue().value <= 0 );
if( !this.waitingFor.isEmpty() || !this.tasks.isEmpty() )
{ {
this.updateElapsedTime(); if( i.next().getValue().value <= 0 )
{
i.remove();
}
} }
return !this.tasks.isEmpty() || !this.waitingFor.isEmpty(); return !this.tasks.isEmpty() || !this.waitingFor.isEmpty();
@@ -1346,16 +1353,12 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
this.remainingItemCount = itemCount; this.remainingItemCount = itemCount;
} }
private void updateRemainingItemCount( final IAEItemStack is ) private void updateElapsedTime( final IAEItemStack is )
{
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
}
private void updateElapsedTime()
{ {
final long nextStartTime = System.nanoTime(); final long nextStartTime = System.nanoTime();
this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime; this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime;
this.lastTime = nextStartTime; this.lastTime = nextStartTime;
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
} }
public long getElapsedTime() public long getElapsedTime()
@@ -277,7 +277,6 @@ public class BasicCellInventory<T extends IAEStack<T>> extends AbstractCellInven
} }
t.setStackSize( stackSize ); t.setStackSize( stackSize );
t.setCraftable( false );
if( stackSize > 0 ) if( stackSize > 0 )
{ {
@@ -218,12 +218,6 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin
private boolean importStuff( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor<IAEItemStack> inv, final IEnergySource energy, final FuzzyMode fzMode ) private boolean importStuff( final InventoryAdaptor myAdaptor, final IAEItemStack whatToImport, final IMEMonitor<IAEItemStack> inv, final IEnergySource energy, final FuzzyMode fzMode )
{ {
final int toSend = this.calculateMaximumAmountToImport( myAdaptor, whatToImport, inv, fzMode ); final int toSend = this.calculateMaximumAmountToImport( myAdaptor, whatToImport, inv, fzMode );
if( toSend == 0 )
{
return true;
}
final ItemStack newItems; final ItemStack newItems;
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 ) if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
@@ -292,17 +286,8 @@ public class PartImportBus extends PartSharedItemBus implements IInventoryDestin
itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source ); itemAmountNotStorable = inv.injectItems( AEItemStack.fromItemStack( simResult ), Actionable.SIMULATE, this.source );
} }
if( simResult.isEmpty() )
{
return 0;
}
if( itemAmountNotStorable != null ) if( itemAmountNotStorable != null )
{ {
if( simResult.getCount() == itemAmountNotStorable.getStackSize() )
{
return 0;
}
return (int) Math.min( simResult.getCount() - itemAmountNotStorable.getStackSize(), toSend ); return (int) Math.min( simResult.getCount() - itemAmountNotStorable.getStackSize(), toSend );
} }
@@ -19,10 +19,20 @@
package appeng.parts.misc; package appeng.parts.misc;
import appeng.api.AEApi; import java.util.ArrayList;
import appeng.api.config.Actionable; import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import appeng.api.config.Settings; import appeng.api.config.Settings;
import appeng.api.config.StorageFilter; import appeng.api.config.StorageFilter;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor; import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickRateModulation;
@@ -36,19 +46,7 @@ import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
import appeng.util.Platform; import appeng.util.Platform;
import appeng.util.inv.ItemHandlerIterator;
import appeng.util.inv.ItemSlot;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.IItemHandler;
import org.apache.commons.lang3.tuple.Pair;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/** /**
@@ -56,7 +54,7 @@ import java.util.Map;
*/ */
class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAEItemStack>, ITickingMonitor class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAEItemStack>, ITickingMonitor
{ {
private final Object2ObjectMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new Object2ObjectOpenHashMap<>(); private final Map<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>();
private IActionSource mySource; private IActionSource mySource;
private final IItemHandler itemHandler; private final IItemHandler itemHandler;
private final IGridProxyable proxyable; private final IGridProxyable proxyable;
@@ -78,7 +76,6 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override @Override
public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src ) public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src )
{ {
ItemStack orgInput = iox.createItemStack(); ItemStack orgInput = iox.createItemStack();
ItemStack remaining = orgInput; ItemStack remaining = orgInput;
@@ -89,10 +86,6 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ ) for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ )
{ {
remaining = this.itemHandler.insertItem( i, remaining, simulate ); remaining = this.itemHandler.insertItem( i, remaining, simulate );
if( remaining.isEmpty() )
{
break;
}
} }
// At this point, we still have some items left... // At this point, we still have some items left...
@@ -112,7 +105,6 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
{ {
// meh // meh
} }
} }
return AEItemStack.fromItemStack( remaining ); return AEItemStack.fromItemStack( remaining );
@@ -121,6 +113,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override @Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{ {
ItemStack requestedItemStack = request.createItemStack(); ItemStack requestedItemStack = request.createItemStack();
int remainingSize = requestedItemStack.getCount(); int remainingSize = requestedItemStack.getCount();
@@ -147,9 +140,16 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
do do
{ {
extracted = this.itemHandler.extractItem( i, remainingCurrentSlot, simulate ); extracted = this.itemHandler.extractItem( i, remainingCurrentSlot, simulate );
if( !extracted.isEmpty() ) if( !extracted.isEmpty() )
{ {
// In order to guard against broken IItemHandler implementations, we'll try to guess if the returned
// stack (especially in simulate mode) is the same that was returned by getStackInSlot. This is
// obviously not a precise science, but it would catch the previous Forge bug:
// https://github.com/MinecraftForge/MinecraftForge/pull/6580
if (extracted == stackInInventorySlot) {
extracted = extracted.copy();
}
if( extracted.getCount() > remainingCurrentSlot ) if( extracted.getCount() > remainingCurrentSlot )
{ {
// Something broke. It should never return more than we requested... // Something broke. It should never return more than we requested...
@@ -159,12 +159,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
extracted.setCount( remainingCurrentSlot ); extracted.setCount( remainingCurrentSlot );
} }
// We're just gonna use the first stack we get our hands on as the template for the rest. // Heuristic for simulation: looping in case of simulations is pointless, since the state of the
// In case some stupid itemhandler (aka forge) returns an internal state we have to do a second // underlying inventory does not change after a simulated extraction. To still support inventories
// expensive copy again. // that report stacks that are larger than maxStackSize, we use this heuristic
if (simulate && extracted.getCount() == extracted.getMaxStackSize()
&& remainingCurrentSlot > extracted.getMaxStackSize()) {
extracted.setCount(remainingCurrentSlot);
}
if( gathered.isEmpty() ) if( gathered.isEmpty() )
{ {
gathered = extracted.copy(); gathered = extracted;
} }
else else
{ {
@@ -172,7 +177,8 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
} }
remainingCurrentSlot -= extracted.getCount(); remainingCurrentSlot -= extracted.getCount();
} }
} while ( !extracted.isEmpty() && remainingCurrentSlot > 0 ); }
while( !simulate && !extracted.isEmpty() && remainingCurrentSlot > 0 );
remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot; remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot;
@@ -251,7 +257,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private void postDifference( Iterable<IAEItemStack> a ) private void postDifference( Iterable<IAEItemStack> a )
{ {
final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator(); final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator();
while ( i.hasNext() ) while( i.hasNext() )
{ {
final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next(); final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey(); final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -266,9 +272,9 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
} }
} }
private static class InventoryCache implements Iterable<ItemSlot> private static class InventoryCache
{ {
private IItemList<IAEItemStack> cachedAeStacks = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final IItemHandler itemHandler; private final IItemHandler itemHandler;
private final StorageFilter mode; private final StorageFilter mode;
@@ -280,77 +286,106 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out ) public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{ {
this.cachedAeStacks.forEach( out::add ); Arrays.stream( this.cachedAeStacks ).forEach( out::add );
return out; return out;
} }
private StorageFilter getMode()
{
return this.mode;
}
public List<IAEItemStack> update() public List<IAEItemStack> update()
{ {
final List<IAEItemStack> changes = new ArrayList<>(); final List<IAEItemStack> changes = new ArrayList<>();
final int slots = this.itemHandler.getSlots();
IItemList<IAEItemStack> storage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); // Make room for new slots
if( slots > this.cachedAeStacks.length )
for( final ItemSlot is : this )
{ {
final ItemStack stackInSlot = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? ItemStack.EMPTY : is.getItemStack(); this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
if( !stackInSlot.isEmpty() )
{
storage.add( AEItemStack.fromItemStack( stackInSlot ) );
}
} }
Iterator<IAEItemStack> cachedAeStacksIterator = cachedAeStacks.iterator(); for( int slot = 0; slot < slots; slot++ )
while ( cachedAeStacksIterator.hasNext() )
{ {
IAEItemStack cachedStack = cachedAeStacksIterator.next(); // Save the old stuff
IAEItemStack storedStack = storage.findPrecise( cachedStack ); final IAEItemStack oldAeIS = this.cachedAeStacks[slot];
if( storedStack == null ) ItemStack newIS = this.itemHandler.getStackInSlot( slot );
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !newIS.isEmpty() )
{ {
changes.add( cachedStack.setStackSize( -cachedStack.getStackSize() ) ); if( this.itemHandler.extractItem( slot, 1, true ).isEmpty() )
} {
else if( cachedStack.getStackSize() != storedStack.getStackSize() ) newIS = ItemStack.EMPTY;
{ }
handleStackSizeChanged( cachedStack, storedStack, changes );
} }
this.handlePossibleSlotChanges( slot, oldAeIS, newIS, changes );
} }
for( IAEItemStack storedStack : storage ) // Handle cases where the number of slots actually is lower now than before
if( slots < this.cachedAeStacks.length )
{ {
if( cachedAeStacks.findPrecise( storedStack ) == null ) for( int slot = slots; slot < this.cachedAeStacks.length; slot++ )
{ {
cachedAeStacks.add( storedStack ); final IAEItemStack aeStack = this.cachedAeStacks[slot];
changes.add( storedStack.copy() );
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
} }
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
} }
return changes; return changes;
} }
private void handleStackSizeChanged( IAEItemStack cachedStack, IAEItemStack storedStack, List<IAEItemStack> changes ) private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{ {
// Still the same item, but amount might have changed if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
final long diff = storedStack.getStackSize() - cachedStack.getStackSize();
if( diff != 0 )
{ {
cachedStack.setStackSize( storedStack.getStackSize() ); this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
final IAEItemStack diffStack = cachedStack.copy(); else
diffStack.setStackSize( diff ); {
changes.add( diffStack ); this.handleItemChanged( slot, oldAeIS, newIS, changes );
} }
} }
@Override private void handleStackSizeChanged( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
public Iterator<ItemSlot> iterator()
{ {
return new ItemHandlerIterator( this.itemHandler ); // Still the same item, but amount might have changed
final long diff = newIS.getCount() - oldAeIS.getStackSize();
if( diff != 0 )
{
final IAEItemStack stack = oldAeIS.copy();
stack.setStackSize( newIS.getCount() );
this.cachedAeStacks[slot] = stack;
final IAEItemStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
} }
private void handleItemChanged( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{
// Completely different item
this.cachedAeStacks[slot] = AEItemStack.fromItemStack( newIS );
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeIS != null )
{
oldAeIS.setStackSize( -oldAeIS.getStackSize() );
changes.add( oldAeIS );
}
// Notify the network about the new stack. Note that this is null if newIS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
} }
} }
@@ -1,5 +1,19 @@
package appeng.parts.misc; package appeng.parts.misc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import appeng.api.storage.IStorageChannel;
import appeng.core.AELog;
import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository;
import net.minecraft.item.ItemStack;
import appeng.api.AEApi; import appeng.api.AEApi;
import appeng.api.config.Actionable; import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource; import appeng.api.networking.security.IActionSource;
@@ -7,24 +21,15 @@ import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation; import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.storage.IMEInventory; import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEMonitorHandlerReceiver; import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.GridAccessException; import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable; import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor; import appeng.me.storage.ITickingMonitor;
import appeng.util.item.AEItemStack; import appeng.util.item.AEItemStack;
import com.jaquadro.minecraft.storagedrawers.api.capabilities.IItemRepository;
import it.unimi.dsi.fastutil.objects.Object2ObjectMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
import net.minecraft.item.ItemStack;
import java.util.ArrayList; import javax.annotation.Nonnull;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/** /**
* Wraps an Item Repository in such a way that it can be used as an IMEInventory for items. * Wraps an Item Repository in such a way that it can be used as an IMEInventory for items.
@@ -33,7 +38,7 @@ import java.util.Map;
class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAEItemStack>, ITickingMonitor class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAEItemStack>, ITickingMonitor
{ {
private final Object2ObjectMap<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new Object2ObjectOpenHashMap<>(); private final Map<IMEMonitorHandlerReceiver<IAEItemStack>, Object> listeners = new HashMap<>();
private IActionSource mySource; private IActionSource mySource;
private final IItemRepository itemRepository; private final IItemRepository itemRepository;
private final IGridProxyable proxyable; private final IGridProxyable proxyable;
@@ -83,12 +88,13 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override @Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src ) public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{ {
ItemStack requestedItemStack = request.getDefinition(); ItemStack requestedItemStack = request.createItemStack();
int remainingSize = (int) Math.min( Integer.MAX_VALUE, request.getStackSize() ); int remainingSize = requestedItemStack.getCount();
final boolean simulate = ( mode == Actionable.SIMULATE ); final boolean simulate = ( mode == Actionable.SIMULATE );
ItemStack extracted = this.itemRepository.extractItem( requestedItemStack, remainingSize, simulate ); ItemStack extracted;
extracted = this.itemRepository.extractItem( requestedItemStack, remainingSize, simulate );
if( extracted.getCount() > remainingSize ) if( extracted.getCount() > remainingSize )
{ {
@@ -112,8 +118,10 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
// meh // meh
} }
} }
return AEItemStack.fromItemStack( extracted ); return AEItemStack.fromItemStack( extracted );
} }
return null; return null;
} }
@@ -144,7 +152,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private void postDifference( Iterable<IAEItemStack> a ) private void postDifference( Iterable<IAEItemStack> a )
{ {
final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator(); final Iterator<Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object>> i = this.listeners.entrySet().iterator();
while ( i.hasNext() ) while( i.hasNext() )
{ {
final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next(); final Map.Entry<IMEMonitorHandlerReceiver<IAEItemStack>, Object> l = i.next();
final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey(); final IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -184,7 +192,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private static class InventoryCache private static class InventoryCache
{ {
private IItemList<IAEItemStack> cachedAeStacks = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final IItemRepository iItemRepository; private final IItemRepository iItemRepository;
public InventoryCache( IItemRepository iItemRepository ) public InventoryCache( IItemRepository iItemRepository )
@@ -194,7 +202,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out ) public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{ {
this.cachedAeStacks.forEach( out::add ); Arrays.stream( this.cachedAeStacks ).forEach( out::add );
return out; return out;
} }
@@ -202,51 +210,94 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
{ {
final List<IAEItemStack> changes = new ArrayList<>(); final List<IAEItemStack> changes = new ArrayList<>();
IItemList<IAEItemStack> storage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList(); List<IAEItemStack> out = this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).collect(Collectors.toList() );
this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).forEach( storage::add );
Iterator<IAEItemStack> cachedAeStacksIterator = cachedAeStacks.iterator(); final int size = out.size();
while ( cachedAeStacksIterator.hasNext() )
// Make room for new slots
if( size > this.cachedAeStacks.length )
{ {
IAEItemStack cachedStack = cachedAeStacksIterator.next(); this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
IAEItemStack storedStack = storage.findPrecise( cachedStack );
if( storedStack == null )
{
changes.add( cachedStack.setStackSize( -cachedStack.getStackSize() ) );
cachedAeStacksIterator.remove();
}
else if( cachedStack.getStackSize() != storedStack.getStackSize() )
{
handleStackSizeChanged( cachedStack, storedStack, changes );
}
} }
for( IAEItemStack storedStack : storage ) for( int x = 0; x < size; x++ )
{ {
if( cachedAeStacks.findPrecise( storedStack ) == null ) // Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[x];
final IAEItemStack newIS = out.get( x );
this.handlePossibleSlotChanges( x, oldAeIS, newIS, changes );
}
// Handle cases where the number of slots actually is lower now than before
if( size < this.cachedAeStacks.length )
{
for( int x = 0; x < this.cachedAeStacks.length; x++ )
{ {
cachedAeStacks.add( storedStack ); final IAEItemStack aeStack = this.cachedAeStacks[x];
changes.add( storedStack.copy() );
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
} }
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
} }
return changes; return changes;
} }
private void handleStackSizeChanged( IAEItemStack cachedStack, IAEItemStack storedStack, List<IAEItemStack> changes ) private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{ {
// Still the same item, but amount might have changed if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
final long diff = storedStack.getStackSize() - cachedStack.getStackSize();
if( diff != 0 )
{ {
cachedStack.setStackSize( storedStack.getStackSize() ); this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
final IAEItemStack diffStack = cachedStack.copy(); else
diffStack.setStackSize( diff ); {
changes.add( diffStack ); this.handleItemChanged( slot, oldAeIS, newIS, changes );
} }
} }
private void handleStackSizeChanged( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
// Still the same item, but amount might have changed
final long diff = newIS.getStackSize() - oldAeIS.getStackSize();
if( diff != 0 )
{
final IAEItemStack stack = oldAeIS.copy();
stack.setStackSize( newIS.getStackSize() );
this.cachedAeStacks[slot] = stack;
final IAEItemStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
}
private void handleItemChanged( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
// Completely different item
this.cachedAeStacks[slot] = newIS ;
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeIS != null )
{
oldAeIS.setStackSize( -oldAeIS.getStackSize() );
changes.add( oldAeIS );
}
// Notify the network about the new stack. Note that this is null if newIS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
} }
} }
@@ -258,20 +258,20 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
@Override @Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource source ) public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource source )
{ {
if( source == this.mySrc || source.machine().map( machine -> machine == this ).orElse( false ) ) try
{ {
try if( this.getProxy().isActive() )
{ {
if( this.getProxy().isActive() ) this.getProxy()
{ .getStorage()
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc ); .postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change,
} this.mySrc );
}
catch( final GridAccessException e )
{
// :(
} }
} }
catch( final GridAccessException e )
{
// :(
}
} }
@Override @Override
@@ -19,12 +19,11 @@
package appeng.parts.p2p; package appeng.parts.p2p;
import java.util.*; import java.util.List;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import appeng.me.cache.helpers.TunnelCollection;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability;
@@ -43,7 +42,6 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage(); private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage();
private final IEnergyStorage inputHandler = new InputEnergyStorage(); private final IEnergyStorage inputHandler = new InputEnergyStorage();
private final IEnergyStorage outputHandler = new OutputEnergyStorage(); private final IEnergyStorage outputHandler = new OutputEnergyStorage();
private final Queue<PartP2PFEPower> outputs = new ArrayDeque<>();
public PartP2PFEPower( ItemStack is ) public PartP2PFEPower( ItemStack is )
{ {
@@ -110,8 +108,6 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private class InputEnergyStorage implements IEnergyStorage private class InputEnergyStorage implements IEnergyStorage
{ {
private boolean iteratingOutputs;
@Override @Override
public int extractEnergy( int maxExtract, boolean simulate ) public int extractEnergy( int maxExtract, boolean simulate )
{ {
@@ -135,14 +131,8 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
final int amountPerOutput = maxReceive / outputTunnels; final int amountPerOutput = maxReceive / outputTunnels;
int overflow = amountPerOutput == 0 ? maxReceive : maxReceive % amountPerOutput; int overflow = amountPerOutput == 0 ? maxReceive : maxReceive % amountPerOutput;
if (outputs.isEmpty()) for( PartP2PFEPower target : PartP2PFEPower.this.getOutputs() )
{ {
for ( PartP2PFEPower o : PartP2PFEPower.this.getOutputs())
outputs.add( o );
}
while ( !outputs.isEmpty() ) {
PartP2PFEPower target = outputs.poll();
final IEnergyStorage output = target.getAttachedEnergyStorage(); final IEnergyStorage output = target.getAttachedEnergyStorage();
final int toSend = amountPerOutput + overflow; final int toSend = amountPerOutput + overflow;
final int received = output.receiveEnergy( toSend, simulate ); final int received = output.receiveEnergy( toSend, simulate );
@@ -425,7 +425,6 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC
if( extracted != null ) if( extracted != null )
{ {
possible = extracted.getStackSize(); possible = extracted.getStackSize();
extracted.setCraftable( false );
final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc ); final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc );
if( failed != null ) if( failed != null )
@@ -56,6 +56,6 @@ public class ReadOnlyCollection<T> implements IReadOnlyCollection<T>
@Override @Override
public boolean contains( final Object node ) public boolean contains( final Object node )
{ {
return this.c.contains( (T) node ); return this.c.contains( node );
} }
} }
@@ -206,4 +206,3 @@ public class AdaptorItemRepository extends InventoryAdaptor
return null; return null;
} }
} }
@@ -25,7 +25,7 @@ import java.util.NoSuchElementException;
import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandler;
public class ItemHandlerIterator implements Iterator<ItemSlot> class ItemHandlerIterator implements Iterator<ItemSlot>
{ {
private final IItemHandler itemHandler; private final IItemHandler itemHandler;
@@ -34,7 +34,7 @@ public class ItemHandlerIterator implements Iterator<ItemSlot>
private int slot = 0; private int slot = 0;
public ItemHandlerIterator( IItemHandler itemHandler ) ItemHandlerIterator( IItemHandler itemHandler )
{ {
this.itemHandler = itemHandler; this.itemHandler = itemHandler;
} }
+282 -225
View File
@@ -1,6 +1,6 @@
/* /*
* This file is part of Applied Energistics 2. * This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2020, AlgorithmX2, All rights reserved. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
* *
* Applied Energistics 2 is free software: you can redistribute it and/or modify * Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@@ -18,6 +18,7 @@
package appeng.util.item; package appeng.util.item;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@@ -26,291 +27,347 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.ItemHandlerHelper; import net.minecraftforge.items.ItemHandlerHelper;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode; import appeng.api.config.FuzzyMode;
import appeng.api.storage.IStorageChannel; import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel; import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.core.Api;
import appeng.util.Platform; import appeng.util.Platform;
public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack {
private static final String NBT_STACKSIZE = "Cnt";
private static final String NBT_REQUESTABLE = "Req";
private static final String NBT_CRAFTABLE = "Craft";
private final AESharedItemStack sharedStack; public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack
private Optional<OreReference> oreReference; {
private AESharedItemStack sharedStack;
private Optional<OreReference> oreReference;
@SideOnly(Side.CLIENT) @SideOnly( Side.CLIENT )
private String displayName; private String displayName;
@SideOnly(Side.CLIENT) @SideOnly( Side.CLIENT )
private List<String> tooltip; private List<String> tooltip;
@SideOnly( Side.CLIENT )
private ResourceLocation uniqueID;
private AEItemStack(final AEItemStack is) { private AEItemStack( final AEItemStack is )
this.setStackSize(is.getStackSize()); {
this.setCraftable(is.isCraftable()); this.setStackSize( is.getStackSize() );
this.setCountRequestable(is.getCountRequestable()); this.setCraftable( is.isCraftable() );
this.sharedStack = is.sharedStack; this.setCountRequestable( is.getCountRequestable() );
this.oreReference = is.oreReference; this.sharedStack = is.sharedStack;
} this.oreReference = is.oreReference;
}
private AEItemStack(final AESharedItemStack is, long size) { private AEItemStack( final AESharedItemStack is, long size )
this.sharedStack = is; {
this.setStackSize(size); this.sharedStack = is;
this.setCraftable(false); this.setStackSize( size );
this.setCountRequestable(0); this.setCraftable( false );
this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() ); this.setCountRequestable( 0 );
} this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() );
}
@Nullable @Nullable
public static AEItemStack fromItemStack(@Nonnull final ItemStack stack) { public static AEItemStack fromItemStack( @Nonnull final ItemStack stack )
if (stack.isEmpty()) { {
return null; if( stack.isEmpty() )
} {
return null;
}
return new AEItemStack(AEItemStackRegistry.getRegisteredStack(stack), stack.getCount()); return new AEItemStack( AEItemStackRegistry.getRegisteredStack( stack ), stack.getCount() );
} }
public static IAEItemStack fromNBT(final NBTTagCompound i) { public static IAEItemStack fromNBT( final NBTTagCompound i )
if (i == null) { {
return null; if( i == null )
} {
return null;
}
final ItemStack itemstack = new ItemStack(i); final ItemStack itemstack = new ItemStack( i );
final AEItemStack item = AEItemStack.fromItemStack(itemstack); if( itemstack.isEmpty() )
if (item == null) { {
return null; return null;
} }
item.setStackSize(i.getLong(NBT_STACKSIZE)); final AEItemStack item = AEItemStack.fromItemStack( itemstack );
item.setCountRequestable(i.getLong(NBT_REQUESTABLE)); item.setStackSize( i.getLong( "Cnt" ) );
item.setCraftable(i.getBoolean(NBT_CRAFTABLE)); item.setCountRequestable( i.getLong( "Req" ) );
return item; item.setCraftable( i.getBoolean( "Craft" ) );
} return item;
}
@Override @Override
public void writeToNBT(final NBTTagCompound i) { public void writeToNBT( final NBTTagCompound i )
final NBTTagCompound itemStack = new NBTTagCompound(); {
this.getDefinition().writeToNBT(itemStack); this.getDefinition().writeToNBT( i );
i.setLong( "Cnt", this.getStackSize() );
i.setLong( "Req", this.getCountRequestable() );
i.setBoolean( "Craft", this.isCraftable() );
}
i.setLong(NBT_STACKSIZE, this.getStackSize()); public static AEItemStack fromPacket( final ByteBuf data )
i.setLong(NBT_REQUESTABLE, this.getCountRequestable()); {
i.setBoolean(NBT_CRAFTABLE, this.isCraftable()); final byte mask = data.readByte();
} final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 );
final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 );
final boolean isCraftable = ( mask & 0x40 ) > 0;
public static AEItemStack fromPacket( final ByteBuf data ) final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) );
{ final long stackSize = getPacketValue( stackType, data );
final byte mask = data.readByte(); final long countRequestable = getPacketValue( countReqType, data );
final byte stackType = (byte) ( ( mask & 0x0C ) >> 2 );
final byte countReqType = (byte) ( ( mask & 0x30 ) >> 4 );
final boolean isCraftable = ( mask & 0x40 ) > 0;
final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) ); if( itemstack.isEmpty() )
final long stackSize = getPacketValue( stackType, data ); {
final long countRequestable = getPacketValue( countReqType, data ); return null;
}
if( itemstack.isEmpty() ) final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize );
{ item.setCountRequestable( countRequestable );
return null; item.setCraftable( isCraftable );
} return item;
}
final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize ); @Override
item.setCountRequestable( countRequestable ); public void writeToPacket( final ByteBuf i )
item.setCraftable( isCraftable ); {
return item; final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this
} .getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 );
@Override i.writeByte( mask );
public void writeToPacket( final ByteBuf i ) ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() );
{ this.putPacketValue( i, this.getStackSize() );
final byte mask = (byte) ( ( this.getType( this.getStackSize() ) << 2 ) | ( this this.putPacketValue( i, this.getCountRequestable() );
.getType( this.getCountRequestable() ) << 4 ) | ( (byte) ( this.isCraftable() ? 1 : 0 ) << 6 ) | ( this.hasTagCompound() ? 1 : 0 ) << 7 ); }
i.writeByte( mask ); @Override
ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() ); public void add( final IAEItemStack option )
this.putPacketValue( i, this.getStackSize() ); {
this.putPacketValue( i, this.getCountRequestable() ); if( option == null )
} {
return;
}
@Override this.incStackSize( option.getStackSize() );
public void add(final IAEItemStack option) { this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() );
if (option == null) { this.setCraftable( this.isCraftable() || option.isCraftable() );
return; }
}
this.incStackSize(option.getStackSize()); @Override
this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable()); public boolean fuzzyComparison( final IAEItemStack other, final FuzzyMode mode )
this.setCraftable(this.isCraftable() || option.isCraftable()); {
} if( mode == FuzzyMode.IGNORE_ALL && OreHelper.INSTANCE.sameOre( this, other ) )
{
return true;
}
@Override final ItemStack itemStack = this.getDefinition();
public boolean fuzzyComparison(final IAEItemStack other, final FuzzyMode mode) { final ItemStack otherStack = other.getDefinition();
final ItemStack itemStack = this.getDefinition();
final ItemStack otherStack = other.getDefinition();
return this.fuzzyItemStackComparison(itemStack, otherStack, mode); return this.fuzzyItemStackComparison( itemStack, otherStack, mode );
} }
@Override @Override
public IAEItemStack copy() { public IAEItemStack copy()
return new AEItemStack(this); {
} return new AEItemStack( this );
}
@Override @Override
public boolean isItem() public boolean isItem()
{ {
return true; return true;
} }
@Override @Override
public boolean isFluid() public boolean isFluid()
{ {
return false; return false;
} }
@Override @Override
public IStorageChannel<IAEItemStack> getChannel() { public IStorageChannel<IAEItemStack> getChannel()
return Api.INSTANCE.storage().getStorageChannel(IItemStorageChannel.class); {
} return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class );
}
@Override @Override
public ItemStack createItemStack() { public ItemStack createItemStack()
return ItemHandlerHelper.copyStackWithSize(this.getDefinition(), {
(int) Math.min(Integer.MAX_VALUE, this.getStackSize())); return ItemHandlerHelper.copyStackWithSize( this.getDefinition(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) );
} }
@Override @Override
public Item getItem() { public Item getItem()
return this.getDefinition().getItem(); {
} return this.getDefinition().getItem();
}
@Override @Override
public int getItemDamage() { public int getItemDamage()
return this.sharedStack.getItemDamage(); {
} return this.sharedStack.getItemDamage();
}
@Override @Override
public boolean sameOre( final IAEItemStack is ) public boolean sameOre( final IAEItemStack is )
{ {
return OreHelper.INSTANCE.sameOre( this, is ); return OreHelper.INSTANCE.sameOre( this, is );
} }
@Override @Override
public boolean isSameType(final IAEItemStack otherStack) { public boolean isSameType( final IAEItemStack otherStack )
if (otherStack == null) { {
return false; if( otherStack == null )
} {
return false;
}
return Objects.equals(this.sharedStack, ((AEItemStack) otherStack).sharedStack); return Objects.equals( this.sharedStack, ( (AEItemStack) otherStack ).sharedStack );
} }
@Override @Override
public boolean isSameType(final ItemStack otherStack) { public boolean isSameType( final ItemStack otherStack )
if (otherStack.isEmpty()) { {
return false; if( otherStack.isEmpty() )
} {
int oldSize = otherStack.getCount(); return false;
}
int oldSize = otherStack.getCount();
otherStack.setCount(1); otherStack.setCount( 1 );
boolean ret = ItemStack.areItemStacksEqual(this.getDefinition(), otherStack); boolean ret = ItemStack.areItemStacksEqual( this.getDefinition(), otherStack );
otherStack.setCount(oldSize); otherStack.setCount( oldSize );
return ret; return ret;
} }
@Override @Override
public int hashCode() { public int hashCode()
return this.sharedStack.hashCode(); {
} return this.sharedStack.hashCode();
}
@Override @Override
public boolean equals(final Object ia) { public boolean equals( final Object ia )
if (ia instanceof AEItemStack) { {
return this.isSameType((AEItemStack) ia); if( ia instanceof AEItemStack )
} else if (ia instanceof ItemStack) { {
// this actually breaks the equals contract (being equals to unrelated classes) return this.isSameType( (AEItemStack) ia );
return equals((ItemStack) ia); }
} else if( ia instanceof ItemStack )
return false; {
} return this.isSameType( (ItemStack) ia );
}
return false;
}
@Override @Override
public boolean equals(final ItemStack is) { public String toString()
return this.isSameType(is); {
} return this.getStackSize() + "x" + this.getDefinition().getItem().getUnlocalizedName() + "@" + this.getDefinition().getItemDamage();
}
@Override @SideOnly( Side.CLIENT )
public String toString() { public List<String> getToolTip()
return this.getStackSize() + "x" + this.getDefinition().getItem().getRegistryName(); {
} if( this.tooltip == null )
{
this.tooltip = Platform.getTooltip( this.asItemStackRepresentation() );
}
return this.tooltip;
}
@SideOnly(Side.CLIENT) @SideOnly( Side.CLIENT )
public List<String> getToolTip() { public String getDisplayName()
if (this.tooltip == null) { {
this.tooltip = Platform.getTooltip(this.asItemStackRepresentation()); if( this.displayName == null )
} {
return this.tooltip; this.displayName = Platform.getItemDisplayName( this.asItemStackRepresentation() );
} }
return this.displayName;
}
@SideOnly(Side.CLIENT) @SideOnly( Side.CLIENT )
public String getDisplayName() { public String getModID()
if (this.displayName == null) { {
this.displayName = Platform.getItemDisplayName(this.asItemStackRepresentation()); if( this.uniqueID == null )
} {
return this.displayName; this.uniqueID = Item.REGISTRY.getNameForObject( this.getDefinition().getItem() );
} }
@SideOnly(Side.CLIENT) if( this.uniqueID == null )
public String getModID() { {
return this.getDefinition().getItem().getRegistryName().getResourceDomain(); return "** Null";
} }
public Optional<OreReference> getOre() return this.uniqueID.getResourceDomain() == null ? "** Null" : this.uniqueID.getResourceDomain();
{ }
return this.oreReference;
}
@Override public Optional<OreReference> getOre()
public boolean hasTagCompound() { {
return this.getDefinition().hasTagCompound(); return this.oreReference;
} }
@Override @Override
public ItemStack asItemStackRepresentation() { public boolean hasTagCompound()
return this.getDefinition().copy(); {
} return this.getDefinition().hasTagCompound();
}
@Override @Override
public ItemStack getDefinition() { public ItemStack asItemStackRepresentation()
return this.sharedStack.getDefinition(); {
} return this.getDefinition().copy();
}
AESharedItemStack getSharedStack() { @Override
return this.sharedStack; public ItemStack getDefinition()
} {
return this.sharedStack.getDefinition();
}
private boolean fuzzyItemStackComparison(ItemStack a, ItemStack b, FuzzyMode mode) { AESharedItemStack getSharedStack()
if (a.getItem() == b.getItem() && a.getItem().isDamageable()) { {
if (mode == FuzzyMode.IGNORE_ALL) { return this.sharedStack;
return true; }
} else if (mode == FuzzyMode.PERCENT_99) {
return a.getItemDamage() > 1 == b.getItemDamage() > 1;
} else {
final float percentDamageOfA = (float) a.getItemDamage() / a.getMaxDamage();
final float percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage();
return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint; private boolean fuzzyItemStackComparison( ItemStack a, ItemStack b, FuzzyMode mode )
} {
} if( a.getItem() == b.getItem() )
{
if( a.getItem().isDamageable() )
{
if( mode == FuzzyMode.IGNORE_ALL )
{
return true;
}
else if( mode == FuzzyMode.PERCENT_99 )
{
return ( a.getItemDamage() > 1 ) == ( b.getItemDamage() > 1 );
}
else
{
final float percentDamageOfA = (float) a.getItemDamage() / (float) a.getMaxDamage();
final float percentDamageOfB = (float) b.getItemDamage() / (float) b.getMaxDamage();
return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint );
}
}
return a.getMetadata() == b.getMetadata();
}
return false;
}
return false;
}
} }
@@ -23,6 +23,7 @@
package appeng.util.item; package appeng.util.item;
import java.lang.ref.WeakReference; import java.lang.ref.WeakReference;
import java.util.WeakHashMap; import java.util.WeakHashMap;
@@ -30,34 +31,56 @@ import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
public final class AEItemStackRegistry { import appeng.util.Platform;
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> REGISTRY = new WeakHashMap<>();
private AEItemStackRegistry() {
}
static synchronized AESharedItemStack getRegisteredStack(final @Nonnull ItemStack itemStack) { public final class AEItemStackRegistry
if (itemStack.isEmpty()) { {
throw new IllegalArgumentException("stack cannot be empty"); private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> SERVER_REGISTRY = new WeakHashMap<>();
} private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> CLIENT_REGISTRY = new WeakHashMap<>();
int oldStackSize = itemStack.getCount(); private AEItemStackRegistry()
itemStack.setCount(1); {
}
AESharedItemStack search = new AESharedItemStack(itemStack); private static WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> registry()
WeakReference<AESharedItemStack> weak = REGISTRY.get(search); {
AESharedItemStack ret = null; if( Platform.isClient() )
{
return CLIENT_REGISTRY;
}
else
{
return SERVER_REGISTRY;
}
}
if (weak != null) { static synchronized AESharedItemStack getRegisteredStack( final @Nonnull ItemStack itemStack )
ret = weak.get(); {
} if( itemStack.isEmpty() )
{
throw new IllegalArgumentException( "stack cannot be empty" );
}
if (ret == null) { int oldStackSize = itemStack.getCount();
ret = new AESharedItemStack(itemStack.copy()); itemStack.setCount( 1 );
REGISTRY.put(ret, new WeakReference<>(ret));
}
itemStack.setCount(oldStackSize);
return ret; AESharedItemStack search = new AESharedItemStack( itemStack );
} WeakReference<AESharedItemStack> weak = registry().get( search );
AESharedItemStack ret = null;
if( weak != null )
{
ret = weak.get();
}
if( ret == null )
{
ret = new AESharedItemStack( itemStack.copy() );
registry().put( ret, new WeakReference<>( ret ) );
}
itemStack.setCount( oldStackSize );
return ret;
}
} }
@@ -18,76 +18,263 @@
package appeng.util.item; package appeng.util.item;
import java.util.Objects; import java.util.Objects;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
final class AESharedItemStack { import appeng.api.config.FuzzyMode;
private final ItemStack itemStack;
private final int itemId;
private final int itemDamage;
private final int hashCode;
public AESharedItemStack(final ItemStack itemStack) { final class AESharedItemStack implements Comparable<AESharedItemStack>
this(itemStack, itemStack.getItemDamage()); {
} private static final NBTTagCompound LOW_TAG = new NBTTagCompound();
private static final NBTTagCompound HIGH_TAG = new NBTTagCompound();
/** private final ItemStack itemStack;
* A constructor to explicitly set the damage value and not fetch it from the {@link ItemStack} private final int itemId;
* private final int itemDamage;
* @param itemStack The {@link ItemStack} to filter private final int hashCode;
* @param damage The damage of the item
*/
private AESharedItemStack(ItemStack itemStack, int damage) {
this.itemStack = itemStack;
this.itemId = Item.getIdFromItem(itemStack.getItem());
this.itemDamage = damage;
// Ensure this is always called last. public AESharedItemStack( final ItemStack itemStack )
this.hashCode = this.makeHashCode(); {
} this.itemStack = itemStack;
this.itemId = Item.getIdFromItem( itemStack.getItem() );
this.itemDamage = itemStack.getItemDamage();
this.hashCode = this.makeHashCode();
}
ItemStack getDefinition() { Bounds getBounds( final FuzzyMode fuzzy, final boolean ignoreMeta )
return this.itemStack; {
} return new Bounds( this.itemStack, fuzzy, ignoreMeta );
}
int getItemDamage() { ItemStack getDefinition()
return this.itemDamage; {
} return this.itemStack;
}
@Override int getItemDamage()
public int hashCode() { {
return this.hashCode; return this.itemDamage;
} }
@Override int getItemID()
public boolean equals(final Object obj) { {
if (this == obj) { return this.itemId;
return true; }
}
if (!(obj instanceof AESharedItemStack)) {
return false;
}
final AESharedItemStack other = (AESharedItemStack) obj; @Override
Preconditions.checkState(this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1"); public int hashCode()
Preconditions.checkArgument(other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1"); {
return this.hashCode;
}
if (this.itemStack == other.itemStack) { @Override
return true; public boolean equals( final Object obj )
} {
return ItemStack.areItemStacksEqual(this.itemStack, other.itemStack); if( obj instanceof AESharedItemStack )
} {
final AESharedItemStack other = (AESharedItemStack) obj;
private int makeHashCode() { Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" );
return Objects.hash( Preconditions.checkArgument( other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" );
this.itemId,
this.itemDamage,
this.itemStack.hasTagCompound() ? this.itemStack.getTagCompound() : 0);
}
if( this.itemStack == other.itemStack )
{
return true;
}
return ItemStack.areItemStacksEqual( this.itemStack, other.itemStack );
}
return false;
}
@Override
public int compareTo( final AESharedItemStack b )
{
Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" );
Preconditions.checkArgument( b.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" );
if( this.itemStack == b.getDefinition() )
{
return 0;
}
final int id = this.itemId - b.itemId;
if( id != 0 )
{
return id;
}
final int damageValue = this.itemDamage - b.itemDamage;
if( damageValue != 0 )
{
return damageValue;
}
final int nbt = this.compareNBT( b.getDefinition() );
if( nbt != 0 )
{
return nbt;
}
if( !this.itemStack.areCapsCompatible( b.getDefinition() ) )
{
return System.identityHashCode( this.itemStack ) - System.identityHashCode( b.getDefinition() );
}
return 0;
}
private int compareNBT( final ItemStack b )
{
if( this.itemStack.getTagCompound() == b.getTagCompound() )
{
return 0;
}
if( this.itemStack.getTagCompound() == LOW_TAG || b.getTagCompound() == HIGH_TAG )
{
return -1;
}
if( this.itemStack.getTagCompound() == HIGH_TAG || b.getTagCompound() == LOW_TAG )
{
return 1;
}
return System.identityHashCode( this.itemStack.getTagCompound() ) - System.identityHashCode( b.getTagCompound() );
}
private int makeHashCode()
{
return Objects.hash( this.itemId, this.itemDamage, this.itemStack.hasTagCompound() ? this.itemStack.getTagCompound() : 0 );
}
/**
* Creates the lower and upper bounds for a specific shared itemstack.
*/
public static final class Bounds
{
/**
* Bounds enforced by {@link ItemStack#isEmpty()}
*/
private static final int MIN_DAMAGE_VALUE = 0;
private static final int MAX_DAMAGE_VALUE = 65535;
private final AESharedItemStack lower;
private final AESharedItemStack upper;
public Bounds( final ItemStack stack, final FuzzyMode fuzzy, final boolean ignoreMeta )
{
Preconditions.checkState( !stack.isEmpty(), "ItemStack#isEmpty() has to be false" );
Preconditions.checkState( stack.getCount() == 1, "ItemStack#getCount() has to be 1" );
final NBTTagCompound tag = stack.hasTagCompound() ? stack.getTagCompound() : null;
this.lower = this.makeLowerBound( stack, tag, fuzzy, ignoreMeta );
this.upper = this.makeUpperBound( stack, tag, fuzzy, ignoreMeta );
}
public AESharedItemStack lower()
{
return this.lower;
}
public AESharedItemStack upper()
{
return this.upper;
}
private AESharedItemStack makeLowerBound( final ItemStack itemStack, final NBTTagCompound tag, final FuzzyMode fuzzy, final boolean ignoreMeta )
{
final ItemStack newDef = itemStack.copy();
if( ignoreMeta )
{
newDef.setItemDamage( MIN_DAMAGE_VALUE );
newDef.setTagCompound( tag );
}
else
{
if( newDef.getItem().isDamageable() )
{
if (itemStack.getMaxDamage() == 0)
{
newDef.setItemDamage(itemStack.getItemDamage() );
}
else if ( fuzzy == FuzzyMode.IGNORE_ALL )
{
newDef.setItemDamage( MIN_DAMAGE_VALUE );
}
else if( fuzzy == FuzzyMode.PERCENT_99 )
{
if( itemStack.getItemDamage() == MIN_DAMAGE_VALUE )
{
newDef.setItemDamage( MIN_DAMAGE_VALUE );
}
else
{
newDef.setItemDamage( MIN_DAMAGE_VALUE + 1 );
}
}
else
{
final int breakpoint = fuzzy.calculateBreakPoint( itemStack.getMaxDamage() );
final int damage = breakpoint <= itemStack.getItemDamage() ? breakpoint : 0;
newDef.setItemDamage( damage );
}
}
newDef.setTagCompound( LOW_TAG );
}
return new AESharedItemStack( newDef );
}
private AESharedItemStack makeUpperBound( final ItemStack itemStack, final NBTTagCompound tag, final FuzzyMode fuzzy, final boolean ignoreMeta )
{
final ItemStack newDef = itemStack.copy();
if( ignoreMeta )
{
newDef.setItemDamage( MAX_DAMAGE_VALUE );
newDef.setTagCompound( tag );
}
else
{
if( newDef.getItem().isDamageable() )
{
if (itemStack.getMaxDamage() == 0)
{
newDef.setItemDamage(itemStack.getItemDamage() );
}
else if ( fuzzy == FuzzyMode.IGNORE_ALL )
{
newDef.setItemDamage( itemStack.getMaxDamage() + 1 );
}
else if( fuzzy == FuzzyMode.PERCENT_99 )
{
if( itemStack.getItemDamage() == MIN_DAMAGE_VALUE )
{
newDef.setItemDamage( MIN_DAMAGE_VALUE );
}
else
{
newDef.setItemDamage( itemStack.getMaxDamage() + 1 );
}
}
else
{
final int breakpoint = fuzzy.calculateBreakPoint( itemStack.getMaxDamage() );
final int damage = itemStack.getItemDamage() < breakpoint ? breakpoint - 1 : itemStack.getMaxDamage() + 1;
newDef.setItemDamage( damage );
}
}
newDef.setTagCompound( HIGH_TAG );
}
return new AESharedItemStack( newDef );
}
}
} }
+143 -126
View File
@@ -18,152 +18,169 @@
package appeng.util.item; package appeng.util.item;
import appeng.api.storage.data.IAEStack;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import appeng.api.storage.data.IAEStack;
public abstract class AEStack<T extends IAEStack<T>> implements IAEStack<T> {
private boolean isCraftable; public abstract class AEStack<StackType extends IAEStack<StackType>> implements IAEStack<StackType>
private long stackSize; {
private long countRequestable;
protected static long getPacketValue( final byte type, final ByteBuf tag ) private boolean isCraftable;
{ private long stackSize;
if( type == 0 ) private long countRequestable;
{
long l = tag.readByte();
l -= Byte.MIN_VALUE;
return l;
}
else if( type == 1 )
{
long l = tag.readShort();
l -= Short.MIN_VALUE;
return l;
}
else if( type == 2 )
{
long l = tag.readInt();
l -= Integer.MIN_VALUE;
return l;
}
return tag.readLong(); protected static long getPacketValue( final byte type, final ByteBuf tag )
} {
if( type == 0 )
{
long l = tag.readByte();
l -= Byte.MIN_VALUE;
return l;
}
else if( type == 1 )
{
long l = tag.readShort();
l -= Short.MIN_VALUE;
return l;
}
else if( type == 2 )
{
long l = tag.readInt();
l -= Integer.MIN_VALUE;
return l;
}
@Override return tag.readLong();
public long getStackSize() { }
return this.stackSize;
}
@Override @Override
public T setStackSize(final long ss) { public long getStackSize()
this.stackSize = ss; {
return (T) this; return this.stackSize;
} }
@Override @Override
public long getCountRequestable() { public StackType setStackSize( final long ss )
return this.countRequestable; {
} this.stackSize = ss;
return (StackType) this;
}
@Override @Override
public T setCountRequestable(final long countRequestable) { public long getCountRequestable()
this.countRequestable = countRequestable; {
return (T) this; return this.countRequestable;
} }
@Override @Override
public boolean isCraftable() { public StackType setCountRequestable( final long countRequestable )
return this.isCraftable; {
} this.countRequestable = countRequestable;
return (StackType) this;
}
@Override @Override
public T setCraftable(final boolean isCraftable) { public boolean isCraftable()
this.isCraftable = isCraftable; {
return (T) this; return this.isCraftable;
} }
@Override @Override
public T reset() { public StackType setCraftable( final boolean isCraftable )
this.stackSize = 0; {
this.setCountRequestable(0); this.isCraftable = isCraftable;
this.setCraftable(false); return (StackType) this;
return (T) this; }
}
@Override @Override
public T empty() { public StackType reset()
final T dup = this.copy(); {
dup.reset(); this.stackSize = 0;
return dup; // priority = Integer.MIN_VALUE;
} this.setCountRequestable( 0 );
this.setCraftable( false );
return (StackType) this;
}
@Override @Override
public boolean isMeaningful() { public StackType empty()
return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable; {
} final StackType dup = this.copy();
dup.reset();
return dup;
}
@Override @Override
public void incStackSize(final long i) { public boolean isMeaningful()
this.stackSize += i; {
} return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable;
}
@Override @Override
public void decStackSize(final long i) { public void incStackSize( final long i )
this.stackSize -= i; {
} this.stackSize += i;
}
@Override @Override
public void incCountRequestable(final long i) { public void decStackSize( final long i )
this.countRequestable += i; {
} this.stackSize -= i;
}
@Override @Override
public void decCountRequestable(final long i) { public void incCountRequestable( final long i )
this.countRequestable -= i; {
} this.countRequestable += i;
}
protected byte getType( final long num ) @Override
{ public void decCountRequestable( final long i )
if( num <= 255 ) {
{ this.countRequestable -= i;
return 0; }
}
else if( num <= 65535 )
{
return 1;
}
else if( num <= 4294967295L )
{
return 2;
}
else
{
return 3;
}
}
protected abstract boolean hasTagCompound(); protected byte getType( final long num )
{
if( num <= 255 )
{
return 0;
}
else if( num <= 65535 )
{
return 1;
}
else if( num <= 4294967295L )
{
return 2;
}
else
{
return 3;
}
}
protected void putPacketValue( final ByteBuf tag, final long num ) protected abstract boolean hasTagCompound();
{
if( num <= 255 ) protected void putPacketValue( final ByteBuf tag, final long num )
{ {
tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) ); if( num <= 255 )
} {
else if( num <= 65535 ) tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) );
{ }
tag.writeShort( (short) ( num + Short.MIN_VALUE ) ); else if( num <= 65535 )
} {
else if( num <= 4294967295L ) tag.writeShort( (short) ( num + Short.MIN_VALUE ) );
{ }
tag.writeInt( (int) ( num + Integer.MIN_VALUE ) ); else if( num <= 4294967295L )
} {
else tag.writeInt( (int) ( num + Integer.MIN_VALUE ) );
{ }
tag.writeLong( num ); else
} {
} tag.writeLong( num );
}
}
} }
@@ -1,190 +0,0 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.util.item;
import java.util.Collection;
import java.util.Comparator;
import java.util.Map;
import com.google.common.base.Preconditions;
import net.minecraft.item.ItemStack;
import it.unimi.dsi.fastutil.objects.Object2ObjectAVLTreeMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectSortedMap;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
/**
* This variant list is optimized for damageable items, and supports selecting durability ranges with
* {@link #findFuzzy(IAEItemStack, FuzzyMode)}.
*/
class FuzzyItemVariantList extends ItemVariantList {
static final SharedStackComparator COMPARATOR = new SharedStackComparator();
// NOTE: We only use Object as they key here so we can pass our special DamageBounds to the subMap method.
// We NEVER put any keys in this map that are not AESharedItemStacks.
private final Object2ObjectSortedMap<Object, IAEItemStack> records = new Object2ObjectAVLTreeMap<>(COMPARATOR);
@Override
public Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) {
ItemStack itemStack = filter.getDefinition();
ItemDamageBound lowerBound = makeLowerBound(itemStack, fuzzy);
ItemDamageBound upperBound = makeUpperBound(itemStack, fuzzy);
Preconditions.checkState(lowerBound.itemDamage > upperBound.itemDamage);
return this.records.subMap(lowerBound, upperBound).values();
}
@SuppressWarnings("unchecked")
@Override
Map<AESharedItemStack, IAEItemStack> getRecords() {
// We ensure on our end that we NEVER use anything but AESharedItemStack as the key in this map
return (Map<AESharedItemStack, IAEItemStack>) (Object) this.records;
}
static class ItemDamageBound {
final int itemDamage;
public ItemDamageBound(int itemDamage) {
this.itemDamage = itemDamage;
}
}
/**
* This comparator creates a strict and total ordering over all {@link AESharedItemStack} of the same item. To
* support selecting ranges of durability, it is defined for type {@link Object} and also accepts
* {@link ItemDamageBound} as an argument to compare against.
*/
static class SharedStackComparator implements Comparator<Object> {
@Override
public int compare(Object a, Object b) {
// Either argument can either be a damage bound or a shared item stack
// Since we never put damage bounds into the map as keys, only one
// of the two arguments can possibly be a bound
ItemDamageBound boundA = null;
AESharedItemStack stackA = null;
int itemDamageA;
if (a instanceof ItemDamageBound) {
boundA = (ItemDamageBound) a;
itemDamageA = boundA.itemDamage;
} else {
stackA = (AESharedItemStack) a;
itemDamageA = stackA.getItemDamage();
}
ItemDamageBound boundB = null;
AESharedItemStack stackB = null;
int itemDamageB;
if (b instanceof ItemDamageBound) {
boundB = (ItemDamageBound) b;
itemDamageB = boundB.itemDamage;
} else {
stackB = (AESharedItemStack) b;
itemDamageB = stackB.getItemDamage();
}
// When either argument is a damage bound, we just compare the damage values because it is used
// only to get a certain damage range out of the map.
if (boundA != null || boundB != null) {
return Integer.compare(itemDamageB, itemDamageA);
}
ItemStack itemStackA = stackA.getDefinition();
ItemStack itemStackB = stackB.getDefinition();
Preconditions.checkState(itemStackA.getCount() == 1, "ItemStack#getCount() has to be 1");
Preconditions.checkArgument(itemStackB.getCount() == 1, "ItemStack#getCount() has to be 1");
if (itemStackA == itemStackB) {
return 0;
}
// Damaged items are sorted before undamaged items
final int damageValue = Integer.compare(itemDamageB, itemDamageA);
if (damageValue != 0) {
return damageValue;
}
// As a final tie breaker, order by the object identity of the item stack
// While this will order seemingly at random, we only need the order of
// damage values to be predictable, while still having to satisfy the
// complete order requirements of the sorted map
return Long.compare(System.identityHashCode(itemStackA), System.identityHashCode(itemStackB));
}
}
/**
* Minecraft reverses the damage values. So anything with a damage of 0 is undamaged and increases the more damaged
* the item is.
* <p>
* Further the used subMap follows [MAX_DAMAGE, MIN_DAMAGE), so to include undamaged items, we have to start with a
* lower damage value than 0, while it is fine to use {@link ItemStack#getMaxDamage()} for the upper bound.
*/
private static final int MIN_DAMAGE_VALUE = -1;
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this lower bound will actually be a
* higher number than the upper bound.
*/
static ItemDamageBound makeLowerBound(final ItemStack stack, final FuzzyMode fuzzy)
{
Preconditions.checkState( stack.getItem().isDamageable(), "Item#isDamageable() has to be true" );
int damage;
if( fuzzy == FuzzyMode.IGNORE_ALL )
{
if( stack.getMaxDamage() == 0 )
{
damage = stack.getItemDamage();
}
else
{
damage = stack.getMaxDamage();
}
}
else
{
final int breakpoint = fuzzy.calculateBreakPoint( stack.getMaxDamage() );
damage = stack.getItemDamage() <= breakpoint ? breakpoint : stack.getMaxDamage();
}
return new ItemDamageBound( damage );
}
/*
* Keep in mind that the stack order is from most damaged to least damaged, so this upper bound will actually be a
* lower number than the lower bound. It also is exclusive.
*/
static ItemDamageBound makeUpperBound(final ItemStack stack, final FuzzyMode fuzzy) {
Preconditions.checkState(stack.getItem().isDamageable(), "Item#isDamageable() has to be true");
int damage;
if (fuzzy == FuzzyMode.IGNORE_ALL) {
damage = MIN_DAMAGE_VALUE;
} else {
final int breakpoint = fuzzy.calculateBreakPoint(stack.getMaxDamage());
damage = stack.getItemDamage() <= breakpoint ? MIN_DAMAGE_VALUE : breakpoint;
}
return new ItemDamageBound(damage);
}
}
+164 -148
View File
@@ -1,6 +1,6 @@
/* /*
* This file is part of Applied Energistics 2. * This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2020, AlgorithmX2, All rights reserved. * Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
* *
* Applied Energistics 2 is free software: you can redistribute it and/or modify * Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@@ -18,196 +18,212 @@
package appeng.util.item; package appeng.util.item;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NavigableMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.ConcurrentSkipListMap;
import net.minecraft.item.Item; import net.minecraftforge.oredict.OreDictionary;
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import appeng.api.config.FuzzyMode; import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList; import appeng.api.storage.data.IItemList;
import appeng.util.item.AESharedItemStack.Bounds;
public final class ItemList implements IItemList<IAEItemStack> {
private final Reference2ObjectMap<Item, ItemVariantList> records = new Reference2ObjectOpenHashMap<>(); public final class ItemList implements IItemList<IAEItemStack>
/** {
* We increment this version field everytime an attempt to mutate this item list (or potentially one of its
* sub-lists) is made. Iterators will copy the version when they are created and compare it against the current
* version whenever they advance to trigger a {@link ConcurrentModificationException}.
*/
private final AtomicInteger version = new AtomicInteger(0);
@Override private final NavigableMap<AESharedItemStack, IAEItemStack> records = new ConcurrentSkipListMap<>();
public IAEItemStack findPrecise(final IAEItemStack itemStack) {
if (itemStack == null) {
return null;
}
ItemVariantList record = this.records.get(itemStack.getItem()); @Override
return record != null ? record.findPrecise(itemStack) : null; public void add( final IAEItemStack option )
} {
if( option == null )
{
return;
}
@Override final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
public Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) {
if (filter == null) {
return Collections.emptyList();
}
ItemVariantList record = this.records.get(filter.getItem()); if( st != null )
return record != null ? record.findFuzzy(filter, fuzzy) : Collections.emptyList(); {
} st.add( option );
return;
}
@Override final IAEItemStack opt = option.copy();
public boolean isEmpty() {
return !this.iterator().hasNext();
}
@Override this.putItemRecord( opt );
public void add(final IAEItemStack itemStack) { }
version.incrementAndGet();
if (itemStack == null) { @Override
return; public IAEItemStack findPrecise( final IAEItemStack itemStack )
} {
if( itemStack == null )
{
return null;
}
this.getOrCreateRecord(itemStack.getItem()).add(itemStack); return this.records.get( ( (AEItemStack) itemStack ).getSharedStack() );
} }
@Override @Override
public void addStorage(final IAEItemStack itemStack) { public Collection<IAEItemStack> findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy )
version.incrementAndGet(); {
if( filter == null )
{
return Collections.emptyList();
}
if (itemStack == null) { final AEItemStack ais = (AEItemStack) filter;
return;
}
this.getOrCreateRecord(itemStack.getItem()).addStorage(itemStack); return ais.getOre().map( or ->
} {
if( or.getAEEquivalents().size() == 1 )
{
final IAEItemStack is = or.getAEEquivalents().get( 0 );
@Override return this.findFuzzyDamage( is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE );
public void addCrafting(final IAEItemStack itemStack) { }
version.incrementAndGet(); else
{
final Collection<IAEItemStack> output = new ArrayList<>();
if (itemStack == null) { for( final IAEItemStack is : or.getAEEquivalents() )
return; {
} output.addAll( this.findFuzzyDamage( is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) );
}
this.getOrCreateRecord(itemStack.getItem()).addCrafting(itemStack); return output;
} }
} ).orElse( this.findFuzzyDamage( ais, fuzzy, false ) );
}
@Override @Override
public void addRequestable(final IAEItemStack itemStack) { public boolean isEmpty()
version.incrementAndGet(); {
return !this.iterator().hasNext();
}
if (itemStack == null) { @Override
return; public void addStorage( final IAEItemStack option )
} {
if( option == null )
{
return;
}
this.getOrCreateRecord(itemStack.getItem()).addRequestable(itemStack); final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
}
@Override if( st != null )
public IAEItemStack getFirstItem() { {
for (final IAEItemStack stackType : this) { st.incStackSize( option.getStackSize() );
return stackType; return;
} }
return null; final IAEItemStack opt = option.copy();
}
@Override this.putItemRecord( opt );
public int size() { }
int size = 0;
for (ItemVariantList entry : records.values()) {
size += entry.size();
}
return size; /*
} * public void clean() { Iterator<StackType> i = iterator(); while (i.hasNext()) { StackType AEI =
* i.next(); if ( !AEI.isMeaningful() ) i.remove(); } }
*/
@Override @Override
public Iterator<IAEItemStack> iterator() { public void addCrafting( final IAEItemStack option )
return new ChainedIterator(this.records.values().iterator(), version); {
} if( option == null )
{
return;
}
@Override final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
public void resetStatus() {
for (final IAEItemStack i : this) {
i.reset();
}
}
private ItemVariantList getOrCreateRecord(Item item) { if( st != null )
return this.records.computeIfAbsent(item, this::makeRecordMap); {
} st.setCraftable( true );
return;
}
private ItemVariantList makeRecordMap(Item item) { final IAEItemStack opt = option.copy();
if (item.isDamageable()) { opt.setStackSize( 0 );
return new FuzzyItemVariantList(); opt.setCraftable( true );
} else {
return new NormalItemVariantList();
}
}
/** this.putItemRecord( opt );
* Iterates over multiple item lists as if they were one list. }
*/
private static class ChainedIterator implements Iterator<IAEItemStack> {
private final AtomicInteger parentVersion; @Override
private final int version; public void addRequestable( final IAEItemStack option )
private final Iterator<ItemVariantList> parent; {
private Iterator<IAEItemStack> next; if( option == null )
{
return;
}
public ChainedIterator(Iterator<ItemVariantList> iterator, AtomicInteger parentVersion) { final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
this.parent = iterator;
this.parentVersion = parentVersion;
this.version = parentVersion.get();
this.ensureItems();
}
@Override if( st != null )
public boolean hasNext() { {
return next != null && next.hasNext(); st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() );
} return;
}
@Override final IAEItemStack opt = option.copy();
public IAEItemStack next() { opt.setStackSize( 0 );
if (this.next == null) { opt.setCraftable( false );
throw new NoSuchElementException(); opt.setCountRequestable( option.getCountRequestable() );
}
if (this.version != this.parentVersion.get()) {
throw new ConcurrentModificationException();
}
IAEItemStack result = this.next.next(); this.putItemRecord( opt );
this.ensureItems(); }
return result;
}
private void ensureItems() { @Override
if (hasNext()) { public IAEItemStack getFirstItem()
return; // Still items left in the current one {
} for( final IAEItemStack stackType : this )
{
return stackType;
}
// Find the next iterator willing to return some items... return null;
while (this.parent.hasNext()) { }
this.next = this.parent.next().iterator();
if (this.next.hasNext()) { @Override
return; // Found one! public int size()
} {
} return this.records.size();
}
// No more items @Override
this.next = null; public Iterator<IAEItemStack> iterator()
} {
} return new MeaningfulItemIterator<>( this.records.values().iterator() );
}
@Override
public void resetStatus()
{
for( final IAEItemStack i : this )
{
i.reset();
}
}
private IAEItemStack putItemRecord( final IAEItemStack itemStack )
{
return this.records.put( ( (AEItemStack) itemStack ).getSharedStack(), itemStack );
}
private Collection<IAEItemStack> findFuzzyDamage( final IAEItemStack filter, final FuzzyMode fuzzy, final boolean ignoreMeta )
{
final AEItemStack itemStack = (AEItemStack) filter;
final Bounds bounds = itemStack.getSharedStack().getBounds( fuzzy, ignoreMeta );
return this.records.subMap( bounds.lower(), true, bounds.upper(), true ).descendingMap().values();
}
} }
@@ -1,118 +0,0 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.util.item;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
/**
* Stores variants of a single type of {@link net.minecraft.item.Item}, i.e. versions with different durability, or
* different NBT or capabilities.
*/
abstract class ItemVariantList {
public void add(final IAEItemStack option) {
final IAEItemStack st = this.getRecords().get(((AEItemStack) option).getSharedStack());
if (st != null) {
st.add(option);
return;
}
final IAEItemStack opt = option.copy();
this.putItemRecord(opt);
}
public IAEItemStack findPrecise(final IAEItemStack itemStack) {
return this.getRecords().get(((AEItemStack) itemStack).getSharedStack());
}
public void addStorage(final IAEItemStack option) {
final IAEItemStack st = this.getRecords().get(((AEItemStack) option).getSharedStack());
if (st != null) {
st.incStackSize(option.getStackSize());
return;
}
final IAEItemStack opt = option.copy();
this.putItemRecord(opt);
}
public void addCrafting(final IAEItemStack option) {
final IAEItemStack st = this.getRecords().get(((AEItemStack) option).getSharedStack());
if (st != null) {
st.setCraftable(true);
return;
}
final IAEItemStack opt = option.copy();
opt.setStackSize(0);
opt.setCraftable(true);
this.putItemRecord(opt);
}
public void addRequestable(final IAEItemStack option) {
final IAEItemStack st = this.getRecords().get(((AEItemStack) option).getSharedStack());
if (st != null) {
st.setCountRequestable(st.getCountRequestable() + option.getCountRequestable());
return;
}
final IAEItemStack opt = option.copy();
opt.setStackSize(0);
opt.setCraftable(false);
opt.setCountRequestable(option.getCountRequestable());
this.putItemRecord(opt);
}
public int size() {
int size = 0;
for (IAEItemStack entry : getRecords().values()) {
if (entry.isMeaningful()) {
size++;
}
}
return size;
}
public Iterator<IAEItemStack> iterator() {
return new MeaningfulItemIterator<>(this.getRecords().values());
}
private void putItemRecord(final IAEItemStack itemStack) {
this.getRecords().put(((AEItemStack) itemStack).getSharedStack(), itemStack);
}
abstract Map<AESharedItemStack, IAEItemStack> getRecords();
public abstract Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy);
}
@@ -1,6 +1,6 @@
/* /*
* This file is part of Applied Energistics 2. * This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved. * Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
* *
* Applied Energistics 2 is free software: you can redistribute it and/or modify * Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by * it under the terms of the GNU Lesser General Public License as published by
@@ -18,53 +18,59 @@
package appeng.util.item; package appeng.util.item;
import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import appeng.api.storage.data.IAEItemStack; import appeng.api.storage.data.IAEItemStack;
/**
* This iterator will only return items from a collection that are meaningful (w.r.t.
* {@link IAEItemStack#isMeaningful()}. Items that are not meaningful are automatically removed from the collection as
* it is being iterated.
*/
public class MeaningfulItemIterator<T extends IAEItemStack> implements Iterator<T> {
private final Iterator<T> parent;
private T next;
public MeaningfulItemIterator(final Collection<T> collection) { public class MeaningfulItemIterator<T extends IAEItemStack> implements Iterator<T>
this.parent = collection.iterator(); {
this.next = seekNext();
}
@Override private final Iterator<T> parent;
public boolean hasNext() { private T next;
return this.next != null;
}
@Override public MeaningfulItemIterator( final Iterator<T> iterator )
public T next() { {
if (this.next == null) { this.parent = iterator;
throw new NoSuchElementException(); }
}
T result = this.next; @Override
this.next = this.seekNext(); public boolean hasNext()
return result; {
} while( this.parent.hasNext() )
{
this.next = this.parent.next();
private T seekNext() { if( this.next.isMeaningful() )
while (this.parent.hasNext()) { {
T item = this.parent.next(); return true;
}
else
{
this.parent.remove(); // self cleaning :3
}
}
if (item.isMeaningful()) { this.next = null;
return item; return false;
} else { }
this.parent.remove();
}
}
return null; @Override
} public T next()
{
if( this.next == null )
{
throw new NoSuchElementException();
}
return this.next;
}
@Override
public void remove()
{
this.parent.remove();
}
} }
@@ -1,51 +0,0 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2021, TeamAppliedEnergistics, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.util.item;
import java.util.Collection;
import java.util.Map;
import it.unimi.dsi.fastutil.objects.Reference2ObjectMap;
import it.unimi.dsi.fastutil.objects.Reference2ObjectOpenHashMap;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEItemStack;
/**
* This variant list is optimized for items that cannot be damaged and thus do not support querying durability ranges
* via {@link #findFuzzy(IAEItemStack, FuzzyMode)}.
*/
class NormalItemVariantList extends ItemVariantList {
private final Reference2ObjectMap<AESharedItemStack, IAEItemStack> records = new Reference2ObjectOpenHashMap<>();
@Override
Map<AESharedItemStack, IAEItemStack> getRecords() {
return this.records;
}
/**
* For items that do not support durability, we just return all variants to a fuzzy search.
*/
@Override
public Collection<IAEItemStack> findFuzzy(IAEItemStack filter, FuzzyMode fuzzy) {
return this.getRecords().values();
}
}
@@ -4,8 +4,8 @@
"type": "forge:and", "type": "forge:and",
"values": [ "values": [
{ {
"type": "appliedenergistics2:part_exists", "type": "minecraft:item_exists",
"part": "part.terminal" "item": "appliedenergistics2:part:part.terminal"
}, },
{ {
"type": "appliedenergistics2:material_exists", "type": "appliedenergistics2:material_exists",