Compare commits

...

39 Commits

Author SHA1 Message Date
Salomão d48c24a2e1 avoid relaying changes if theres no one listening to the passthrough 2021-07-05 19:56:41 -03:00
Salomão b6eef99312 Merge branch '111' into AE2-Omnifactory 2021-07-05 16:51:14 -03:00
Salomão decb869011 reworked propagation of item/fluid changes on the network 2021-07-05 16:49:52 -03:00
Salomão 5877fd2def Merge branch 'fluid-terminal-multiple-containers' into AE2-Omnifactory 2021-07-04 10:30:16 -03:00
Salomão df08ce0513 Fluid terminal is now able to fill/empty stacked tanks 2021-07-04 10:28:36 -03:00
Salomão f9c274fb48 Reduce power flickering by increasing energy polling rate
in testing 84 dense cells could sustain MAX Integer on a FE p2p pair
2021-06-27 23:17:26 -03:00
Salomão 3582582e3f fix off-by-one voiding patterns when removing expansion cards 2021-06-26 10:25:47 -03:00
Salomão 6de48f8541 fixes #34
getAllIngredients() can contain nulls
2021-06-26 07:31:16 -03:00
Salomão 5a2c2d06d3 make pattern expansion recipe shapeless 2021-06-24 22:34:21 -03:00
Salomão 98d3cafdfd Merge branch 'oredictfixes' into AE2-Omnifactory 2021-06-23 10:19:02 -03:00
Salomão 904de49543 wip
fix substitution crafting, for real this time
wip 2


wip. still has NBT issues


fix semantic changes


fix interface with free slots on interface terminal


Auto stash before cherry pick of "fix interface with free slots on interface terminal"
2021-06-23 10:16:59 -03:00
Salomão b0772bf94c backport 223163aa0a
fixes #32
2021-06-21 22:48:25 -03:00
Salomão aa5d5e3623 set idle power usage of expanded interface to a power of four 2021-06-21 16:25:26 -03:00
Salomão 42f4ef2855 tweak GUIs 2021-06-21 15:54:40 -03:00
Salomão 3eb2582f29 Merge branch 'bigger-interfaces' into AE2-Omnifactory 2021-06-21 15:22:13 -03:00
Salomão 307f86ded8 increase AE energy polling rate from once every 90 to once every 3 ticks 2021-06-18 12:48:01 -03:00
Salomão 56f57e18a5 Merge branch 'wip' into AE2-Omnifactory 2021-06-17 23:32:34 -03:00
Salomão eab695b692 try to not void fluids in fluid terminal when running out of power 2021-06-17 23:32:16 -03:00
Salomão 0fb393820b half-undo wip 2021-06-17 00:07:06 -03:00
Salomão 01fe5c7a8b jei transfer tweaks..again 2021-06-16 19:22:52 -03:00
Salomão 8468b47443 workaround for damaged tools and gtce tools not being set as damageable 2021-06-15 12:46:44 -03:00
Salomão 6cb583c918 clear old NBT from cells 2021-06-15 12:41:51 -03:00
Salomão d69395a117 cache fixes 2021-06-14 12:57:49 -03:00
Salomão 59effe8131 save NBT properly 2021-06-14 11:51:17 -03:00
Salomão 6f42876963 Merge branch 'fastutil' into AE2-Omnifactory 2021-06-14 10:54:12 -03:00
Salomão 08952b48dd backported fastutil implementation of the item list 2021-06-14 10:53:50 -03:00
Salomão e3c9c4ce65 clear cells of craftable status
remove unsupported removal call
2021-06-14 10:20:58 -03:00
Salomão 7b91da58c0 resolve suspicious calls 2021-06-14 02:33:43 -03:00
Salomão 26c06bca15 fix IO-Port copying craftable boolean 2021-06-14 02:33:23 -03:00
Salomão 4458bd28ab refresh ETA not only when items are crafted 2021-06-13 20:30:52 -03:00
Salomão df3f00d978 try to fix remaining concurrent modifications to energy grid 2021-06-13 20:29:56 -03:00
Salomão 18ae994ee4 try to avoid CME by copying FE p2p outputs before iterating
backported 1c88ea7b78 and attempt to fix #25 with feedback
2021-06-10 21:13:41 -03:00
Salomão 47888b5546 reworked Adapter caches ( storage busses ) 2021-06-09 16:31:49 -03:00
Salomão e18593feb5 fix pattern inventory size mismatch 2021-06-08 23:46:37 -03:00
Salomão af4c3de55e fix client desync 2021-06-08 23:23:12 -03:00
Salomão bea29331a3 implement pattern expansion cards for interfaces
Maximum of 4 rows
Uses 4x the previous tier for crafting operations (4 rows = 64 interfaces consumption)
2021-06-08 23:23:12 -03:00
Salomão 9b9579b358 storage drawer cache optimisation 2021-06-08 23:22:00 -03:00
Salomão 52da4f9528 fix shift-clicking patterns from pattern slot sometimes voiding them 2021-06-05 18:54:26 -03:00
Salomão 50aac2c768 send the player a message if the crafting job succeeds on simulation
but fails on real extraction
2021-06-02 23:46:35 -03:00
76 changed files with 2454 additions and 1857 deletions
+1 -1
View File
@@ -3,7 +3,7 @@ aechannel=stable
aebuild=7
aegroup=appeng
aebasename=appliedenergistics2
trousers=omni-fixes-v21b
trousers=omni-fixes-v44
#########################################################
# Versions #
+1 -1
View File
@@ -80,7 +80,7 @@ configurations {
}
dependencies {
compileOnly "gregtechce:gregtech:1.12.2:1.12.0.662"
compileOnly "gregtechce:gregtech:1.12.2:1.15.1.735"
// installable runtime dependencies
mods "mcp.mobius.waila:Hwyla:${hwyla_version}"
+2 -1
View File
@@ -46,7 +46,8 @@ public enum Upgrades
*/
FUZZY( 1 ),
SPEED( 1 ),
INVERTER( 1 );
INVERTER( 1 ),
PATTERN_EXPANSION(1);
private final int tier;
private final Map<ItemStack, Integer> supportedMax = new HashMap<>();
@@ -89,6 +89,8 @@ public interface IMaterials
IItemDefinition cardCapacity();
IItemDefinition cardPatternExpansion();
IItemDefinition cardFuzzy();
IItemDefinition cardInverter();
@@ -31,6 +31,9 @@ import net.minecraft.world.World;
import appeng.api.implementations.ICraftingPatternItem;
import appeng.api.storage.data.IAEItemStack;
import java.util.Collections;
import java.util.List;
/**
* do not implement provided by {@link ICraftingPatternItem}
@@ -84,6 +87,11 @@ public interface ICraftingPatternDetails
*/
boolean canSubstitute();
default List<IAEItemStack> getSubstituteInputs( int slot )
{
return Collections.emptyList();
}
/**
* Allow using this INSTANCE of the pattern details to preform the crafting action with performance enhancements.
*
@@ -44,11 +44,8 @@ public interface IStackWatcherHost
/**
* Called when a watched item changes amounts.
*
* @param o changed item list
* @param fullStack old stack
* @param diffStack new stack
* @param src action source
* @param chan storage channel
*/
void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan );
void onStackChange( IAEStack<?> diffStack, IStorageChannel<?> chan );
}
@@ -52,4 +52,9 @@ public interface IMEMonitorHandlerReceiver<T extends IAEStack<T>>
* called when the list updates its contents, this is mostly for handling power events.
*/
void onListUpdate();
default boolean hasListeners()
{
return true;
}
}
@@ -112,4 +112,13 @@ public interface IAEItemStack extends IAEStack<IAEItemStack>
* @return definition stack
*/
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);
}
@@ -50,7 +50,7 @@ public class GuiInterface extends GuiUpgradeable
public GuiInterface( final InventoryPlayer inventoryPlayer, final IInterfaceHost te )
{
super( new ContainerInterface( inventoryPlayer, te ) );
this.ySize = 211;
this.ySize = 256;
}
@Override
@@ -62,8 +62,7 @@ public class GuiInterface extends GuiUpgradeable
this.BlockMode = new GuiImgButton( this.guiLeft - 18, this.guiTop + 8, Settings.BLOCK, YesNo.NO );
this.buttonList.add( this.BlockMode );
this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal
.getLocal(), GuiText.InterfaceTerminalHint.getLocal() );
this.interfaceMode = new GuiToggleButton( this.guiLeft - 18, this.guiTop + 26, 84, 85, GuiText.InterfaceTerminal.getLocal(), GuiText.InterfaceTerminalHint.getLocal() );
this.buttonList.add( this.interfaceMode );
}
@@ -86,13 +85,20 @@ public class GuiInterface extends GuiUpgradeable
this.fontRenderer.drawString( GuiText.StoredItems.getLocal(), 8, 6 + 60 + 7, 4210752 );
this.fontRenderer.drawString( GuiText.Patterns.getLocal(), 8, 6 + 73 + 7, 4210752 );
this.fontRenderer.drawString( GuiText.inventory.getLocal(), 8, this.ySize - 96 + 3, 4210752 );
}
@Override
protected String getBackground()
{
return "guis/interface.png";
int upgrades = ( (ContainerInterface) this.cvb ).getPatternUpgrades();
if( upgrades == 0 )
{
return "guis/newinterface.png";
}
else
{
return "guis/newinterface" + upgrades + ".png";
}
}
@Override
@@ -117,4 +123,5 @@ public class GuiInterface extends GuiUpgradeable
NetworkHandler.instance().sendToServer( new PacketConfigButton( this.BlockMode.getSetting(), backwards ) );
}
}
}
@@ -24,8 +24,13 @@ import java.util.*;
import appeng.api.config.ActionItems;
import appeng.api.config.Settings;
import appeng.api.config.Upgrades;
import appeng.client.gui.widgets.GuiImgButton;
import appeng.core.worlddata.IWorldPlayerMapping;
import appeng.helpers.DualityInterface;
import appeng.parts.misc.PartInterface;
import appeng.tile.inventory.AppEngInternalInventory;
import appeng.tile.misc.TileInterface;
import appeng.util.BlockPosUtils;
import com.google.common.collect.HashMultimap;
@@ -69,6 +74,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
private final HashMultimap<String, ClientDCInternalInv> byName = HashMultimap.create();
private final HashMap<ClientDCInternalInv,BlockPos> blockPosHashMap = new HashMap<>();
private final HashMap<GuiButton,ClientDCInternalInv> guiButtonHashMap = new HashMap<>();
private final Map<ClientDCInternalInv,Integer> numUpgradesMap = new HashMap<>();
private final ArrayList<String> names = new ArrayList<>();
private final ArrayList<Object> lines = new ArrayList<>();
private final Set<Object> matchedStacks = new HashSet<>();
@@ -91,7 +97,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
final GuiScrollbar scrollbar = new GuiScrollbar();
this.setScrollBar( scrollbar );
this.xSize = 208;
this.ySize = 256;
this.ySize = 255;
}
@Override
@@ -136,36 +142,43 @@ public class GuiInterfaceTerminal extends AEBaseGui
this.fontRenderer.drawString( this.getGuiDisplayName( GuiText.InterfaceTerminal.getLocal() ), 8, 6, 4210752 );
this.fontRenderer.drawString( GuiText.inventory.getLocal(), this.offsetX + 2, this.ySize - 96 + 3, 4210752 );
final int ex = this.getScrollBar().getCurrentScroll();
final int currentScroll = this.getScrollBar().getCurrentScroll();
this.guiButtonNextAssembler = new GuiImgButton(guiLeft + 123, guiTop + 25,Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT);
this.guiButtonNextAssembler = new GuiImgButton( guiLeft + 123, guiTop + 25, Settings.ACTIONS, ActionItems.FREE_MOLECULAR_SLOT_SHORTCUT );
this.buttonList.add( guiButtonNextAssembler );
guiButtonHide = new GuiImgButton( guiLeft + 141, guiTop + 25,Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ?
ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF :
ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON);
guiButtonHide = new GuiImgButton( guiLeft + 141, guiTop + 25, Settings.ACTIONS, this.partInterfaceTerminal.onlyInterfacesWithFreeSlots ? ActionItems.TOGGLE_SHOW_FULL_INTERFACES_OFF : ActionItems.TOGGLE_SHOW_FULL_INTERFACES_ON );
this.buttonList.add( guiButtonHide );
this.inventorySlots.inventorySlots.removeIf( slot -> slot instanceof SlotDisconnected );
int offset = 51;
for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ )
int offset = 52;
int linesDraw = 0;
for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && currentScroll + x < this.lines.size(); x++ )
{
final Object lineObj = this.lines.get( ex + x );
final Object lineObj = this.lines.get( currentScroll + x );
if( lineObj instanceof ClientDCInternalInv )
{
final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj;
for( int z = 0; z < inv.getInventory().getSlots(); z++ )
{
this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z, z * 18 + 22, 1 + offset ) );
if (this.matchedStacks.contains(inv.getInventory().getStackInSlot(z)))
drawRect( z * 18 + 22, 1 + offset, z * 18 + 22 + 16, 1 + offset + 16, 0x2A00FF00 );
}
GuiButton guiButton = new GuiImgButton(guiLeft + 4, guiTop + offset + 1, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE);
guiButtonHashMap.put( guiButton , inv);
GuiButton guiButton = new GuiImgButton( guiLeft + 4, guiTop + offset, Settings.ACTIONS, ActionItems.HIGHLIGHT_INTERFACE );
guiButtonHashMap.put( guiButton, inv );
this.buttonList.add( guiButton );
int extraLines = numUpgradesMap.get( inv );
for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE ; ++row )
{
for( int z = 0; z < 9 ; z++ )
{
this.inventorySlots.inventorySlots.add( new SlotDisconnected( inv, z + ( row * 9 ), ( z * 18 + 22 ), offset ) );
if( this.matchedStacks.contains( inv.getInventory().getStackInSlot( z + ( row * 9 ) ) ) )
{
drawRect( z * 18 + 22, offset, z * 18 + 22 + 16, offset + 16, 0x2A00FF00 );
}
}
linesDraw++;
offset += 18;
}
}
else if( lineObj instanceof String )
{
@@ -176,17 +189,17 @@ public class GuiInterfaceTerminal extends AEBaseGui
name = name + " (" + rows + ')';
}
while( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 )
while ( name.length() > 2 && this.fontRenderer.getStringWidth( name ) > 155 )
{
name = name.substring( 0, name.length() - 1 );
}
this.fontRenderer.drawString( name, this.offsetX + 2, 6 + offset, 4210752 );
this.fontRenderer.drawString( name, this.offsetX + 2, 5 + offset, 4210752 );
linesDraw++;
offset += 18;
}
offset += 18;
}
if( searchFieldInputs.isMouseIn( mouseX , mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" );
if( searchFieldInputs.isMouseIn( mouseX, mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Inputs OR names" );
else if( searchFieldOutputs.isMouseIn( mouseX, mouseY ) ) drawTooltip( Mouse.getEventX() * this.width / this.mc.displayWidth - offsetX, mouseY - guiTop, "Outputs OR names" );
}
@@ -264,19 +277,28 @@ public class GuiInterfaceTerminal extends AEBaseGui
int offset = 51;
final int ex = this.getScrollBar().getCurrentScroll();
for( int x = 0; x < LINES_ON_PAGE && ex + x < this.lines.size(); x++ )
int linesDraw = 0;
for( int x = 0; x < LINES_ON_PAGE && linesDraw < LINES_ON_PAGE && ex + x < this.lines.size(); x++ )
{
final Object lineObj = this.lines.get( ex + x );
if( lineObj instanceof ClientDCInternalInv )
{
final ClientDCInternalInv inv = (ClientDCInternalInv) lineObj;
GlStateManager.color( 1, 1, 1, 1 );
final int width = inv.getInventory().getSlots() * 18;
this.drawTexturedModalRect( offsetX + 20, offsetY + offset, 20, 173, width, 18 );
final int width = 9 * 18;
int extraLines = numUpgradesMap.get( lineObj );
for( int row = 0; row < 1 + extraLines && linesDraw < LINES_ON_PAGE; ++row )
{
this.drawTexturedModalRect( offsetX + 20, offsetY + offset , 20, 173, width, 18 );
offset += 18;
linesDraw++;
}
}
else {
offset += 18;
linesDraw++;
}
offset += 18;
}
if( this.searchFieldInputs != null )
@@ -337,6 +359,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
final ClientDCInternalInv current = this.getById( id, invData.getLong( "sortBy" ), invData.getString( "un" ) );
blockPosHashMap.put( current, NBTUtil.getPosFromTag( invData.getCompoundTag( "pos" )) );
dimHashMap.put( current, invData.getInteger( "dim" ));
numUpgradesMap.put( current, invData.getInteger("numUpgrades"));
for( int x = 0; x < current.getInventory().getSlots(); x++ )
{
@@ -395,8 +418,12 @@ public class GuiInterfaceTerminal extends AEBaseGui
// Search if the current inventory holds a pattern containing the search term.
if( !found )
{
int slot = 0;
for( final ItemStack itemStack : entry.getInventory() )
{
if (slot > 8 + numUpgradesMap.get(entry) * 9) {
break;
}
if( !searchFieldInputs.isEmpty() && !searchFieldOutputs.isEmpty() ) {
if (this.itemStackMatchesSearchTerm(itemStack, searchFieldInputs, 0) || this.itemStackMatchesSearchTerm(itemStack, searchFieldOutputs, 1)) {
found = true;
@@ -418,6 +445,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
// If only Interfaces with empty slots should be shown, check that here
if(itemStack.isEmpty())
interfaceHasFreeSlots = true;
slot++;
}
}
// if found, filter skipped or machine name matching the search term, add it
@@ -458,7 +486,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
this.lines.addAll( clientInventories );
}
this.getScrollBar().setRange( 0, this.lines.size() - LINES_ON_PAGE, 2 );
this.getScrollBar().setRange( 0, this.lines.size() - 1, 1 );
}
private boolean itemStackMatchesSearchTerm( final ItemStack itemStack, final String searchTerm,int pass )
@@ -548,7 +576,7 @@ public class GuiInterfaceTerminal extends AEBaseGui
if( o == null )
{
this.byId.put( id, o = new ClientDCInternalInv( 9, id, sortBy, string ) );
this.byId.put( id, o = new ClientDCInternalInv( DualityInterface.NUMBER_OF_PATTERN_SLOTS, id, sortBy, string ) );
this.refreshList = true;
}
@@ -159,56 +159,58 @@ public class ContainerCraftingCPU extends AEBaseContainer implements IMEMonitorH
@Override
public void detectAndSendChanges()
{
if( Platform.isServer() && this.getMonitor() != null && !this.list.isEmpty() )
if( Platform.isServer() && this.getMonitor() != null )
{
try
if( this.getEstimatedTime() >= 0 )
{
if( this.getEstimatedTime() >= 0 )
final long elapsedTime = this.getMonitor().getElapsedTime();
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 long elapsedTime = this.getMonitor().getElapsedTime();
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 );
}
final PacketMEInventoryUpdate a = new PacketMEInventoryUpdate( (byte) 0 );
final PacketMEInventoryUpdate b = new PacketMEInventoryUpdate( (byte) 1 );
final PacketMEInventoryUpdate c = new PacketMEInventoryUpdate( (byte) 2 );
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 )
for( final IAEItemStack out : this.list )
{
if( !a.isEmpty() )
{
NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g );
}
a.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.STORAGE ) );
b.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.ACTIVE ) );
c.appendItem( this.getMonitor().getItemStack( out, CraftingItemList.PENDING ) );
}
if( !b.isEmpty() )
{
NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g );
}
this.list.resetStatus();
if( !c.isEmpty() )
for( final Object g : this.listeners )
{
if( g instanceof EntityPlayer )
{
NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g );
if( !a.isEmpty() )
{
NetworkHandler.instance().sendTo( a, (EntityPlayerMP) g );
}
if( !b.isEmpty() )
{
NetworkHandler.instance().sendTo( b, (EntityPlayerMP) g );
}
if( !c.isEmpty() )
{
NetworkHandler.instance().sendTo( c, (EntityPlayerMP) g );
}
}
}
}
}
catch( final IOException e )
{
// :P
catch( final IOException e )
{
// :P
}
}
}
super.detectAndSendChanges();
@@ -19,6 +19,9 @@
package appeng.container.implementations;
import appeng.api.config.Upgrades;
import appeng.container.slot.*;
import appeng.util.Platform;
import net.minecraft.entity.player.InventoryPlayer;
import appeng.api.config.SecurityPermissions;
@@ -26,14 +29,11 @@ import appeng.api.config.Settings;
import appeng.api.config.YesNo;
import appeng.api.util.IConfigManager;
import appeng.container.guisync.GuiSync;
import appeng.container.slot.SlotFake;
import appeng.container.slot.SlotNormal;
import appeng.container.slot.SlotRestrictedInput;
import appeng.helpers.DualityInterface;
import appeng.helpers.IInterfaceHost;
public class ContainerInterface extends ContainerUpgradeable
public class ContainerInterface extends ContainerUpgradeable implements IOptionalSlotHost
{
private final DualityInterface myDuality;
@@ -44,16 +44,22 @@ public class ContainerInterface extends ContainerUpgradeable
@GuiSync( 4 )
public YesNo iTermMode = YesNo.YES;
@GuiSync( 7 )
public int patternExpansions = 0;
public ContainerInterface( final InventoryPlayer ip, final IInterfaceHost te )
{
super( ip, te.getInterfaceDuality().getHost() );
this.myDuality = te.getInterfaceDuality();
for( int x = 0; x < DualityInterface.NUMBER_OF_PATTERN_SLOTS; x++ )
for (int row = 0 ; row < 4 ; ++row)
{
this.addSlotToContainer( new SlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality
.getPatterns(), x, 8 + 18 * x, 90 + 7, this.getInventoryPlayer() ).setStackLimit( 1 ) );
for( int x = 0; x < 9; x++ )
{
this.addSlotToContainer( new OptionalSlotRestrictedInput( SlotRestrictedInput.PlacableItemType.ENCODED_PATTERN, this.myDuality
.getPatterns(), this, x + row * 9, 8 + 18 * x, 97 + ( 18 * row ), row, this.getInventoryPlayer() ).setStackLimit( 1 ) );
}
}
for( int x = 0; x < DualityInterface.NUMBER_OF_CONFIG_SLOTS; x++ )
@@ -70,7 +76,7 @@ public class ContainerInterface extends ContainerUpgradeable
@Override
protected int getHeight()
{
return 211;
return 256;
}
@Override
@@ -82,16 +88,35 @@ public class ContainerInterface extends ContainerUpgradeable
@Override
public int availableUpgrades()
{
return 1;
return 4;
}
@Override
public boolean isSlotEnabled( final int idx )
{
return myDuality.getInstalledUpgrades(Upgrades.PATTERN_EXPANSION) >= idx;
}
@Override
public void detectAndSendChanges()
{
this.verifyPermissions( SecurityPermissions.BUILD, false );
if (patternExpansions != getPatternUpgrades())
{
patternExpansions = getPatternUpgrades();
this.myDuality.dropExcessPatterns();
}
super.detectAndSendChanges();
}
@Override
public void onUpdate( final String field, final Object oldValue, final Object newValue ) {
super.onUpdate(field, oldValue, newValue);
if ( Platform.isClient() && field.equals("patternExpansions"))
this.myDuality.dropExcessPatterns();
}
@Override
protected void loadSettingsFromHost( final IConfigManager cm )
{
@@ -118,4 +143,9 @@ public class ContainerInterface extends ContainerUpgradeable
{
this.iTermMode = iTermMode;
}
public int getPatternUpgrades()
{
return this.myDuality.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION );
}
}
@@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import appeng.api.config.Upgrades;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
@@ -405,6 +406,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
tag.setString( "un", inv.unlocalizedName );
tag.setTag( "pos", NBTUtil.createPosTag( inv.pos ) );
tag.setInteger( "dim", inv.dim );
tag.setInteger( "numUpgrades", inv.numUpgrades );
}
for( int x = 0; x < length; x++ )
@@ -437,6 +439,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
private final IItemHandler server;
private final BlockPos pos;
private final int dim;
private final int numUpgrades;
public InvTracker( final DualityInterface dual, final IItemHandler patterns, final String unlocalizedName )
{
@@ -446,6 +449,7 @@ public final class ContainerInterfaceTerminal extends AEBaseContainer
this.sortBy = dual.getSortValue();
this.pos = dual.getLocation().getPos();
this.dim = dual.getLocation().getWorld().provider.getDimension();
this.numUpgrades = dual.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION);
}
}
@@ -134,14 +134,16 @@ public class ContainerPatternTerm extends ContainerMEMonitorable implements IAEA
{
return ItemStack.EMPTY;
}
final AppEngSlot clickSlot = ( AppEngSlot ) this.inventorySlots.get( idx ); // require AE SLots!
ItemStack itemStack = clickSlot.getStack();
if( AEApi.instance().definitions().materials().blankPattern().isSameAs( itemStack ) )
if( this.inventorySlots.get( idx ) instanceof SlotPlayerInv || this.inventorySlots.get( idx ) instanceof SlotPlayerHotBar )
{
IItemHandler patternInv = this.getPatternTerminal().getInventoryByName( "pattern" );
ItemStack remainder = patternInv.insertItem( 0, itemStack, false );
clickSlot.putStack( remainder );
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 );
}
@@ -157,7 +157,7 @@ public class AppEngSlot extends Slot
{
if( this.isSlotEnabled() )
{
return !this.itemHandler.extractItem( this.index, 1, true ).isEmpty();
return !this.itemHandler.extractItem( this.index, Integer.MAX_VALUE, true ).isEmpty();
}
return false;
}
@@ -363,6 +363,8 @@ final class Registration
// Interface
Upgrades.CRAFTING.registerItem( parts.iface(), 1 );
Upgrades.CRAFTING.registerItem( blocks.iface(), 1 );
Upgrades.PATTERN_EXPANSION.registerItem( parts.iface(), 3 );
Upgrades.PATTERN_EXPANSION.registerItem( blocks.iface(), 3 );
// IO Port!
Upgrades.SPEED.registerItem( blocks.iOPort(), 3 );
@@ -175,7 +175,7 @@ public class ApiStorage implements IStorageHelper
@Override
public int transferFactor()
{
return 125;
return 1000;
}
@Override
@@ -86,6 +86,7 @@ public final class ApiMaterials implements IMaterials
private final IItemDefinition cardRedstone;
private final IItemDefinition cardSpeed;
private final IItemDefinition cardCapacity;
private final IItemDefinition cardPatternExpansion;
private final IItemDefinition cardFuzzy;
private final IItemDefinition cardInverter;
private final IItemDefinition cardCrafting;
@@ -204,6 +205,7 @@ public final class ApiMaterials implements IMaterials
this.cardRedstone = new DamagedItemDefinition( "material.card.redstone", materials.createMaterial( MaterialType.CARD_REDSTONE ) );
this.cardSpeed = new DamagedItemDefinition( "material.card.acceleration", materials.createMaterial( MaterialType.CARD_SPEED ) );
this.cardCapacity = new DamagedItemDefinition( "material.card.capacity", materials.createMaterial( MaterialType.CARD_CAPACITY ) );
this.cardPatternExpansion = new DamagedItemDefinition( "material.card.pattern.expansion", materials.createMaterial(MaterialType.CARD_PATTERN_EXPANSION) );
this.cardFuzzy = new DamagedItemDefinition( "material.card.fuzzy", materials.createMaterial( MaterialType.CARD_FUZZY ) );
this.cardInverter = new DamagedItemDefinition( "material.card.inverter", materials.createMaterial( MaterialType.CARD_INVERTER ) );
this.cardCrafting = new DamagedItemDefinition( "material.card.crafting", materials.createMaterial( MaterialType.CARD_CRAFTING ) );
@@ -424,6 +426,9 @@ public final class ApiMaterials implements IMaterials
return this.cardCapacity;
}
@Override
public IItemDefinition cardPatternExpansion(){ return this.cardPatternExpansion;}
@Override
public IItemDefinition cardFuzzy()
{
@@ -29,6 +29,7 @@ import java.util.Iterator;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IItemList;
import appeng.container.implementations.ContainerPatternTerm;
import gregtech.common.items.MetaTool;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@@ -211,23 +212,21 @@ public class PacketJEIRecipe extends AppEngPacket
out = Platform.poweredExtraction( energy, storage, request, cct.getActionSource() );
if( out == null )
{
Collection<IAEItemStack> outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL );
IAEItemStack mostDamaged = null;
for( IAEItemStack is : outList )
if( request.getItem().isDamageable() || ( Platform.isModLoaded( "gregtech" ) && request.getItem() instanceof MetaTool ) )
{
if( !is.isCraftable() )
Collection<IAEItemStack> outList = inv.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).getStorageList().findFuzzy( request, FuzzyMode.IGNORE_ALL );
for( IAEItemStack is : outList )
{
if( mostDamaged == null || mostDamaged.getItemDamage() < is.getItemDamage() )
if( is.getDefinition().getMetadata() == request.getDefinition().getMetadata() )
{
mostDamaged = is;
out = Platform.poweredExtraction( energy, storage, is.copy().setStackSize( 1 ), cct.getActionSource() );
}
if( out != null )
{
break;
}
}
}
if( mostDamaged != null )
{
mostDamaged.setStackSize( 1 );
out = Platform.poweredExtraction( energy, storage, mostDamaged, cct.getActionSource() );
}
}
}
else
@@ -130,7 +130,12 @@ public class CraftingTreeNode
if( this.parent.details.canSubstitute() )
{
itemList = inventoryList.findFuzzy( this.what, FuzzyMode.IGNORE_ALL );
final List<IAEItemStack> substitutes = this.parent.details.getSubstituteInputs(this.slot);
itemList = new ArrayList<>(substitutes.size());
for (IAEItemStack stack : substitutes) {
itemList.addAll(inventoryList.findFuzzy(stack, FuzzyMode.IGNORE_ALL));
}
}
else
{
@@ -305,7 +305,7 @@ public class CraftingTreeProcess
void getPlan( final IItemList<IAEItemStack> plan )
{
for( IAEItemStack i : this.details.getOutputs() )
for( IAEItemStack i : this.details.getCondensedOutputs() )
{
i = i.copy();
i.setCountRequestable( i.getStackSize() * this.crafts );
@@ -28,7 +28,9 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.me.helpers.PlayerSource;
import appeng.util.inv.ItemListIgnoreCrafting;
import net.minecraft.util.text.TextComponentString;
public class MECraftingInventory implements IMEInventory<IAEItemStack>
@@ -307,8 +309,15 @@ public class MECraftingInventory implements IMEInventory<IAEItemStack>
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;
break;
if( !src.player().isPresent() ) break;
}
}
}
@@ -24,6 +24,9 @@ import java.nio.BufferOverflowException;
import javax.annotation.Nonnull;
import appeng.container.slot.AppEngSlot;
import appeng.container.slot.SlotPlayerHotBar;
import appeng.container.slot.SlotPlayerInv;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
@@ -70,6 +73,7 @@ import appeng.me.helpers.ChannelPowerSrc;
import appeng.util.ConfigManager;
import appeng.util.IConfigManagerHost;
import appeng.util.Platform;
import net.minecraftforge.items.IItemHandler;
/**
@@ -342,6 +346,89 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
}
}
@Override
public ItemStack transferStackInSlot( final EntityPlayer p, final int idx )
{
if( Platform.isClient() )
{
return ItemStack.EMPTY;
}
EntityPlayerMP player = (EntityPlayerMP) p;
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();
ItemStack copy = itemStack.copy();
copy.setCount( 1 );
IFluidHandlerItem fh = FluidUtil.getFluidHandler( copy );
if( fh == null )
{
// only fluid handlers items
return ItemStack.EMPTY;
}
int heldAmount = itemStack.getCount();
for( int i = 0; i < heldAmount; i++ )
{
copy = itemStack.copy();
copy.setCount( 1 );
fh = FluidUtil.getFluidHandler( copy );
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
return ItemStack.EMPTY;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
{
return ItemStack.EMPTY;
}
else
{
extract.amount = storable.amount;
}
}
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
{
IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() );
if( spill != null && spill.getStackSize() > 0 )
{
fh.fill( spill.getFluidStack(), true );
}
}
if( notInserted == null )
{
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
clickSlot.decrStackSize( 1 );
}
}
this.detectAndSendChanges();
return ItemStack.EMPTY;
}
return super.transferStackInSlot( p, idx );
}
@Override
public void doAction( EntityPlayerMP player, InventoryAction action, int slot, long id )
{
@@ -352,13 +439,9 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
}
final ItemStack held = player.inventory.getItemStack();
if( held.getCount() != 1 )
{
// only support stacksize 1 for now
return;
}
final IFluidHandlerItem fh = FluidUtil.getFluidHandler( held );
ItemStack heldCopy = held.copy();
heldCopy.setCount( 1 );
IFluidHandlerItem fh = FluidUtil.getFluidHandler( heldCopy );
if( fh == null )
{
// only fluid handlers items
@@ -372,84 +455,122 @@ public class ContainerFluidTerminal extends AEBaseContainer implements IConfigMa
// Check how much we can store in the item
stack.setStackSize( Integer.MAX_VALUE );
int amountAllowed = fh.fill( stack.getFluidStack(), false );
stack.setStackSize( amountAllowed );
// Check if we can pull out of the system
final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack, this.getActionSource(), Actionable.SIMULATE );
if( canPull == null || canPull.getStackSize() < 1 )
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
return;
}
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
// How much could fit into the container
final int canFill = fh.fill( canPull.getFluidStack(), false );
if( canFill == 0 )
{
return;
}
// Now actually pull out of the system
stack.setStackSize( canFill );
final IAEFluidStack pulled = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack, this.getActionSource() );
if( pulled == null || pulled.getStackSize() < 1 )
{
// Something went wrong
AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " );
return;
}
// Actually fill
final int used = fh.fill( pulled.getFluidStack(), true );
if( used != canFill )
{
AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() );
}
player.inventory.setItemStack( fh.getContainer() );
this.updateHeld( player );
}
else if( action == InventoryAction.EMPTY_ITEM )
{
// See how much we can drain from the item
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
return;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ),
this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
// Check if we can pull out of the system
final IAEFluidStack canPull = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( amountAllowed ), this.getActionSource(), Actionable.SIMULATE );
if( canPull == null || canPull.getStackSize() < 1 )
{
return;
}
// How much could fit into the container
final int canFill = fh.fill( canPull.getFluidStack(), false );
if( canFill == 0 )
{
return;
}
// Now actually pull out of the system
final IAEFluidStack pulled = Platform.poweredExtraction( this.getPowerSource(), this.monitor, stack.setStackSize( canFill ), this.getActionSource() );
if( pulled == null || pulled.getStackSize() < 1 )
{
// Something went wrong
AELog.error( "Unable to pull fluid out of the ME system even though the simulation said yes " );
return;
}
// Actually fill
final int used = fh.fill( pulled.getFluidStack(), true );
if( used != canFill )
{
AELog.error( "Fluid item [%s] reported a different possible amount than it actually accepted.", held.getDisplayName() );
}
if( held.getCount() == 1 )
{
player.inventory.setItemStack( fh.getContainer() );
}
else
{
extract.amount = storable.amount;
player.inventory.getItemStack().shrink( 1 );
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
}
}
this.updateHeld( player );
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ),
this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
}
else if( action == InventoryAction.EMPTY_ITEM )
{
int heldAmount = held.getCount();
for( int i = 0; i < heldAmount; i++ )
{
AELog.error( "Fluid item [%s] reported a different possible amount to drain than it actually provided.", held.getDisplayName() );
}
ItemStack copiedFluidContainer = held.copy();
copiedFluidContainer.setCount( 1 );
fh = FluidUtil.getFluidHandler( copiedFluidContainer );
player.inventory.setItemStack( fh.getContainer() );
// See how much we can drain from the item
final FluidStack extract = fh.drain( Integer.MAX_VALUE, false );
if( extract == null || extract.amount < 1 )
{
return;
}
// Check if we can push into the system
final IAEFluidStack notStorable = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource(), Actionable.SIMULATE );
if( notStorable != null && notStorable.getStackSize() > 0 )
{
final int toStore = (int) ( extract.amount - notStorable.getStackSize() );
final FluidStack storable = fh.drain( toStore, false );
if( storable == null || storable.amount == 0 )
{
return;
}
else
{
extract.amount = storable.amount;
}
}
// Actually drain
final FluidStack drained = fh.drain( extract, true );
extract.amount = drained.amount;
final IAEFluidStack notInserted = Platform.poweredInsert( this.getPowerSource(), this.monitor, AEFluidStack.fromFluidStack( extract ), this.getActionSource() );
if( notInserted != null && notInserted.getStackSize() > 0 )
{
IAEFluidStack spill = this.monitor.injectItems( notInserted, Actionable.MODULATE, this.getActionSource() );
if( spill != null && spill.getStackSize() > 0 )
{
fh.fill( spill.getFluidStack(), true );
}
}
if( held.getCount() == 1 )
{
player.inventory.setItemStack( fh.getContainer() );
}
else
{
player.inventory.getItemStack().shrink( 1 );
if( !player.inventory.addItemStackToInventory( fh.getContainer() ) )
{
player.dropItem( fh.getContainer(), false );
}
}
}
this.updateHeld( player );
}
}
@@ -20,7 +20,6 @@ package appeng.fluids.parts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -45,7 +44,6 @@ import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IItemList;
import appeng.fluids.util.AEFluidStack;
import appeng.me.GridAccessException;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
@@ -94,14 +92,9 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
if( type == Actionable.MODULATE )
{
try
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ignore )
{
// meh
}
this.cache
.currentlyCached
.add( input.copy().setStackSize( wasFillled ));
}
fluidStack.amount = remaining;
@@ -123,18 +116,16 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
return null;
}
IAEFluidStack gatheredAEFluidstack = AEFluidStack.fromFluidStack( gathered );
if( mode == Actionable.MODULATE )
{
try
IAEFluidStack e = this.cache.currentlyCached.findPrecise( gatheredAEFluidstack );
if (e != null)
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ignore )
{
// meh
e.decStackSize( gathered.amount );
}
}
return AEFluidStack.fromFluidStack( gathered );
return gatheredAEFluidstack;
}
@Override
@@ -202,9 +193,10 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
private static class InventoryCache
{
private IAEFluidStack[] cachedAeStacks = new IAEFluidStack[0];
private final IFluidHandler fluidHandler;
private final StorageFilter mode;
IItemList<IAEFluidStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
public InventoryCache( IFluidHandler fluidHandler, StorageFilter mode )
{
@@ -216,19 +208,12 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
{
final List<IAEFluidStack> changes = new ArrayList<>();
final IFluidTankProperties[] tankProperties = this.fluidHandler.getTankProperties();
final int slots = tankProperties.length;
// Make room for new slots
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
IItemList<IAEFluidStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ).createList();
for( int slot = 0; slot < slots; slot++ )
for( IFluidTankProperties tankProperty : tankProperties )
{
// Save the old stuff
final IAEFluidStack oldAEFS = this.cachedAeStacks[slot];
FluidStack newFS = tankProperties[slot].getContents();
FluidStack newFS = tankProperty.getContents();
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && newFS != null )
{
if( this.fluidHandler.drain( 1, false ) == null )
@@ -236,82 +221,40 @@ public class FluidHandlerAdapter implements IMEInventory<IAEFluidStack>, IBaseMo
newFS = null;
}
}
this.handlePossibleSlotChanges( slot, oldAEFS, newFS, changes );
}
// Handle cases where the number of slots actually is lower now than before
if( slots < this.cachedAeStacks.length )
{
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ )
if( newFS != null )
{
final IAEFluidStack aeStack = this.cachedAeStacks[slot];
if( aeStack != null )
{
final IAEFluidStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
currentlyOnStorage.add( AEFluidStack.fromFluidStack( newFS ) );
}
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
for ( final IAEFluidStack is : currentlyCached )
{
is.setStackSize( -is.getStackSize() );
}
for ( final IAEFluidStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEFluidStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes;
}
public IItemList<IAEFluidStack> getAvailableItems( IItemList<IAEFluidStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
private void handlePossibleSlotChanges( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
if( oldAeFS != null && oldAeFS.getFluidStack().isFluidEqual( newFS ) )
{
this.handleStackSizeChanged( slot, oldAeFS, newFS, changes );
}
else
{
this.handleFluidChanged( slot, oldAeFS, newFS, changes );
}
}
private void handleStackSizeChanged( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
// Still the same fluid, but amount might have changed
final long diff = newFS.amount - oldAeFS.getStackSize();
if( diff != 0 )
{
final IAEFluidStack stack = oldAeFS.copy();
stack.setStackSize( newFS.amount );
this.cachedAeStacks[slot] = stack;
final IAEFluidStack a = stack.copy();
a.setStackSize( diff );
changes.add( a );
}
}
private void handleFluidChanged( int slot, IAEFluidStack oldAeFS, FluidStack newFS, List<IAEFluidStack> changes )
{
// Completely different fluid
this.cachedAeStacks[slot] = AEFluidStack.fromFluidStack( newFS );
// If we had a stack previously in this slot, notify the network about its disappearance
if( oldAeFS != null )
{
oldAeFS.setStackSize( -oldAeFS.getStackSize() );
changes.add( oldAeFS );
}
// Notify the network about the new stack. Note that this is null if newFS was null
if( this.cachedAeStacks[slot] != null )
{
changes.add( this.cachedAeStacks[slot] );
}
}
}
}
@@ -4,7 +4,9 @@ package appeng.fluids.parts;
import java.util.Random;
import appeng.api.networking.events.MENetworkChannelChanged;
import appeng.fluids.helper.IConfigurableFluidInventory;
import appeng.me.cache.NetworkMonitor;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
@@ -34,7 +36,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager;
@@ -112,11 +113,11 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
}
@Override
public void onStackChange( IItemList<?> o, IAEStack<?> fullStack, IAEStack<?> diffStack, IActionSource src, IStorageChannel<?> chan )
public void onStackChange( IAEStack<?> diffStack, IStorageChannel<?> chan )
{
if( chan == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) && fullStack.equals( this.config.getFluidInSlot( 0 ) ) )
if( chan == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) && diffStack.equals( this.config.getFluidInSlot( 0 ) ) )
{
this.lastReportedValue = fullStack.getStackSize();
this.lastReportedValue += diffStack.getStackSize();
this.updateState();
}
}
@@ -128,14 +129,22 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
public void powerStatusChange( final MENetworkPowerStatusChange powerEvent )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c )
public void channelChanged( final MENetworkChannelsChanged c )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@@ -247,10 +256,9 @@ public class PartFluidLevelEmitter extends PartUpgradeable implements IStackWatc
if( myStack == null )
{
this.lastReportedValue = 0;
for( final IAEFluidStack st : monitor.getStorageList() )
if( monitor instanceof NetworkMonitor )
{
this.lastReportedValue += st.getStackSize();
this.lastReportedValue = ( (NetworkMonitor<IAEFluidStack>) monitor ).getGridCurrentCount();
}
}
else
@@ -264,20 +264,17 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
@Override
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().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
}
catch( final GridAccessException e )
{
// :(
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ), change, this.source );
}
}
catch( final GridAccessException e )
{
// :(
}
}
public MEInventoryHandler<IAEFluidStack> getInternalHandler()
@@ -415,7 +412,7 @@ public class PartFluidStorageBus extends PartSharedStorageBus implements IMEMoni
{
if( channel == this.getStorageChannel() )
{
final IMEInventoryHandler<IAEFluidStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null;
final IMEInventoryHandler<IAEFluidStack> out = this.getInternalHandler();
if( out != null )
{
return Collections.singletonList( out );
@@ -20,10 +20,10 @@ package appeng.helpers;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import appeng.api.definitions.IItemDefinition;
import appeng.integration.modules.gregtech.GTCEInventoryAdaptor;
import appeng.util.*;
import appeng.util.inv.*;
@@ -33,10 +33,9 @@ import de.ellpeck.actuallyadditions.api.tile.IPhantomTile;
import gregtech.api.block.machines.BlockMachine;
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.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
@@ -115,7 +114,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
public static final int NUMBER_OF_STORAGE_SLOTS = 9;
public static final int NUMBER_OF_CONFIG_SLOTS = 9;
public static final int NUMBER_OF_PATTERN_SLOTS = 9;
public static final int NUMBER_OF_PATTERN_SLOTS = 36;
private static final Collection<Block> BAD_BLOCKS = new HashSet<>( 100 );
private final IAEItemStack[] requireWork = { null, null, null, null, null, null, null, null, null };
@@ -151,7 +150,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
this.gridProxy = networkProxy;
this.gridProxy.setFlags( GridFlags.REQUIRE_CHANNEL );
this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 1 );
this.upgrades = new StackUpgradeInventory( this.gridProxy.getMachineRepresentation(), this, 4);
this.cm.registerSetting( Settings.BLOCK, YesNo.NO );
this.cm.registerSetting( Settings.INTERFACE_TERMINAL, YesNo.YES );
@@ -179,7 +178,6 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
{
return;
}
if( inv == this.config )
{
this.readConfig();
@@ -279,10 +277,11 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
this.waitingToSendFacing = null;
final NBTTagCompound waitingListSided = data.getCompoundTag("sidedWaitList");
final NBTTagCompound waitingListSided = data.getCompoundTag( "sidedWaitList" );
for (EnumFacing s : EnumFacing.values())
if (waitingListSided.hasKey( s.name() )) {
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++ )
{
@@ -290,14 +289,31 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
if( c != null )
{
final ItemStack is = new ItemStack( c );
this.addToSendListFacing( is , EnumFacing.getFront( s.getIndex() ) );
this.addToSendListFacing( is, EnumFacing.getFront( s.getIndex() ) );
}
}
}
this.craftingTracker.readFromNBT( data );
// fix upgrade slot size mismatch
NBTTagCompound up = data.getCompoundTag( "upgrades" );
if( up.hasKey( "Size" ) && up.getInteger( "Size" ) != this.upgrades.getSlots() )
{
up.setInteger( "Size", this.upgrades.getSlots() );
this.upgrades.writeToNBT( up, "upgrades" );
}
this.upgrades.readFromNBT( data, "upgrades" );
this.config.readFromNBT( data, "config" );
NBTTagCompound pa = data.getCompoundTag( "patterns" );
if( pa.hasKey( "Size" ) && pa.getInteger( "Size" ) != this.patterns.getSlots() )
{
pa.setInteger( "Size", this.patterns.getSlots() );
this.upgrades.writeToNBT( pa, "patterns" );
}
this.patterns.readFromNBT( data, "patterns" );
this.storage.readFromNBT( data, "storage" );
this.priority = data.getInteger( "priority" );
@@ -400,9 +416,8 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
private void updateCraftingList()
{
final Boolean[] accountedFor = { false, false, false, false, false, false, false, false, false }; // 9...
assert ( accountedFor.length == this.patterns.getSlots() );
final Boolean[] accountedFor = new Boolean[this.patterns.getSlots()];
Arrays.fill( accountedFor, false );
if( !this.gridProxy.isReady() )
{
@@ -417,7 +432,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
final ICraftingPatternDetails details = i.next();
boolean found = false;
for( int x = 0; x < accountedFor.length; x++ )
for( int x = 0; x < accountedFor.length ; x++ )
{
final ItemStack is = this.patterns.getStackInSlot( x );
if( details.getPattern() == is )
@@ -433,7 +448,7 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
}
}
for( int x = 0; x < accountedFor.length; x++ )
for( int x = 0; x < accountedFor.length ; x++ )
{
if( !accountedFor[x] )
{
@@ -586,6 +601,30 @@ public class DualityInterface implements IGridTickable, IStorageMonitorable, IIn
return false;
}
public void dropExcessPatterns()
{
IItemHandler patterns = getPatterns();
List<ItemStack> dropList = new ArrayList<>();
for( int invSlot = 0; invSlot < patterns.getSlots(); invSlot++ )
{
if( invSlot > 8 + this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) * 9 )
{
ItemStack is = patterns.getStackInSlot( invSlot );
if( is.isEmpty() ) continue;
dropList.add( patterns.extractItem( invSlot, Integer.MAX_VALUE, false ) );
}
}
if( dropList.size() > 0 )
{
World world = this.getLocation().getWorld();
BlockPos blockPos = this.getLocation().getPos();
Platform.spawnDrops( world, blockPos, dropList );
}
this.gridProxy.setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) );
}
@Override
public boolean canInsert( final ItemStack stack )
{
+114 -46
View File
@@ -19,21 +19,18 @@
package appeng.helpers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
import java.util.*;
import java.util.stream.Collectors;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import appeng.api.AEApi;
@@ -46,11 +43,17 @@ import appeng.core.AELog;
import appeng.core.features.AEFeature;
import appeng.util.Platform;
import appeng.util.item.AEItemStack;
import net.minecraftforge.common.crafting.IShapedRecipe;
public class PatternHelper implements ICraftingPatternDetails, Comparable<PatternHelper>
{
private static final int CRAFTING_GRID_DIMENSION = 3;
private static final int ALL_INPUT_LIMIT = CRAFTING_GRID_DIMENSION * CRAFTING_GRID_DIMENSION;
private static final int CRAFTING_OUTPUT_LIMIT = 1;
private static final int PROCESSING_OUTPUT_LIMIT = 3;
private final ItemStack patternItem;
private final InventoryCrafting crafting = new InventoryCrafting( new ContainerNull(), 3, 3 );
private final InventoryCrafting testFrame = new InventoryCrafting( new ContainerNull(), 3, 3 );
@@ -60,6 +63,7 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
private final IAEItemStack[] condensedOutputs;
private final IAEItemStack[] inputs;
private final IAEItemStack[] outputs;
private final Map<Integer, List<IAEItemStack>> substituteInputs;
private final boolean isCrafting;
private final boolean canSubstitute;
private final Set<TestLookup> failCache = new HashSet<>();
@@ -143,9 +147,11 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
}
}
}
final int outputLength = this.isCrafting ? CRAFTING_OUTPUT_LIMIT : PROCESSING_OUTPUT_LIMIT;
this.outputs = out.toArray( new IAEItemStack[out.size()] );
this.inputs = in.toArray( new IAEItemStack[in.size()] );
this.inputs = in.toArray(new IAEItemStack[ALL_INPUT_LIMIT]);
this.outputs = out.toArray(new IAEItemStack[outputLength]);
this.substituteInputs = new HashMap<>(ALL_INPUT_LIMIT);
final Map<IAEItemStack, IAEItemStack> tmpOutputs = new HashMap<>();
@@ -257,6 +263,14 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
this.testFrame.setInventorySlotContents( slotIndex, i );
// If we cannot substitute, the items must match exactly
if (!canSubstitute && slotIndex < inputs.length) {
if (!inputs[slotIndex].isSameType(i)) {
this.markItemAs(slotIndex, i, TestStatus.DECLINE);
return false;
}
}
if( this.standardRecipe.matches( this.testFrame, w ) )
{
final ItemStack testOutput = this.standardRecipe.getCraftingResult( this.testFrame );
@@ -268,25 +282,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return true;
}
}
else if( AEConfig.instance().isFeatureEnabled( AEFeature.CRAFTING_MANAGER_FALLBACK ) )
{
final ItemStack testOutput = CraftingManager.findMatchingResult( this.testFrame, w );
if( Platform.itemComparisons().isSameItem( this.correctOutput, testOutput ) )
{
this.testFrame.setInventorySlotContents( slotIndex, this.crafting.getStackInSlot( slotIndex ) );
this.markItemAs( slotIndex, i, TestStatus.ACCEPT );
if( AELog.isCraftingDebugLogEnabled() )
{
this.warnAboutCraftingManager( true );
}
return true;
}
this.warnAboutCraftingManager( false );
}
this.markItemAs( slotIndex, i, TestStatus.DECLINE );
return false;
@@ -328,6 +323,97 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.canSubstitute;
}
@Override
public List<IAEItemStack> getSubstituteInputs(int slot) {
if (this.inputs[slot] == null) {
return Collections.emptyList();
}
return this.substituteInputs.computeIfAbsent(slot, value -> {
ItemStack[] matchingStacks = getRecipeIngredient(slot).getMatchingStacks();
List<IAEItemStack> itemList = new ArrayList<>(matchingStacks.length + 1);
for (ItemStack matchingStack : matchingStacks) {
itemList.add(AEItemStack.fromItemStack(matchingStack));
}
// Ensure that the specific item put in by the user is at the beginning,
// so that it takes precedence over substitutions
itemList.add(0, this.inputs[slot]);
return itemList;
});
}
/**
* Gets the {@link Ingredient} from the actual used recipe for a given slot-index into {@link #getInputs()}.
* <p/>
* Conversion is needed for two reasons: our sparse ingredients are always organized in a 3x3 grid, while Vanilla's
* ingredient list will be condensed to the actual recipe's grid size. In addition, in our 3x3 grid, the user can
* shift the actual recipe input to the right and down.
*/
private Ingredient getRecipeIngredient(int slot) {
if (standardRecipe instanceof IShapedRecipe ) {
IShapedRecipe shapedRecipe = (IShapedRecipe) standardRecipe;
return getShapedRecipeIngredient(slot, shapedRecipe.getRecipeWidth());
} else {
return getShapelessRecipeIngredient(slot);
}
}
private Ingredient getShapedRecipeIngredient(int slot, int recipeWidth) {
// Compute the offset of the user's input vs. crafting grid origin
// Which is >0 if they have empty rows above or to the left of their input
int topOffset = 0;
if (inputs[0] == null && inputs[1] == null && inputs[2] == null) {
topOffset++; // First row is fully empty
if (inputs[3] == null && inputs[4] == null && inputs[5] == null) {
topOffset++; // Second row is fully empty
}
}
int leftOffset = 0;
if (inputs[0] == null && inputs[3] == null && inputs[6] == null) {
leftOffset++; // First column is fully empty
if (inputs[1] == null && inputs[4] == null && inputs[7] == null) {
leftOffset++; // Second column is fully empty
}
}
// Compute the x,y of the slot, as-if the recipe was anchored to 0,0
int slotX = slot % CRAFTING_GRID_DIMENSION - leftOffset;
int slotY = slot / CRAFTING_GRID_DIMENSION - topOffset;
// Compute the index into the recipe's ingredient list now
int ingredientIndex = slotY * recipeWidth + slotX;
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < 0 || ingredientIndex > ingredients.size()) {
return Ingredient.EMPTY;
}
return ingredients.get(ingredientIndex);
}
private Ingredient getShapelessRecipeIngredient(int slot) {
// We map the list of *filled* sparse inputs to the shapeless (ergo unordered)
// ingredients. While these do not actually correspond to each other,
// since both lists have the same length, the mapping is at least stable.
int ingredientIndex = 0;
for (int i = 0; i < slot; i++) {
if (inputs[i] != null) {
ingredientIndex++;
}
}
NonNullList<Ingredient> ingredients = standardRecipe.getIngredients();
if (ingredientIndex < ingredients.size()) {
return ingredients.get(ingredientIndex);
}
return Ingredient.EMPTY;
}
@Override
public ItemStack getOutput( final InventoryCrafting craftingInv, final World w )
{
@@ -406,24 +492,6 @@ public class PatternHelper implements ICraftingPatternDetails, Comparable<Patter
return this.pattern.hashCode();
}
private void warnAboutCraftingManager( boolean foundAlternative )
{
final String foundAlternativeRecipe = foundAlternative ? "Found alternative recipe." : "NOT FOUND, please report.";
final StringJoiner joinActualInputs = new StringJoiner( ", " );
for( int j = 0; j < this.testFrame.getSizeInventory(); j++ )
{
final ItemStack stack = this.testFrame.getStackInSlot( j );
if( !stack.isEmpty() )
{
joinActualInputs.add( stack.toString() );
}
}
AELog.warn( "Using CraftingManager fallback: Recipe <%s> for output <%s> rejected inputs [%s]. %s",
this.standardRecipe.getRegistryName(), this.standardRecipe.getRecipeOutput(), joinActualInputs, foundAlternativeRecipe );
}
@Override
public boolean equals( final Object obj )
{
@@ -147,8 +147,12 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
}
// prefer pure crystals.
for( ItemStack stack : ingredient.getAllIngredients() )
for ( ItemStack stack : ingredient.getAllIngredients() )
{
if( stack == null )
{
continue;
}
if( Platform.isRecipePrioritized( stack ) )
{
list.add( 0, stack );
@@ -159,7 +163,7 @@ class RecipeTransferHandler<T extends Container> implements IRecipeTransferHandl
}
}
for( final ItemStack is : list )
for ( final ItemStack is : list )
{
final NBTTagCompound tag = new NBTTagCompound();
is.writeToNBT( tag );
@@ -164,6 +164,8 @@ public final class ItemMaterial extends AEBaseItem implements IStorageComponent,
return Upgrades.INVERTER;
case CARD_CRAFTING:
return Upgrades.CRAFTING;
case CARD_PATTERN_EXPANSION:
return Upgrades.PATTERN_EXPANSION;
default:
return null;
}
@@ -118,7 +118,10 @@ public enum MaterialType
FLUID_CELL1K_PART( 54, "material_fluid_cell1k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL4K_PART( 55, "material_fluid_cell4k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL16K_PART( 56, "material_fluid_cell16k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
FLUID_CELL64K_PART( 57, "material_fluid_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) );
FLUID_CELL64K_PART( 57, "material_fluid_cell64k_part", EnumSet.of( AEFeature.STORAGE_CELLS ) ),
CARD_PATTERN_EXPANSION( 58, "material_card_pattern_expansion", EnumSet.of( AEFeature.ADVANCED_CARDS ) );
private final Set<AEFeature> features;
private final ModelResourceLocation model;
@@ -225,7 +225,7 @@ public class ItemEncodedPattern extends AEBaseItem implements ICraftingPatternIt
final ICraftingPatternDetails details = this.getPatternForItem( item, w );
out = details != null ? details.getOutputs()[0].createItemStack() : ItemStack.EMPTY;
out = details != null ? details.getCondensedOutputs()[0].createItemStack() : ItemStack.EMPTY;
SIMPLE_CACHE.put( item, out );
return out;
+2 -2
View File
@@ -633,10 +633,10 @@ public class GridNode implements IGridNode, IPathItem
this.usedChannels = 0;
}
final int idx = this.connections.indexOf( fast );
final int idx = this.connections.indexOf( (IGridConnection) fast );
if( idx > 0 )
{
this.connections.remove( fast );
this.connections.remove( (IGridConnection) fast );
this.connections.add( 0, (IGridConnection) fast );
}
}
+19 -11
View File
@@ -42,6 +42,10 @@ import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
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 appeng.api.AEApi;
@@ -105,8 +109,8 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
private final Set<ICraftingProvider> craftingProviders = new HashSet<>();
private final Map<IGridNode, ICraftingWatcher> craftingWatchers = new HashMap<>();
private final IGrid grid;
private final Map<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new HashMap<>();
private final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new HashMap<>();
private final Object2ObjectMap<ICraftingPatternDetails, List<ICraftingMedium>> craftingMethods = new Object2ObjectOpenHashMap<>();
private final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> craftableItems = new Object2ObjectOpenHashMap<>();
private final Set<IAEItemStack> emitableItems = new HashSet<>();
private final Map<String, CraftingLinkNexus> craftingLinks = new HashMap<>();
private final Multimap<IAEStack, CraftingWatcher> interests = HashMultimap.create();
@@ -160,11 +164,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
{
if( machine instanceof ICraftingWatcherHost )
{
final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( machine );
final ICraftingWatcher craftingWatcher = this.craftingWatchers.get( gridNode );
if( craftingWatcher != null )
{
craftingWatcher.reset();
this.craftingWatchers.remove( machine );
this.craftingWatchers.remove( gridNode );
}
}
@@ -270,7 +274,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
return;
}
final Map<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = this.craftableItems;
final Object2ObjectMap<IAEItemStack, ImmutableList<ICraftingPatternDetails>> oldItems = this.craftableItems;
// erase list.
this.craftingMethods.clear();
@@ -287,22 +291,22 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
provider.provideCrafting( this );
}
final Map<IAEItemStack, Set<ICraftingPatternDetails>> tmpCraft = new HashMap<>();
final Object2ObjectMap<IAEItemStack, ObjectSet<ICraftingPatternDetails>> tmpCraft = new Object2ObjectOpenHashMap<>();
// new craftables!
for( final ICraftingPatternDetails details : this.craftingMethods.keySet() )
{
for( IAEItemStack out : details.getOutputs() )
for( IAEItemStack out : details.getCondensedOutputs() )
{
out = out.copy();
out.reset();
out.setCraftable( true );
Set<ICraftingPatternDetails> methods = tmpCraft.get( out );
ObjectSet<ICraftingPatternDetails> methods = tmpCraft.get( out );
if( methods == null )
{
tmpCraft.put( out, methods = new TreeSet<>( COMPARATOR ) );
tmpCraft.put( out, methods = new ObjectRBTreeSet<>( COMPARATOR ) );
}
methods.add( details );
@@ -310,7 +314,7 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
}
// make them immutable
for( final Entry<IAEItemStack, Set<ICraftingPatternDetails>> e : tmpCraft.entrySet() )
for( final Entry<IAEItemStack, ObjectSet<ICraftingPatternDetails>> e : tmpCraft.entrySet() )
{
this.craftableItems.put( e.getKey(), ImmutableList.copyOf( e.getValue() ) );
}
@@ -635,7 +639,11 @@ public class CraftingGridCache implements ICraftingGrid, ICraftingProviderHelper
public boolean hasCpu( final ICraftingCPU cpu )
{
return this.craftingCPUClusters.contains( cpu );
if (cpu instanceof CraftingCPUCluster)
{
return this.craftingCPUClusters.contains( (CraftingCPUCluster) cpu );
}
return false;
}
public GenericInterestManager<CraftingWatcher> getInterestManager()
+143 -32
View File
@@ -30,6 +30,7 @@ import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
@@ -63,7 +64,7 @@ import appeng.me.energy.EnergyWatcher;
public class EnergyGridCache implements IEnergyGrid
{
private static final double MAX_BUFFER_STORAGE = 200;
private static final double MAX_BUFFER_STORAGE = 800;
private static final Comparator<IEnergyGridProvider> COMPARATOR_HIGHEST_AMOUNT_STORED_FIRST = ( o1, o2 ) -> Double.compare( o2.getProviderStoredEnergy(),
o1.getProviderStoredEnergy() );
@@ -76,9 +77,24 @@ public class EnergyGridCache implements IEnergyGrid
};
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 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<>();
// 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 IGrid myGrid;
private final HashMap<IGridNode, IEnergyWatcher> watchers = new HashMap<>();
@@ -110,6 +126,10 @@ public class EnergyGridCache implements IEnergyGrid
private double lastStoredPower = -1;
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 )
{
@@ -143,18 +163,32 @@ public class EnergyGridCache implements IEnergyGrid
{
if( ev.storage.isAEPublicPowerStorage() )
{
switch( ev.type )
switch ( ev.type )
{
case PROVIDE_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.WRITE )
{
this.providers.add( ev.storage );
if( !ongoingExtractOperation )
{
addProvider( ev.storage );
}
else
{
this.providersToAdd.add( ev.storage );
}
}
break;
case REQUEST_POWER:
if( ev.storage.getPowerFlow() != AccessRestriction.READ )
{
this.requesters.add( ev.storage );
if( !ongoingInjectOperation )
{
addRequester( ev.storage );
}
else
{
this.requesterToAdd.add( ev.storage );
}
}
break;
}
@@ -197,7 +231,7 @@ public class EnergyGridCache implements IEnergyGrid
if( this.drainPerTick > 0.0001 )
{
final double drained = this.extractAEPower( this.getIdlePowerUsage(), Actionable.MODULATE, PowerMultiplier.CONFIG );
currentlyHasPower = drained >= this.drainPerTick - 0.001;
currentlyHasPower = drained >= this.drainPerTick - 0.001 && this.getStoredPower() > 0;
}
else
{
@@ -301,20 +335,32 @@ public class EnergyGridCache implements IEnergyGrid
{
double extractedPower = 0;
this.providers.addAll( providersToAdd );
providersToAdd.clear();
final Iterator<IAEPowerStorage> it = this.providers.iterator();
while( extractedPower < amt && it.hasNext() )
ongoingExtractOperation = true;
try
{
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 )
while ( extractedPower < amt && it.hasNext() )
{
it.remove();
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 )
{
it.remove();
}
}
} finally
{
providers.removeIf( p -> providerToRemove.contains( p ) );
this.providerToRemove.clear();
ongoingExtractOperation = false;
}
final double result = Math.min( extractedPower, amt );
@@ -338,17 +384,30 @@ public class EnergyGridCache implements IEnergyGrid
{
final double originalAmount = amt;
this.requesters.addAll( requesterToAdd );
requesterToAdd.clear();
final Iterator<IAEPowerStorage> it = this.requesters.iterator();
while( amt > 0 && it.hasNext() )
ongoingInjectOperation = true;
try
{
final IAEPowerStorage node = it.next();
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
while ( amt > 0 && it.hasNext() )
{
it.remove();
final IAEPowerStorage node = it.next();
amt = node.injectAEPower( amt, mode );
if( amt > 0 && mode == Actionable.MODULATE )
{
it.remove();
}
}
} finally
{
requesters.removeIf( r -> requesterToRemove.contains( r ) );
this.requesterToRemove.clear();
ongoingInjectOperation = false;
}
final double overflow = Math.max( 0.0, amt );
@@ -428,11 +487,7 @@ public class EnergyGridCache implements IEnergyGrid
@Override
public double getStoredPower()
{
if( this.availableTicksSinceUpdate > 90 )
{
this.refreshPower();
}
this.refreshPower();
return Math.max( 0.0, this.globalAvailablePower );
}
@@ -505,9 +560,22 @@ public class EnergyGridCache implements IEnergyGrid
this.globalMaxPower -= ps.getAEMaxPower();
this.globalAvailablePower -= ps.getAECurrentPower();
}
this.providers.remove( ps );
this.requesters.remove( ps );
if( !ongoingExtractOperation )
{
removeProvider( ps );
}
else
{
this.providerToRemove.add( ps );
}
if( !ongoingInjectOperation )
{
removeRequester( ps );
}
else
{
this.requesterToRemove.add( ps );
}
}
}
@@ -523,6 +591,31 @@ 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
public void addNode( final IGridNode node, final IGridHost machine )
{
@@ -554,12 +647,26 @@ public class EnergyGridCache implements IEnergyGrid
if( current > 0 && ps.getPowerFlow() != AccessRestriction.WRITE )
{
this.globalAvailablePower += current;
this.providers.add( ps );
if( !ongoingExtractOperation )
{
addProvider( ps );
}
else
{
this.providersToAdd.add( ps );
}
}
if( current < max && ps.getPowerFlow() != AccessRestriction.READ )
{
this.requesters.add( ps );
if( !ongoingInjectOperation )
{
addRequester( ps );
}
else
{
this.requesterToAdd.add( ps );
}
}
}
}
@@ -681,8 +788,12 @@ public class EnergyGridCache implements IEnergyGrid
if( this.stored < 0.01 )
{
EnergyGridCache.this.ticksSinceHasPowerChange = 0;
EnergyGridCache.this.publicPowerState( false, EnergyGridCache.this.myGrid );
refreshPower();
if (globalAvailablePower < MAX_BUFFER_STORAGE - 0.001)
{
EnergyGridCache.this.ticksSinceHasPowerChange = 0;
EnergyGridCache.this.publicPowerState( false, EnergyGridCache.this.myGrid );
}
}
}
}
+2 -2
View File
@@ -101,12 +101,12 @@ public class GridStorageCache implements IStorageGrid
if( machine instanceof IStackWatcherHost )
{
final IStackWatcher myWatcher = this.watchers.get( machine );
final IStackWatcher myWatcher = this.watchers.get( node );
if( myWatcher != null )
{
myWatcher.reset();
this.watchers.remove( machine );
this.watchers.remove( node );
}
}
}
+63 -16
View File
@@ -19,17 +19,21 @@
package appeng.me.cache;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.api.storage.data.IAEItemStack;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Queues;
@@ -66,6 +70,8 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
private boolean hasChanged = false;
@Nonnegative
private int localDepthSemaphore = 0;
private long gridItemCount;
private long gridFluidCount;
public NetworkMonitor( final GridStorageCache cache, final IStorageChannel<T> chan )
{
@@ -137,6 +143,32 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
return this.getHandler().getSlot();
}
public long getGridCurrentCount()
{
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
return gridItemCount;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
return gridFluidCount;
}
return 0;
}
public long incGridCurrentCount(long count)
{
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
return gridItemCount += count;
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
return gridFluidCount += count;
}
return 0;
}
@Nonnull
@Override
public IItemList<T> getStorageList()
@@ -230,7 +262,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
{
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
if( receiver.isValid( o.getValue() ) )
if( receiver.isValid( o.getValue() ) && receiver.hasListeners() )
{
receiver.postChange( this, diff, src );
}
@@ -258,9 +290,7 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
this.sendEvent = true;
this.notifyListenersOfChange( changes, src );
for( final T changedItem : changes )
for ( final T changedItem : changes )
{
T difference = changedItem;
@@ -270,25 +300,20 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
difference.setStackSize( -changedItem.getStackSize() );
}
incGridCurrentCount( difference.getStackSize() );
this.cachedList.add( difference );
if( this.myGridCache.getInterestManager().containsKey( changedItem ) )
{
final Collection<ItemWatcher> list = this.myGridCache.getInterestManager().get( changedItem );
if( !list.isEmpty() )
{
IAEStack<T> fullStack = this.getStorageList().findPrecise( changedItem );
if( fullStack == null )
{
fullStack = changedItem.copy();
fullStack.setStackSize( 0 );
}
this.myGridCache.getInterestManager().enableTransactions();
for( final ItemWatcher iw : list )
{
iw.getHost().onStackChange( this.getStorageList(), fullStack, difference, src, this.getChannel() );
iw.getHost().onStackChange( difference, this.getChannel() );
}
this.myGridCache.getInterestManager().disableTransactions();
@@ -296,6 +321,8 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
}
}
this.notifyListenersOfChange( changes, src );
final NetworkMonitor<?> last = GLOBAL_DEPTH.pop();
this.localDepthSemaphore--;
@@ -308,9 +335,28 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
void forceUpdate()
{
this.hasChanged = true;
//when the grid comes back online, reset the count to 0 so
//it reflects the correct amount after the changes are accounted for
if( myChannel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
gridItemCount = 0;
for( IAEItemStack iaeItemStack : (Iterable<IAEItemStack>) getStorageList() )
{
gridItemCount += iaeItemStack.getStackSize();
}
}
else if( myChannel == AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) )
{
gridFluidCount = 0;
for( IAEFluidStack iaeFluidStack : (Iterable<IAEFluidStack>) getStorageList() )
{
gridFluidCount += iaeFluidStack.getStackSize();
}
}
final Iterator<Entry<IMEMonitorHandlerReceiver<T>, Object>> i = this.getListeners();
while( i.hasNext() )
while ( i.hasNext() )
{
final Entry<IMEMonitorHandlerReceiver<T>, Object> o = i.next();
final IMEMonitorHandlerReceiver<T> receiver = o.getKey();
@@ -333,5 +379,6 @@ public class NetworkMonitor<T extends IAEStack<T>> implements IMEMonitor<T>
this.sendEvent = false;
this.myGridCache.getGrid().postEvent( new MENetworkStorageEvent( this, this.myChannel ) );
}
}
}
+1 -1
View File
@@ -314,7 +314,7 @@ public class PathGridCache implements IPathingGrid
int depth = 0;
for( final IGridNode nodes : this.requireChannels )
{
if( !this.semiOpen.contains( nodes ) )
if( !this.semiOpen.contains( (IPathItem) nodes ) )
{
final IGridBlock gb = nodes.getGridBlock();
final EnumSet<GridFlags> flags = gb.getFlags();
-1
View File
@@ -138,7 +138,6 @@ public class TickManagerCache implements ITickManager
tt.addEntityCrashInfo( crashreportcategory );
throw new ReportedException( crashreport );
}
PartLevelEmitter.wipeCache();
}
private void addToQueue( final TickTracker tt )
@@ -23,6 +23,9 @@ import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import appeng.api.config.Upgrades;
import appeng.helpers.DualityInterface;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import net.minecraft.inventory.InventoryCrafting;
@@ -233,8 +236,9 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
public IAEItemStack injectItems( final IAEItemStack input, final Actionable type, final IActionSource src )
{
if( !( input instanceof IAEItemStack ) )
{
// also stop accepting items when the job is complete, i.e. to prevent re-insertion when pushing out
// items during storeItems
if (input == null || isComplete) {
return input;
}
@@ -292,7 +296,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
{
is.decStackSize( what.getStackSize() );
this.updateElapsedTime( what );
this.updateRemainingItemCount( what );
this.markDirty();
this.postCraftingStatusChange( what.copy().setStackSize( -what.getStackSize() ) );
@@ -431,6 +435,11 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
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.startItemCount = 0;
this.lastTime = 0;
@@ -485,22 +494,87 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return null;
}
private boolean canCraft( final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs )
private boolean canCraft(final ICraftingPatternDetails details, final IAEItemStack[] condensedInputs)
{
for( IAEItemStack g : condensedInputs )
if( !details.isCraftable() )
{
// Processing patterns are relatively easy
for ( IAEItemStack input : condensedInputs )
{
final IAEItemStack ais = this.inventory.extractItems( input.copy(), Actionable.SIMULATE,
this.machineSrc );
if( details.isCraftable() )
if( ais == null || ais.getStackSize() < input.getStackSize() )
{
return false;
}
}
}
else if( details.canSubstitute() )
{
// When substitutions are allowed, we have to keep track of which items we've reserved
IAEItemStack[] inputs = details.getInputs();
Map<IAEItemStack, Integer> consumedCount = new HashMap<>();
for ( int i = 0; i < inputs.length; i++ )
{
List<IAEItemStack> substitutes = details.getSubstituteInputs( i );
if( substitutes.isEmpty() )
{
continue;
}
boolean found = false;
for ( IAEItemStack substitute : substitutes )
{
for ( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( substitute, FuzzyMode.IGNORE_ALL ) )
{
int alreadyConsumed = consumedCount.getOrDefault( fuzz, 0 );
if( fuzz.getStackSize() - alreadyConsumed <= 0 )
{
continue; // Already fully consumed by a previous slot of this recipe
}
fuzz = fuzz.copy();
fuzz.setStackSize( 1 ); // We're iterating over non condensed inputs which means there's 1 of each needed
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE,
this.machineSrc );
if( ais != null && ais.getStackSize() > 0 )
{
// Mark 1 of the stack as consumed
consumedCount.merge( fuzz, 1, Integer::sum );
found = true;
break;
}
}
if( found )
{
break;
}
}
if( !found )
{
return false;
}
}
}
else
{
// When no substitutions can occur, we can simply check that all items are accounted since
// each type of item should only occur once
for ( IAEItemStack g : condensedInputs )
{
boolean found = false;
for( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) )
for ( IAEItemStack fuzz : this.inventory.getItemList().findFuzzy( g, FuzzyMode.IGNORE_ALL ) )
{
fuzz = fuzz.copy();
fuzz.setStackSize( g.getStackSize() );
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.SIMULATE, this.machineSrc );
if (ais != null && ais.getStackSize() == g.getStackSize())
if( ais != null && ais.getStackSize() >= g.getStackSize() )
{
found = true;
break;
@@ -517,15 +591,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
return false;
}
}
else
{
final IAEItemStack ais = this.inventory.extractItems( g.copy(), Actionable.SIMULATE, this.machineSrc );
if (ais == null || ais.getStackSize() < g.getStackSize())
{
return false;
}
}
}
return true;
@@ -680,71 +746,67 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
boolean found = false;
for( int x = 0; x < input.length; x++ )
{
if( input[x] != null )
{
for (int x = 0; x < input.length; x++) {
if (input[x] != null) {
found = false;
if( details.isCraftable() )
{
if (details.isCraftable()) {
final Collection<IAEItemStack> itemList;
if( details.canSubstitute() )
{
itemList = this.inventory.getItemList().findFuzzy( input[x], FuzzyMode.IGNORE_ALL );
}
else
{
itemList = new ArrayList<>( 1 );
if (details.canSubstitute()) {
final List<IAEItemStack> substitutes = details.getSubstituteInputs(x);
itemList = new ArrayList<>(substitutes.size());
final IAEItemStack item = this.inventory.getItemList().findPrecise( input[x] );
for (IAEItemStack stack : substitutes) {
itemList.addAll(this.inventory.getItemList().findFuzzy(stack,
FuzzyMode.IGNORE_ALL));
}
} else {
itemList = new ArrayList<>(1);
if( item != null )
{
itemList.add( item );
final IAEItemStack item = this.inventory.getItemList()
.findPrecise(input[x]);
if (item != null) {
itemList.add(item);
}
}
for( IAEItemStack fuzz : itemList )
{
for (IAEItemStack fuzz : itemList) {
fuzz = fuzz.copy();
fuzz.setStackSize( input[x].getStackSize() );
fuzz.setStackSize(input[x].getStackSize());
if( details.isValidItemForSlot( x, fuzz.createItemStack(), this.getWorld() ) )
{
final IAEItemStack ais = this.inventory.extractItems( fuzz, Actionable.MODULATE, this.machineSrc );
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack();
if (details.isValidItemForSlot(x, fuzz.createItemStack(),
this.getWorld())) {
final IAEItemStack ais = this.inventory.extractItems(fuzz,
Actionable.MODULATE, this.machineSrc);
final ItemStack is = ais == null ? ItemStack.EMPTY
: ais.createItemStack();
if( !is.isEmpty() )
{
this.postChange( AEItemStack.fromItemStack( is ), this.machineSrc );
ic.setInventorySlotContents( x, is );
if (!is.isEmpty()) {
this.postChange(AEItemStack.fromItemStack(is), this.machineSrc);
ic.setInventorySlotContents(x, is);
found = true;
break;
}
}
}
}
else
{
final IAEItemStack ais = this.inventory.extractItems( input[x].copy(), Actionable.MODULATE, this.machineSrc );
} else {
final IAEItemStack ais = this.inventory.extractItems(input[x].copy(),
Actionable.MODULATE, this.machineSrc);
final ItemStack is = ais == null ? ItemStack.EMPTY : ais.createItemStack();
if( !is.isEmpty() )
{
this.postChange( input[x], this.machineSrc );
ic.setInventorySlotContents( x, is );
if( is.getCount() == input[x].getStackSize() )
{
if (!is.isEmpty()) {
this.postChange(input[x], this.machineSrc);
ic.setInventorySlotContents(x, is);
if (is.getCount() == input[x].getStackSize()) {
found = true;
continue;
}
}
}
if( !found )
{
if (!found) {
break;
}
}
@@ -828,6 +890,7 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
private void storeItems()
{
Preconditions.checkState(isComplete, "CPU should be complete to prevent re-insertion when dumping items");
final IGrid g = this.getGrid();
if( g == null )
@@ -838,23 +901,24 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
final IStorageGrid sg = g.getCache( IStorageGrid.class );
final IMEInventory<IAEItemStack> ii = sg.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) );
for( IAEItemStack is : this.inventory.getItemList() )
IItemList<IAEItemStack> itemList = this.inventory.getItemList();
for( IAEItemStack is : itemList )
{
is = this.inventory.extractItems( is.copy(), Actionable.MODULATE, this.machineSrc );
this.postChange( is, this.machineSrc );
IAEItemStack remainder = ii.injectItems( is.copy(), Actionable.MODULATE, this.machineSrc );
if( is != null )
// The network was unable to receive all of the items, i.e. no or not enough storage space left
if( remainder != null )
{
this.postChange( is, this.machineSrc );
is = ii.injectItems( is, Actionable.MODULATE, this.machineSrc );
is.setStackSize( remainder.getStackSize() );
}
if( is != null )
else
{
this.inventory.injectItems( is, Actionable.MODULATE, this.machineSrc );
is.reset();
}
}
if( this.inventory.getItemList().isEmpty() )
if( itemList.isEmpty() )
{
this.inventory = new MECraftingInventory();
}
@@ -939,14 +1003,13 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
@Override
public boolean isBusy()
{
final Iterator<Entry<ICraftingPatternDetails, TaskProgress>> i = this.tasks.entrySet().iterator();
while( i.hasNext() )
this.tasks.entrySet().removeIf(
taskProgressEntry -> taskProgressEntry.getValue().value <= 0 );
if( !this.waitingFor.isEmpty() || !this.tasks.isEmpty() )
{
if( i.next().getValue().value <= 0 )
{
i.remove();
}
this.updateElapsedTime();
}
return !this.tasks.isEmpty() || !this.waitingFor.isEmpty();
@@ -1338,12 +1401,16 @@ public final class CraftingCPUCluster implements IAECluster, ICraftingCPU
this.remainingItemCount = itemCount;
}
private void updateElapsedTime( final IAEItemStack is )
private void updateRemainingItemCount( final IAEItemStack is )
{
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
}
private void updateElapsedTime()
{
final long nextStartTime = System.nanoTime();
this.elapsedTime = this.getElapsedTime() + nextStartTime - this.lastTime;
this.lastTime = nextStartTime;
this.remainingItemCount = this.getRemainingItemCount() - is.getStackSize();
}
public long getElapsedTime()
@@ -23,9 +23,10 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Multimap;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.data.IAEStack;
import appeng.util.item.AEItemStack;
import com.google.common.collect.Multimap;
public class GenericInterestManager<T>
@@ -101,12 +102,30 @@ public class GenericInterestManager<T>
public boolean containsKey( final IAEStack stack )
{
if( stack.isItem() && ( ( AEItemStack ) stack ).getItem().isDamageable() )
{
return this.container.keySet().stream().filter( s -> s.isItem() )
.anyMatch( s -> s.fuzzyComparison( stack, FuzzyMode.IGNORE_ALL ) );
}
return this.container.containsKey( stack );
}
public Collection<T> get( final IAEStack stack )
{
return this.container.get( stack );
Collection<T> watchers = new ArrayList<>();
if( stack.isItem() && ( ( AEItemStack ) stack ).getItem().isDamageable() )
{
this.container.keySet().stream().filter( s -> s.isItem() )
.filter( k -> k.fuzzyComparison( stack, FuzzyMode.IGNORE_ALL ) )
.forEach( key ->
watchers.addAll( this.container.get( key ) )
);
}
else
{
return this.container.get( stack );
}
return watchers;
}
private class SavedTransactions
@@ -151,7 +151,7 @@ public abstract class AbstractCellInventory<T extends IAEStack<T>> implements IC
}
// clean any old crusty stuff...
for( ; x < oldStoredItems && x < this.maxItemTypes; x++ )
for( ; x >= oldStoredItems && x < this.maxItemTypes; x++ )
{
this.tagCompound.removeTag( ITEM_SLOT_KEYS[x] );
this.tagCompound.removeTag( ITEM_SLOT_COUNT_KEYS[x] );
@@ -277,6 +277,7 @@ public class BasicCellInventory<T extends IAEStack<T>> extends AbstractCellInven
}
t.setStackSize( stackSize );
t.setCraftable( false );
if( stackSize > 0 )
{
@@ -90,6 +90,13 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
@Override
public void addListener( final IMEMonitorHandlerReceiver<T> l, final Object verificationToken )
{
if( this.listeners.size() == 0 )
{
if( this.monitor != null )
{
this.monitor.addListener( this, this.monitor );
}
}
this.listeners.put( l, verificationToken );
}
@@ -117,6 +124,12 @@ public class MEMonitorPassThrough<T extends IAEStack<T>> extends MEPassThrough<T
return verificationToken == this.monitor;
}
@Override
public boolean hasListeners()
{
return this.listeners.size() > 0;
}
@Override
public void postChange( final IBaseMonitor<T> monitor, final Iterable<T> change, final IActionSource source )
{
@@ -19,11 +19,17 @@
package appeng.parts.automation;
import java.util.Collections;
import java.util.Optional;
import java.util.Random;
import appeng.api.networking.events.*;
import appeng.me.Grid;
import appeng.me.GridNode;
import appeng.me.cache.NetworkMonitor;
import appeng.util.item.AEItemStack;
import appeng.util.item.OreHelper;
import appeng.util.item.OreReference;
import it.unimi.dsi.fastutil.objects.Object2LongMap;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap;
@@ -56,10 +62,6 @@ import appeng.api.networking.crafting.ICraftingWatcherHost;
import appeng.api.networking.energy.IEnergyGrid;
import appeng.api.networking.energy.IEnergyWatcher;
import appeng.api.networking.energy.IEnergyWatcherHost;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkCraftingPatternChange;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.storage.IStackWatcher;
@@ -72,7 +74,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.api.util.AECableType;
import appeng.api.util.AEPartLocation;
import appeng.api.util.IConfigManager;
@@ -123,9 +124,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
private double centerX;
private double centerY;
private double centerZ;
static Object2LongMap<Grid> gridItemCount = new Object2LongOpenHashMap<>();
static Object2ObjectOpenHashMap<Grid, Object2LongMap<AEItemStack>> fuzzyAEItemStackCount = new Object2ObjectOpenHashMap<>();
static Object2ObjectOpenHashMap<Grid, Object2LongMap<AEItemStack>> preciseAEItemStackCount = new Object2ObjectOpenHashMap<>();
@Reflected
public PartLevelEmitter( final ItemStack is )
@@ -156,12 +154,6 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
}
@MENetworkEventSubscribe
public void powerChanged( final MENetworkPowerStatusChange c )
{
this.updateState();
}
private void updateState()
{
final boolean isOn = this.isLevelEmitterOn();
@@ -206,9 +198,23 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
return flipState ? this.reportingValue >= this.lastReportedValue + 1 : this.reportingValue < this.lastReportedValue + 1;
}
@MENetworkEventSubscribe
public void powerStatusChange( final MENetworkPowerStatusChange powerEvent )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
{
if (this.getProxy().isActive())
{
onListUpdate();
}
this.updateState();
}
@@ -296,24 +302,37 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
try
{
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 || myStack == null )
if( myStack == null )
{
this.getProxy()
.getStorage()
.getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
.addListener( this,
this.getProxy().getGrid() );
this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).addListener( this, this.getProxy().getGrid() );
}
else
{
this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ).removeListener( this );
if( this.myWatcher != null )
{
this.myWatcher.add( myStack );
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
Optional<OreReference> ores = OreHelper.INSTANCE.getOre( myStack.getDefinition() );
if( ores.isPresent() )
{
for( IAEItemStack iaeItemStack : ores.get().getAEEquivalents() )
{
this.myWatcher.add( iaeItemStack );
}
}
else
{
this.myWatcher.add( myStack );
}
}
else
{
this.myWatcher.add( myStack );
}
}
}
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
catch( final GridAccessException e )
@@ -323,90 +342,29 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
private void updateReportingValue( final IMEMonitor<IAEItemStack> monitor )
{
updateReportingValue( monitor,null );
}
private void updateReportingValue( final IMEMonitor<IAEItemStack> monitor, Iterable<IAEItemStack> change )
{
final IAEItemStack myStack = this.config.getAEStackInSlot( 0 );
GridNode node = (GridNode) (this.getGridNode());
if( node != null )
if( myStack == null )
{
final Grid g = node.getInternalGrid();
if( myStack == null )
if( monitor instanceof NetworkMonitor )
{
if( change != null )
{
if( gridItemCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
}
}
gridItemCount.computeIfAbsent( g, ( aLong ) -> {
this.lastReportedValue = 0;
monitor.getStorageList().forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
return ( lastReportedValue );
} );
this.lastReportedValue = gridItemCount.get( g );
this.lastReportedValue = ( (NetworkMonitor<IAEItemStack>) monitor ).getGridCurrentCount();
}
}
else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
if( change != null )
{
if( fuzzyAEItemStackCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> {
if( iaeItemStack.sameOre( myStack ) ) lastReportedValue += iaeItemStack.getStackSize();
} );
}
}
else if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
fuzzyAEItemStackCount.computeIfAbsent( g, ( grid -> new Object2LongOpenHashMap<>() ) );
fuzzyAEItemStackCount.get( g ).computeIfAbsent( (AEItemStack) myStack, ( aLong -> {
this.lastReportedValue = 0;
monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
return ( lastReportedValue );
} ) );
this.lastReportedValue = fuzzyAEItemStackCount.get( g ).get( myStack );
if( this.lastReportedValue == 0 )
{
fuzzyAEItemStackCount.get( g ).remove( myStack );
fuzzyAEItemStackCount.trim();
}
}
else
{
if( change != null )
{
if( preciseAEItemStackCount.containsKey( g ) )
{
change.forEach( iaeItemStack -> {
if( iaeItemStack.isSameType( myStack ) ) lastReportedValue += iaeItemStack.getStackSize();
} );
}
}
preciseAEItemStackCount.computeIfAbsent( g, ( grid -> new Object2LongOpenHashMap<>() ) );
preciseAEItemStackCount.get( g ).computeIfAbsent( (AEItemStack) myStack, ( aLong -> {
this.lastReportedValue = 0;
IAEItemStack precise = monitor.getStorageList().findPrecise( myStack );
if( precise != null ) lastReportedValue = precise.getStackSize();
return ( lastReportedValue );
} ) );
this.lastReportedValue = preciseAEItemStackCount.get( g ).get( myStack );
if( this.lastReportedValue == 0 )
{
preciseAEItemStackCount.get( g ).remove( myStack );
preciseAEItemStackCount.trim();
}
}
this.lastReportedValue = 0;
monitor.getStorageList().findFuzzy( myStack, fzMode ).forEach( iaeItemStack -> lastReportedValue += iaeItemStack.getStackSize() );
}
else
{
this.lastReportedValue = 0;
IAEItemStack precise = monitor.getStorageList().findPrecise( myStack );
if( precise != null ) lastReportedValue = precise.getStackSize();
}
this.updateState();
}
@@ -419,12 +377,23 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
@Override
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan )
public void onStackChange( final IAEStack diffStack, final IStorageChannel chan )
{
if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) && fullStack.equals( this.config.getAEStackInSlot( 0 ) ) && this
.getInstalledUpgrades( Upgrades.FUZZY ) == 0 )
if( chan == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
this.lastReportedValue = fullStack.getStackSize();
IAEItemStack myStack = this.config.getAEStackInSlot( 0 );
if( this.getInstalledUpgrades( Upgrades.FUZZY ) > 0 )
{
final FuzzyMode fzMode = (FuzzyMode) this.getConfigManager().getSetting( Settings.FUZZY_MODE );
if( Platform.itemComparisons().isFuzzyEqualItem( myStack.getDefinition(), ( (IAEItemStack) diffStack ).getDefinition(), fzMode ) )
{
this.lastReportedValue += diffStack.getStackSize();
}
}
else if( diffStack.equals( myStack ) )
{
this.lastReportedValue += diffStack.getStackSize();
}
this.updateState();
}
}
@@ -459,7 +428,7 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
@Override
public void postChange( final IBaseMonitor<IAEItemStack> monitor, final Iterable<IAEItemStack> change, final IActionSource actionSource )
{
this.updateReportingValue( (IMEMonitor<IAEItemStack>) monitor, change );
this.updateReportingValue( (IMEMonitor<IAEItemStack>) monitor );
}
@Override
@@ -636,9 +605,4 @@ public class PartLevelEmitter extends PartUpgradeable implements IEnergyWatcherH
}
}
public static void wipeCache(){
fuzzyAEItemStackCount.clear();
preciseAEItemStackCount.clear();
gridItemCount.clear();
}
}
@@ -19,10 +19,20 @@
package appeng.parts.automation;
import javax.annotation.Nonnull;
import appeng.api.AEApi;
import appeng.container.slot.SlotRestrictedInput;
import appeng.core.Api;
import appeng.helpers.DualityInterface;
import appeng.util.inv.ItemHandlerIterator;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Items;
import net.minecraft.inventory.Slot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.items.IItemHandler;
import appeng.api.config.Upgrades;
@@ -33,6 +43,9 @@ import appeng.util.inv.IAEAppEngInventory;
import appeng.util.inv.InvOperation;
import appeng.util.inv.filter.IAEItemFilter;
import java.util.ArrayList;
import java.util.List;
public abstract class UpgradeInventory extends AppEngInternalInventory implements IAEAppEngInventory
{
@@ -45,6 +58,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
private int capacityUpgrades = 0;
private int inverterUpgrades = 0;
private int craftingUpgrades = 0;
private int patternExpansionUpgrades = 0;
public UpgradeInventory( final IAEAppEngInventory parent, final int s )
{
@@ -81,6 +95,8 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
return this.inverterUpgrades;
case CRAFTING:
return this.craftingUpgrades;
case PATTERN_EXPANSION:
return this.patternExpansionUpgrades;
default:
return 0;
}
@@ -91,7 +107,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
private void updateUpgradeInfo()
{
this.cached = true;
this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0;
this.patternExpansionUpgrades = this.inverterUpgrades = this.capacityUpgrades = this.redstoneUpgrades = this.speedUpgrades = this.fuzzyUpgrades = this.craftingUpgrades = 0;
for( final ItemStack is : this )
{
@@ -121,6 +137,9 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
case CRAFTING:
this.craftingUpgrades++;
break;
case PATTERN_EXPANSION:
this.patternExpansionUpgrades++;
break;
default:
break;
}
@@ -132,6 +151,7 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
this.speedUpgrades = Math.min( this.speedUpgrades, this.getMaxInstalled( Upgrades.SPEED ) );
this.inverterUpgrades = Math.min( this.inverterUpgrades, this.getMaxInstalled( Upgrades.INVERTER ) );
this.craftingUpgrades = Math.min( this.craftingUpgrades, this.getMaxInstalled( Upgrades.CRAFTING ) );
this.patternExpansionUpgrades = Math.min( this.patternExpansionUpgrades, this.getMaxInstalled( Upgrades.PATTERN_EXPANSION ) );
}
@Override
@@ -160,6 +180,13 @@ public abstract class UpgradeInventory extends AppEngInternalInventory implement
}
}
@Nonnull
@Override
public ItemStack extractItem( int slot, int amount, boolean simulate )
{
return super.extractItem( slot, amount, simulate );
}
private class UpgradeInvFilter implements IAEItemFilter
{
@@ -19,17 +19,11 @@
package appeng.parts.misc;
import java.util.*;
import appeng.api.config.Settings;
import appeng.api.config.StorageFilter;
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 javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.config.Settings;
import appeng.api.config.StorageFilter;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation;
@@ -41,9 +35,16 @@ import appeng.api.storage.data.IItemList;
import appeng.core.AELog;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
import appeng.util.Platform;
import appeng.util.inv.ItemHandlerIterator;
import appeng.util.inv.ItemSlot;
import appeng.util.item.AEItemStack;
import org.apache.commons.lang3.tuple.Pair;
import com.google.common.primitives.Ints;
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 java.util.*;
/**
@@ -58,6 +59,8 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private final InventoryCache cache;
private StorageFilter mode;
private ItemStack stackCache = null;
ItemHandlerAdapter( IItemHandler itemHandler, IGridProxyable proxy )
{
this.itemHandler = itemHandler;
@@ -73,28 +76,36 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override
public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src )
{
// Try to reuse the cached stack
@Nullable ItemStack currentCached = stackCache;
stackCache = null;
ItemStack orgInput;
int slotCount = this.itemHandler.getSlots();
if( currentCached != null && iox.isSameType( currentCached ) )
{
// Cache is suitable, just update the count
orgInput = currentCached;
currentCached.setCount( Ints.saturatedCast( iox.getStackSize() ) );
}
else
{
// We need a new stack :-(
orgInput = iox.createItemStack();
}
ItemStack orgInput = iox.createItemStack();
ItemStack remaining = orgInput;
int slotCount = this.itemHandler.getSlots();
boolean simulate = ( type == Actionable.SIMULATE );
List<Pair<Integer, Integer>> injectedList = new ArrayList<>();
// This uses a brute force approach and tries to jam it in every slot the inventory exposes.
for( int i = 0; i < slotCount && !remaining.isEmpty(); i++ )
for ( int i = 0; i < slotCount && !remaining.isEmpty(); i++ )
{
int countPre = remaining.getCount();
remaining = this.itemHandler.insertItem( i, remaining, simulate );
int countPos = remaining.getCount();
if( remaining.isEmpty() )
{
injectedList.add( Pair.of( i, countPre ) );
break;
}
else if( countPos < countPre )
{
injectedList.add( Pair.of( i, countPre - countPos ) );
}
remaining = this.itemHandler.insertItem( i, remaining, type == Actionable.SIMULATE );
}
// Store the stack in the cache for next time.
if( !remaining.isEmpty() && remaining != orgInput )
{
stackCache = remaining;
}
// At this point, we still have some items left...
@@ -106,30 +117,9 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( type == Actionable.MODULATE )
{
if( this.cache.cachedAeStacks.length == 0 )
{
this.cache.update();
}
else
{
for( Pair<Integer, Integer> pair : injectedList )
{
if( pair.getKey() >= this.cache.cachedAeStacks.length )
{
this.cache.update();
break;
}
if( this.cache.cachedAeStacks[pair.getKey()] == null )
{
this.cache.cachedAeStacks[pair.getKey()] = iox.copy().setStackSize( pair.getValue() );
}
else
{
this.cache.cachedAeStacks[pair.getKey()].incStackSize( pair.getValue() );
}
}
}
this.cache
.currentlyCached
.add( AEItemStack.fromItemStack( orgInput ).setStackSize( orgInput.getCount() - remaining.getCount() ) );
}
return AEItemStack.fromItemStack( remaining );
@@ -138,21 +128,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
@Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{
ItemStack requestedItemStack = request.createItemStack();
int remainingSize = requestedItemStack.getCount();
int remainingSize = Ints.saturatedCast( request.getStackSize() );
// Use this to gather the requested items
ItemStack gathered = ItemStack.EMPTY;
final boolean simulate = ( mode == Actionable.SIMULATE );
List<Pair<Integer, Integer>> extractedList = new ArrayList<>();
for ( int i = 0; i < this.itemHandler.getSlots(); i++ )
{
ItemStack stackInInventorySlot = this.itemHandler.getStackInSlot( i );
if( !Platform.itemComparisons().isSameItem( stackInInventorySlot, requestedItemStack ) )
if( !request.isSameType( stackInInventorySlot ) )
{
continue;
}
@@ -191,16 +177,10 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
}
remainingCurrentSlot -= extracted.getCount();
}
}
while ( !extracted.isEmpty() && remainingCurrentSlot > 0 );
} while ( !extracted.isEmpty() && remainingCurrentSlot > 0 );
remainingSize -= stackSizeCurrentSlot - remainingCurrentSlot;
if (!gathered.isEmpty())
{
extractedList.add( Pair.of( i, gathered.getCount() ) );
}
// Done?
if( remainingSize <= 0 )
{
@@ -210,29 +190,17 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
if( !gathered.isEmpty() )
{
IAEItemStack gatheredAEItemStack = AEItemStack.fromItemStack( gathered );
if( mode == Actionable.MODULATE )
{
if( this.cache.cachedAeStacks.length == 0 )
IAEItemStack e = this.cache.currentlyCached.findPrecise( gatheredAEItemStack );
if (e != null)
{
this.cache.update();
}
else
{
for( Pair<Integer, Integer> pair : extractedList )
{
if( this.cache.cachedAeStacks[pair.getKey()] != null )
{
this.cache.cachedAeStacks[pair.getKey()].decStackSize( pair.getValue() );
if( this.cache.cachedAeStacks[pair.getKey()].getStackSize() == 0 )
{
this.cache.cachedAeStacks[pair.getKey()] = null;
}
}
}
e.decStackSize( gathered.getCount() );
}
}
return AEItemStack.fromItemStack( gathered );
return gatheredAEItemStack;
}
return null;
@@ -286,7 +254,7 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
private void postDifference( Iterable<IAEItemStack> a )
{
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 IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -301,11 +269,12 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
}
}
private static class InventoryCache
private static class InventoryCache implements Iterable<ItemSlot>
{
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private final IItemHandler itemHandler;
private final StorageFilter mode;
IItemList<IAEItemStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
public InventoryCache( IItemHandler itemHandler, StorageFilter mode )
{
@@ -315,106 +284,58 @@ class ItemHandlerAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<IAE
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
private StorageFilter getMode()
{
return this.mode;
}
public List<IAEItemStack> update()
{
final List<IAEItemStack> changes = new ArrayList<>();
final int slots = this.itemHandler.getSlots();
// Make room for new slots
if( slots > this.cachedAeStacks.length )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, slots );
}
IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
for( int slot = 0; slot < slots; slot++ )
for ( final ItemSlot is : this )
{
// Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[slot];
ItemStack newIS = this.itemHandler.getStackInSlot( slot );
if( this.mode == StorageFilter.EXTRACTABLE_ONLY && !newIS.isEmpty() )
final ItemStack newIS = !is.isExtractable() && this.getMode() == StorageFilter.EXTRACTABLE_ONLY ? ItemStack.EMPTY : is.getItemStack();
if( !newIS.isEmpty() )
{
if( this.itemHandler.extractItem( slot, 1, true ).isEmpty() )
{
newIS = ItemStack.EMPTY;
}
currentlyOnStorage.add( is.getAEItemStack() );
}
this.handlePossibleSlotChanges( slot, oldAeIS, newIS, changes );
}
// Handle cases where the number of slots actually is lower now than before
if( slots < this.cachedAeStacks.length )
for ( final IAEItemStack is : currentlyCached )
{
for( int slot = slots; slot < this.cachedAeStacks.length; slot++ )
{
final IAEItemStack aeStack = this.cachedAeStacks[slot];
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 );
is.setStackSize( -is.getStackSize() );
}
for ( final IAEItemStack is : currentlyOnStorage )
{
currentlyCached.add( is );
}
for ( final IAEItemStack is : currentlyCached )
{
if( is.getStackSize() != 0 )
{
changes.add( is );
}
}
currentlyCached = currentlyOnStorage;
return changes;
}
private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
@Override
public Iterator<ItemSlot> iterator()
{
if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
{
this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
else
{
this.handleItemChanged( slot, oldAeIS, newIS, changes );
}
return new ItemHandlerIterator( this.itemHandler );
}
private void handleStackSizeChanged( int slot, IAEItemStack oldAeIS, ItemStack newIS, List<IAEItemStack> changes )
{
// 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,16 +1,6 @@
package appeng.parts.misc;
import java.util.*;
import java.util.stream.Collectors;
import appeng.api.storage.IStorageChannel;
import appeng.core.AELog;
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 javax.annotation.Nullable;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.security.IActionSource;
@@ -18,15 +8,22 @@ import appeng.api.networking.storage.IBaseMonitor;
import appeng.api.networking.ticking.TickRateModulation;
import appeng.api.storage.IMEInventory;
import appeng.api.storage.IMEMonitorHandlerReceiver;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.me.GridAccessException;
import appeng.core.AELog;
import appeng.me.helpers.IGridProxyable;
import appeng.me.storage.ITickingMonitor;
import appeng.util.item.AEItemStack;
import com.google.common.primitives.Ints;
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.*;
import javax.annotation.Nonnull;
/**
* Wraps an Item Repository in such a way that it can be used as an IMEInventory for items.
@@ -41,6 +38,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private final IGridProxyable proxyable;
private final InventoryCache cache;
private ItemStack stackCache;
ItemRepositoryAdapter( IItemRepository itemRepository, IGridProxyable proxy )
{
@@ -52,12 +50,29 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override
public IAEItemStack injectItems( IAEItemStack iox, Actionable type, IActionSource src )
{
ItemStack orgInput = iox.createItemStack();
ItemStack remaining = orgInput;
// Try to reuse the cached stack
@Nullable ItemStack currentCached = stackCache;
stackCache = null;
boolean simulate = ( type == Actionable.SIMULATE );
ItemStack orgInput;
if( currentCached != null && iox.isSameType( currentCached ) )
{
// Cache is suitable, just update the count
orgInput = currentCached;
currentCached.setCount( Ints.saturatedCast( iox.getStackSize() ) );
}
else
{
// We need a new stack :-(
orgInput = iox.createItemStack();
}
ItemStack remaining = this.itemRepository.insertItem( orgInput, type == Actionable.SIMULATE );
remaining = this.itemRepository.insertItem( remaining, simulate );
// Store the stack in the cache for next time.
if (!remaining.isEmpty() && remaining != orgInput)
{
stackCache = remaining;
}
// At this point, we still have some items left...
if( remaining == orgInput )
@@ -68,14 +83,9 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
if( type == Actionable.MODULATE )
{
try
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
}
this.cache
.currentlyCached
.add( AEItemStack.fromItemStack( orgInput ).setStackSize( orgInput.getCount() - remaining.getCount() ) );
}
return AEItemStack.fromItemStack( remaining );
@@ -85,36 +95,32 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
@Override
public IAEItemStack extractItems( IAEItemStack request, Actionable mode, IActionSource src )
{
ItemStack requestedItemStack = request.getDefinition();
int remainingSize = (int) Math.min( Integer.MAX_VALUE, request.getStackSize());
int remainingSize = Ints.saturatedCast( request.getStackSize() );
final boolean simulate = ( mode == Actionable.SIMULATE );
ItemStack extracted = this.itemRepository.extractItem( requestedItemStack, remainingSize, simulate );
ItemStack extracted = this.itemRepository.extractItem( request.getDefinition(), remainingSize, simulate );
if( extracted.getCount() > remainingSize )
{
// Something broke. It should never return more than we requested...
// We're going to silently eat the remainder
AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.",
this.itemRepository.getClass().getName(), extracted.toString(), remainingSize );
AELog.warn( "Mod that provided item handler %s is broken. Returned %s items while only requesting %d.", this.itemRepository.getClass().getName(), extracted.toString(), remainingSize );
extracted.setCount( remainingSize );
}
if( !extracted.isEmpty() )
{
IAEItemStack extractedAEItemStack = AEItemStack.fromItemStack( extracted );
if( mode == Actionable.MODULATE )
{
try
IAEItemStack e = this.cache.currentlyCached.findPrecise( extractedAEItemStack );
if (e != null)
{
this.proxyable.getProxy().getTick().alertDevice( this.proxyable.getProxy().getNode() );
}
catch( GridAccessException ex )
{
// meh
e.decStackSize( extracted.getCount() );
}
}
return AEItemStack.fromItemStack( extracted );
return extractedAEItemStack;
}
return null;
}
@@ -146,7 +152,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private void postDifference( Iterable<IAEItemStack> a )
{
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 IMEMonitorHandlerReceiver<IAEItemStack> key = l.getKey();
@@ -186,7 +192,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
private static class InventoryCache
{
private IAEItemStack[] cachedAeStacks = new IAEItemStack[0];
private IItemList<IAEItemStack> currentlyCached = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
private final IItemRepository iItemRepository;
public InventoryCache( IItemRepository iItemRepository )
@@ -196,7 +202,7 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
public IItemList<IAEItemStack> getAvailableItems( IItemList<IAEItemStack> out )
{
Arrays.stream( this.cachedAeStacks ).forEach( out::add );
currentlyCached.iterator().forEachRemaining( out::add );
return out;
}
@@ -204,94 +210,31 @@ class ItemRepositoryAdapter implements IMEInventory<IAEItemStack>, IBaseMonitor<
{
final List<IAEItemStack> changes = new ArrayList<>();
List<IAEItemStack> out = this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).collect(Collectors.toList() );
IItemList<IAEItemStack> currentlyOnStorage = AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ).createList();
this.iItemRepository.getAllItems().stream().map( s -> AEItemStack.fromItemStack( s.itemPrototype ).setStackSize( s.count ) ).forEach( currentlyOnStorage::add );
final int size = out.size();
// Make room for new slots
if( size > this.cachedAeStacks.length )
for ( final IAEItemStack is : currentlyCached )
{
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
is.setStackSize( -is.getStackSize() );
}
for( int x = 0; x < size; x++ )
for ( final IAEItemStack is : currentlyOnStorage )
{
// Save the old stuff
final IAEItemStack oldAeIS = this.cachedAeStacks[x];
final IAEItemStack newIS = out.get( x );
this.handlePossibleSlotChanges( x, oldAeIS, newIS, changes );
currentlyCached.add( is );
}
// Handle cases where the number of slots actually is lower now than before
if( size < this.cachedAeStacks.length )
for ( final IAEItemStack is : currentlyCached )
{
for( int x = 0; x < this.cachedAeStacks.length; x++ )
if( is.getStackSize() != 0 )
{
final IAEItemStack aeStack = this.cachedAeStacks[x];
if( aeStack != null )
{
final IAEItemStack a = aeStack.copy();
a.setStackSize( -a.getStackSize() );
changes.add( a );
}
changes.add( is );
}
// Reduce the cache size
this.cachedAeStacks = Arrays.copyOf( this.cachedAeStacks, size );
}
currentlyCached = currentlyOnStorage;
return changes;
}
private void handlePossibleSlotChanges( int slot, IAEItemStack oldAeIS, IAEItemStack newIS, List<IAEItemStack> changes )
{
if( oldAeIS != null && oldAeIS.isSameType( newIS ) )
{
this.handleStackSizeChanged( slot, oldAeIS, newIS, changes );
}
else
{
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,17 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
@Override
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().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc );
}
}
catch( final GridAccessException e )
{
// :(
this.getProxy().getStorage().postAlterationOfStoredItems( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ), change, this.mySrc );
}
}
catch( final GridAccessException e )
{
// :(
}
}
@Override
@@ -598,7 +595,7 @@ public class PartStorageBus extends PartUpgradeable implements IGridTickable, IC
{
if( channel == AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) )
{
final IMEInventoryHandler<IAEItemStack> out = this.getProxy().isActive() ? this.getInternalHandler() : null;
final IMEInventoryHandler<IAEItemStack> out = this.getInternalHandler();
if( out != null )
{
return Collections.singletonList( out );
@@ -19,11 +19,12 @@
package appeng.parts.p2p;
import java.util.List;
import java.util.*;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import appeng.me.cache.helpers.TunnelCollection;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.capabilities.Capability;
@@ -42,6 +43,7 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private static final IEnergyStorage NULL_ENERGY_STORAGE = new NullEnergyStorage();
private final IEnergyStorage inputHandler = new InputEnergyStorage();
private final IEnergyStorage outputHandler = new OutputEnergyStorage();
private final Queue<PartP2PFEPower> outputs = new ArrayDeque<>();
public PartP2PFEPower( ItemStack is )
{
@@ -108,6 +110,8 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
private class InputEnergyStorage implements IEnergyStorage
{
private boolean iteratingOutputs;
@Override
public int extractEnergy( int maxExtract, boolean simulate )
{
@@ -131,8 +135,14 @@ public class PartP2PFEPower extends PartP2PTunnel<PartP2PFEPower>
final int amountPerOutput = maxReceive / outputTunnels;
int overflow = amountPerOutput == 0 ? maxReceive : maxReceive % amountPerOutput;
for( PartP2PFEPower target : PartP2PFEPower.this.getOutputs() )
if (outputs.isEmpty())
{
for ( PartP2PFEPower o : PartP2PFEPower.this.getOutputs())
outputs.add( o );
}
while ( !outputs.isEmpty() ) {
PartP2PFEPower target = outputs.poll();
final IEnergyStorage output = target.getAttachedEnergyStorage();
final int toSend = amountPerOutput + overflow;
final int received = output.receiveEnergy( toSend, simulate );
@@ -21,10 +21,12 @@ package appeng.parts.reporting;
import java.io.IOException;
import appeng.api.networking.events.MENetworkChannelsChanged;
import appeng.api.networking.events.MENetworkEventSubscribe;
import appeng.api.networking.events.MENetworkPowerStatusChange;
import appeng.api.storage.channels.IFluidStorageChannel;
import appeng.api.storage.data.IAEFluidStack;
import appeng.fluids.util.AEFluidStack;
import appeng.util.item.AEStack;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.renderer.GlStateManager;
@@ -43,7 +45,6 @@ import net.minecraftforge.fml.relauncher.SideOnly;
import appeng.api.AEApi;
import appeng.api.implementations.parts.IPartStorageMonitor;
import appeng.api.networking.security.IActionSource;
import appeng.api.networking.storage.IStackWatcher;
import appeng.api.networking.storage.IStackWatcherHost;
import appeng.api.parts.IPartModel;
@@ -52,7 +53,6 @@ import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IAEStack;
import appeng.api.storage.data.IItemList;
import appeng.client.render.TesrRenderHelper;
import appeng.core.localization.PlayerMessages;
import appeng.helpers.Reflected;
@@ -385,19 +385,87 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
this.configureWatchers();
}
@MENetworkEventSubscribe
public void powerStatusChange( final MENetworkPowerStatusChange ev )
{
if( !this.getProxy().isPowered() )
{
if( this.myWatcher != null )
{
if( this.configuredItem != null )
{
this.configuredItem.setStackSize( 0 );
}
if( this.configuredFluid != null )
{
this.configuredFluid.setStackSize( 0 );
}
}
}
else
{
try
{
if( this.configuredItem != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
if( this.configuredFluid != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) );
}
}
catch( final GridAccessException e )
{
// ;P
}
}
}
@MENetworkEventSubscribe
public void channelChanged( final MENetworkChannelsChanged c )
{
if( !this.getProxy().isPowered() )
{
if( this.myWatcher != null )
{
if( this.configuredItem != null )
{
this.configuredItem.setStackSize( 0 );
}
if( this.configuredFluid != null )
{
this.configuredFluid.setStackSize( 0 );
}
}
}
else
{
try
{
if( this.configuredItem != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class ) ) );
}
if( this.configuredFluid != null )
{
this.updateReportingValue( this.getProxy().getStorage().getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ) );
}
}
catch( final GridAccessException e )
{
// ;P
}
}
}
@Override
public void onStackChange( final IItemList o, final IAEStack fullStack, final IAEStack diffStack, final IActionSource src, final IStorageChannel chan )
public void onStackChange( final IAEStack diffStack, final IStorageChannel chan )
{
if( this.configuredItem != null )
{
if( fullStack == null )
{
this.configuredItem.setStackSize( 0 );
}
else
{
this.configuredItem.setStackSize( fullStack.getStackSize() );
}
long diff = this.configuredItem.getStackSize() + diffStack.getStackSize();
this.configuredItem.setStackSize( diff >= 0 ? this.configuredItem.getStackSize() + diffStack.getStackSize() : 0 );
final long stackSize = this.configuredItem.getStackSize();
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize );
@@ -410,14 +478,8 @@ public abstract class AbstractPartMonitor extends AbstractPartDisplay implements
}
else if( this.configuredFluid != null )
{
if( fullStack == null )
{
this.configuredFluid.setStackSize( 0 );
}
else
{
this.configuredFluid.setStackSize( fullStack.getStackSize() );
}
long diff = this.configuredFluid.getStackSize() + diffStack.getStackSize();
this.configuredFluid.setStackSize( diff >= 0 ? this.configuredFluid.getStackSize() + diffStack.getStackSize() : 0 );
final long stackSize = this.configuredFluid.getStackSize() / 1000;
final String humanReadableText = NUMBER_CONVERTER.toWideReadableForm( stackSize ) + "B";
@@ -206,7 +206,7 @@ public class AppEngInternalInventory extends ItemStackHandler implements Iterabl
this.enableClientEvents = enableClientEvents;
}
private IAEAppEngInventory getTileEntity()
public IAEAppEngInventory getTileEntity()
{
return this.te;
}
@@ -164,6 +164,7 @@ public class TileInterface extends AENetworkInvTile implements IGridTickable, II
super.onReady();
this.duality.initialize();
this.getProxy().setIdlePowerUsage( Math.pow( 4, ( this.getInstalledUpgrades( Upgrades.PATTERN_EXPANSION ) ) ) );
}
@Override
@@ -425,6 +425,7 @@ public class TileIOPort extends AENetworkInvTile implements IUpgradeableHost, IC
if( extracted != null )
{
possible = extracted.getStackSize();
extracted.setCraftable( false );
final IAEStack failed = Platform.poweredInsert( energy, destination, extracted, this.mySrc );
if( failed != null )
+7 -5
View File
@@ -1246,18 +1246,20 @@ public class Platform
if( itemToAdd < input.getStackSize() )
{
final long original = input.getStackSize();
final T leftover = input.copy();
final T split = input.copy();
split.decStackSize( itemToAdd );
input.setStackSize( itemToAdd );
split.add( cell.injectItems( input, Actionable.MODULATE, src ) );
leftover.decStackSize(itemToAdd);
split.setStackSize(itemToAdd);
leftover.add(cell.injectItems(split, Actionable.MODULATE, src));
src.player().ifPresent( player ->
{
final long diff = original - split.getStackSize();
final long diff = original - leftover.getStackSize();
Stats.ItemsInserted.addToPlayer( player, (int) diff );
} );
return split;
return leftover;
}
final T ret = cell.injectItems( input, Actionable.MODULATE, src );
@@ -56,6 +56,6 @@ public class ReadOnlyCollection<T> implements IReadOnlyCollection<T>
@Override
public boolean contains( final Object node )
{
return this.c.contains( node );
return this.c.contains( (T) node );
}
}
@@ -52,7 +52,7 @@ public class ItemHandlerIterator implements Iterator<ItemSlot>
{
throw new NoSuchElementException();
}
this.itemSlot.setExtractable( !this.itemHandler.extractItem( this.slot, 1, true ).isEmpty() );
this.itemSlot.setExtractable( !this.itemHandler.extractItem( this.slot, Integer.MAX_VALUE, true ).isEmpty() );
this.itemSlot.setItemStack( this.itemHandler.getStackInSlot( this.slot ) );
this.itemSlot.setSlot( this.slot );
this.slot++;
+227 -281
View File
@@ -1,6 +1,6 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
* Copyright (c) 2013 - 2020, AlgorithmX2, 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
@@ -18,7 +18,6 @@
package appeng.util.item;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -27,347 +26,294 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import io.netty.buffer.ByteBuf;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.items.ItemHandlerHelper;
import appeng.api.AEApi;
import appeng.api.config.FuzzyMode;
import appeng.api.storage.IStorageChannel;
import appeng.api.storage.channels.IItemStorageChannel;
import appeng.api.storage.data.IAEItemStack;
import appeng.core.Api;
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";
public final class AEItemStack extends AEStack<IAEItemStack> implements IAEItemStack
{
private AESharedItemStack sharedStack;
private Optional<OreReference> oreReference;
private final AESharedItemStack sharedStack;
private Optional<OreReference> oreReference;
@SideOnly( Side.CLIENT )
private String displayName;
@SideOnly( Side.CLIENT )
private List<String> tooltip;
@SideOnly( Side.CLIENT )
private ResourceLocation uniqueID;
@SideOnly(Side.CLIENT)
private String displayName;
@SideOnly(Side.CLIENT)
private List<String> tooltip;
private AEItemStack( final AEItemStack is )
{
this.setStackSize( is.getStackSize() );
this.setCraftable( is.isCraftable() );
this.setCountRequestable( is.getCountRequestable() );
this.sharedStack = is.sharedStack;
this.oreReference = is.oreReference;
}
private AEItemStack(final AEItemStack is) {
this.setStackSize(is.getStackSize());
this.setCraftable(is.isCraftable());
this.setCountRequestable(is.getCountRequestable());
this.sharedStack = is.sharedStack;
this.oreReference = is.oreReference;
}
private AEItemStack( final AESharedItemStack is, long size )
{
this.sharedStack = is;
this.setStackSize( size );
this.setCraftable( false );
this.setCountRequestable( 0 );
this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() );
}
private AEItemStack(final AESharedItemStack is, long size) {
this.sharedStack = is;
this.setStackSize(size);
this.setCraftable(false);
this.setCountRequestable(0);
this.oreReference = OreHelper.INSTANCE.getOre( is.getDefinition() );
}
@Nullable
public static AEItemStack fromItemStack( @Nonnull final ItemStack stack )
{
if( stack.isEmpty() )
{
return null;
}
@Nullable
public static AEItemStack fromItemStack(@Nonnull final ItemStack stack) {
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 )
{
if( i == null )
{
return null;
}
public static IAEItemStack fromNBT( final NBTTagCompound i )
{
if( i == null )
{
return null;
}
final ItemStack itemstack = new ItemStack( i );
if( itemstack.isEmpty() )
{
return null;
}
final ItemStack itemstack = new ItemStack( i );
if( itemstack.isEmpty() )
{
return null;
}
final AEItemStack item = AEItemStack.fromItemStack( itemstack );
item.setStackSize( i.getLong( "Cnt" ) );
item.setCountRequestable( i.getLong( "Req" ) );
item.setCraftable( i.getBoolean( "Craft" ) );
return item;
}
final AEItemStack item = AEItemStack.fromItemStack( itemstack );
@Override
public void writeToNBT( final NBTTagCompound i )
{
this.getDefinition().writeToNBT( i );
i.setLong( "Cnt", this.getStackSize() );
i.setLong( "Req", this.getCountRequestable() );
i.setBoolean( "Craft", this.isCraftable() );
}
item.setStackSize(i.getLong(NBT_STACKSIZE));
item.setCountRequestable(i.getLong(NBT_REQUESTABLE));
item.setCraftable(i.getBoolean(NBT_CRAFTABLE));
return item;
}
public static AEItemStack fromPacket( final ByteBuf data )
{
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;
@Override
public void writeToNBT(final NBTTagCompound i) {
this.getDefinition().writeToNBT( i );
final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) );
final long stackSize = getPacketValue( stackType, data );
final long countRequestable = getPacketValue( countReqType, data );
i.setLong(NBT_STACKSIZE, this.getStackSize());
i.setLong(NBT_REQUESTABLE, this.getCountRequestable());
i.setBoolean(NBT_CRAFTABLE, this.isCraftable());
}
if( itemstack.isEmpty() )
{
return null;
}
public static AEItemStack fromPacket( final ByteBuf data )
{
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;
final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize );
item.setCountRequestable( countRequestable );
item.setCraftable( isCraftable );
return item;
}
final ItemStack itemstack = new ItemStack( ByteBufUtils.readTag( data ) );
final long stackSize = getPacketValue( stackType, data );
final long countRequestable = getPacketValue( countReqType, data );
@Override
public void writeToPacket( final ByteBuf i )
{
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 );
if( itemstack.isEmpty() )
{
return null;
}
i.writeByte( mask );
ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() );
this.putPacketValue( i, this.getStackSize() );
this.putPacketValue( i, this.getCountRequestable() );
}
final AEItemStack item = new AEItemStack( AEItemStackRegistry.getRegisteredStack( itemstack ), stackSize );
item.setCountRequestable( countRequestable );
item.setCraftable( isCraftable );
return item;
}
@Override
public void add( final IAEItemStack option )
{
if( option == null )
{
return;
}
@Override
public void writeToPacket( final ByteBuf i )
{
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 );
this.incStackSize( option.getStackSize() );
this.setCountRequestable( this.getCountRequestable() + option.getCountRequestable() );
this.setCraftable( this.isCraftable() || option.isCraftable() );
}
i.writeByte( mask );
ByteBufUtils.writeTag( i, this.getDefinition().serializeNBT() );
this.putPacketValue( i, this.getStackSize() );
this.putPacketValue( i, this.getCountRequestable() );
}
@Override
public boolean fuzzyComparison( final IAEItemStack other, final FuzzyMode mode )
{
if( mode == FuzzyMode.IGNORE_ALL && OreHelper.INSTANCE.sameOre( this, other ) )
{
return true;
}
@Override
public void add(final IAEItemStack option) {
if (option == null) {
return;
}
final ItemStack itemStack = this.getDefinition();
final ItemStack otherStack = other.getDefinition();
this.incStackSize(option.getStackSize());
this.setCountRequestable(this.getCountRequestable() + option.getCountRequestable());
this.setCraftable(this.isCraftable() || option.isCraftable());
}
return this.fuzzyItemStackComparison( itemStack, otherStack, mode );
}
@Override
public boolean fuzzyComparison(final IAEItemStack other, final FuzzyMode mode) {
final ItemStack itemStack = this.getDefinition();
final ItemStack otherStack = other.getDefinition();
@Override
public IAEItemStack copy()
{
return new AEItemStack( this );
}
return this.fuzzyItemStackComparison(itemStack, otherStack, mode);
}
@Override
public boolean isItem()
{
return true;
}
@Override
public IAEItemStack copy() {
return new AEItemStack(this);
}
@Override
public boolean isFluid()
{
return false;
}
@Override
public boolean isItem()
{
return true;
}
@Override
public IStorageChannel<IAEItemStack> getChannel()
{
return AEApi.instance().storage().getStorageChannel( IItemStorageChannel.class );
}
@Override
public boolean isFluid()
{
return false;
}
@Override
public ItemStack createItemStack()
{
return ItemHandlerHelper.copyStackWithSize( this.getDefinition(), (int) Math.min( Integer.MAX_VALUE, this.getStackSize() ) );
}
@Override
public IStorageChannel<IAEItemStack> getChannel() {
return Api.INSTANCE.storage().getStorageChannel(IItemStorageChannel.class);
}
@Override
public Item getItem()
{
return this.getDefinition().getItem();
}
@Override
public ItemStack createItemStack() {
return ItemHandlerHelper.copyStackWithSize(this.getDefinition(),
(int) Math.min(Integer.MAX_VALUE, this.getStackSize()));
}
@Override
public int getItemDamage()
{
return this.sharedStack.getItemDamage();
}
@Override
public Item getItem() {
return this.getDefinition().getItem();
}
@Override
public boolean sameOre( final IAEItemStack is )
{
return OreHelper.INSTANCE.sameOre( this, is );
}
@Override
public int getItemDamage() {
return this.sharedStack.getItemDamage();
}
@Override
public boolean isSameType( final IAEItemStack otherStack )
{
if( otherStack == null )
{
return false;
}
@Override
public boolean sameOre( final IAEItemStack is )
{
return OreHelper.INSTANCE.sameOre( this, is );
}
return Objects.equals( this.sharedStack, ( (AEItemStack) otherStack ).sharedStack );
}
@Override
public boolean isSameType(final IAEItemStack otherStack) {
if (otherStack == null) {
return false;
}
@Override
public boolean isSameType( final ItemStack otherStack )
{
if( otherStack.isEmpty() )
{
return false;
}
int oldSize = otherStack.getCount();
return Objects.equals(this.sharedStack, ((AEItemStack) otherStack).sharedStack);
}
otherStack.setCount( 1 );
boolean ret = ItemStack.areItemStacksEqual( this.getDefinition(), otherStack );
otherStack.setCount( oldSize );
@Override
public boolean isSameType(final ItemStack otherStack) {
if (otherStack.isEmpty()) {
return false;
}
int oldSize = otherStack.getCount();
return ret;
}
otherStack.setCount(1);
boolean ret = ItemStack.areItemStacksEqual(this.getDefinition(), otherStack);
otherStack.setCount(oldSize);
@Override
public int hashCode()
{
return this.sharedStack.hashCode();
}
return ret;
}
@Override
public boolean equals( final Object ia )
{
if( ia instanceof AEItemStack )
{
return this.isSameType( (AEItemStack) ia );
}
else if( ia instanceof ItemStack )
{
return this.isSameType( (ItemStack) ia );
}
return false;
}
@Override
public int hashCode() {
return this.sharedStack.hashCode();
}
@Override
public String toString()
{
return this.getStackSize() + "x" + this.getDefinition().getItem().getUnlocalizedName() + "@" + this.getDefinition().getItemDamage();
}
@Override
public boolean equals(final Object ia) {
if (ia instanceof AEItemStack) {
return this.isSameType((AEItemStack) ia);
} else if (ia instanceof ItemStack) {
// this actually breaks the equals contract (being equals to unrelated classes)
return equals((ItemStack) ia);
}
return false;
}
@SideOnly( Side.CLIENT )
public List<String> getToolTip()
{
if( this.tooltip == null )
{
this.tooltip = Platform.getTooltip( this.asItemStackRepresentation() );
}
return this.tooltip;
}
@Override
public boolean equals(final ItemStack is) {
return this.isSameType(is);
}
@SideOnly( Side.CLIENT )
public String getDisplayName()
{
if( this.displayName == null )
{
this.displayName = Platform.getItemDisplayName( this.asItemStackRepresentation() );
}
return this.displayName;
}
@Override
public String toString() {
return this.getStackSize() + "x" + this.getDefinition().getItem().getRegistryName();
}
@SideOnly( Side.CLIENT )
public String getModID()
{
if( this.uniqueID == null )
{
this.uniqueID = Item.REGISTRY.getNameForObject( this.getDefinition().getItem() );
}
@SideOnly(Side.CLIENT)
public List<String> getToolTip() {
if (this.tooltip == null) {
this.tooltip = Platform.getTooltip(this.asItemStackRepresentation());
}
return this.tooltip;
}
if( this.uniqueID == null )
{
return "** Null";
}
@SideOnly(Side.CLIENT)
public String getDisplayName() {
if (this.displayName == null) {
this.displayName = Platform.getItemDisplayName(this.asItemStackRepresentation());
}
return this.displayName;
}
return this.uniqueID.getResourceDomain() == null ? "** Null" : this.uniqueID.getResourceDomain();
}
@SideOnly(Side.CLIENT)
public String getModID() {
return this.getDefinition().getItem().getRegistryName().getResourceDomain();
}
public Optional<OreReference> getOre()
{
return this.oreReference;
}
public Optional<OreReference> getOre()
{
return this.oreReference;
}
@Override
public boolean hasTagCompound()
{
return this.getDefinition().hasTagCompound();
}
@Override
public boolean hasTagCompound() {
return this.getDefinition().hasTagCompound();
}
@Override
public ItemStack asItemStackRepresentation()
{
return this.getDefinition().copy();
}
@Override
public ItemStack asItemStackRepresentation() {
return this.getDefinition().copy();
}
@Override
public ItemStack getDefinition()
{
return this.sharedStack.getDefinition();
}
@Override
public ItemStack getDefinition() {
return this.sharedStack.getDefinition();
}
AESharedItemStack getSharedStack()
{
return this.sharedStack;
}
AESharedItemStack getSharedStack() {
return this.sharedStack;
}
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();
private boolean fuzzyItemStackComparison(ItemStack a, ItemStack b, FuzzyMode mode) {
if (a.getItem() == b.getItem() && 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() / a.getMaxDamage();
final float percentDamageOfB = (float) b.getItemDamage() / b.getMaxDamage();
return ( percentDamageOfA > mode.breakPoint ) == ( percentDamageOfB > mode.breakPoint );
}
}
return a.getMetadata() == b.getMetadata();
}
return false;
}
return percentDamageOfA > mode.breakPoint == percentDamageOfB > mode.breakPoint;
}
}
return false;
}
}
@@ -23,7 +23,6 @@
package appeng.util.item;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
@@ -31,56 +30,34 @@ import javax.annotation.Nonnull;
import net.minecraft.item.ItemStack;
import appeng.util.Platform;
public final class AEItemStackRegistry {
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> REGISTRY = new WeakHashMap<>();
private AEItemStackRegistry() {
}
public final class AEItemStackRegistry
{
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> SERVER_REGISTRY = new WeakHashMap<>();
private static final WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> CLIENT_REGISTRY = new WeakHashMap<>();
static synchronized AESharedItemStack getRegisteredStack(final @Nonnull ItemStack itemStack) {
if (itemStack.isEmpty()) {
throw new IllegalArgumentException("stack cannot be empty");
}
private AEItemStackRegistry()
{
}
int oldStackSize = itemStack.getCount();
itemStack.setCount(1);
private static WeakHashMap<AESharedItemStack, WeakReference<AESharedItemStack>> registry()
{
if( Platform.isClient() )
{
return CLIENT_REGISTRY;
}
else
{
return SERVER_REGISTRY;
}
}
AESharedItemStack search = new AESharedItemStack(itemStack);
WeakReference<AESharedItemStack> weak = REGISTRY.get(search);
AESharedItemStack ret = null;
static synchronized AESharedItemStack getRegisteredStack( final @Nonnull ItemStack itemStack )
{
if( itemStack.isEmpty() )
{
throw new IllegalArgumentException( "stack cannot be empty" );
}
if (weak != null) {
ret = weak.get();
}
int oldStackSize = itemStack.getCount();
itemStack.setCount( 1 );
if (ret == null) {
ret = new AESharedItemStack(itemStack.copy());
REGISTRY.put(ret, new WeakReference<>(ret));
}
itemStack.setCount(oldStackSize);
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;
}
return ret;
}
}
@@ -18,263 +18,76 @@
package appeng.util.item;
import java.util.Objects;
import com.google.common.base.Preconditions;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import appeng.api.config.FuzzyMode;
final class AESharedItemStack {
private final ItemStack itemStack;
private final int itemId;
private final int itemDamage;
private final int hashCode;
final class AESharedItemStack implements Comparable<AESharedItemStack>
{
private static final NBTTagCompound LOW_TAG = new NBTTagCompound();
private static final NBTTagCompound HIGH_TAG = new NBTTagCompound();
public AESharedItemStack(final ItemStack itemStack) {
this(itemStack, itemStack.getItemDamage());
}
private final ItemStack itemStack;
private final int itemId;
private final int itemDamage;
private final int hashCode;
/**
* A constructor to explicitly set the damage value and not fetch it from the {@link ItemStack}
*
* @param itemStack The {@link ItemStack} to filter
* @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;
public AESharedItemStack( final ItemStack itemStack )
{
this.itemStack = itemStack;
this.itemId = Item.getIdFromItem( itemStack.getItem() );
this.itemDamage = itemStack.getItemDamage();
this.hashCode = this.makeHashCode();
}
// Ensure this is always called last.
this.hashCode = this.makeHashCode();
}
Bounds getBounds( final FuzzyMode fuzzy, final boolean ignoreMeta )
{
return new Bounds( this.itemStack, fuzzy, ignoreMeta );
}
ItemStack getDefinition() {
return this.itemStack;
}
ItemStack getDefinition()
{
return this.itemStack;
}
int getItemDamage() {
return this.itemDamage;
}
int getItemDamage()
{
return this.itemDamage;
}
@Override
public int hashCode() {
return this.hashCode;
}
int getItemID()
{
return this.itemId;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof AESharedItemStack)) {
return false;
}
@Override
public int hashCode()
{
return this.hashCode;
}
final AESharedItemStack other = (AESharedItemStack) obj;
Preconditions.checkState(this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1");
Preconditions.checkArgument(other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1");
@Override
public boolean equals( final Object obj )
{
if( obj instanceof AESharedItemStack )
{
final AESharedItemStack other = (AESharedItemStack) obj;
if (this.itemStack == other.itemStack) {
return true;
}
return ItemStack.areItemStacksEqual(this.itemStack, other.itemStack);
}
Preconditions.checkState( this.itemStack.getCount() == 1, "ItemStack#getCount() has to be 1" );
Preconditions.checkArgument( other.getDefinition().getCount() == 1, "ItemStack#getCount() has to be 1" );
private int makeHashCode() {
return Objects.hash(
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 );
}
}
}
+126 -143
View File
@@ -18,169 +18,152 @@
package appeng.util.item;
import appeng.api.storage.data.IAEStack;
import io.netty.buffer.ByteBuf;
import appeng.api.storage.data.IAEStack;
public abstract class AEStack<T extends IAEStack<T>> implements IAEStack<T> {
public abstract class AEStack<StackType extends IAEStack<StackType>> implements IAEStack<StackType>
{
private boolean isCraftable;
private long stackSize;
private long countRequestable;
private boolean isCraftable;
private long stackSize;
private long countRequestable;
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;
}
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;
}
return tag.readLong();
}
return tag.readLong();
}
@Override
public long getStackSize() {
return this.stackSize;
}
@Override
public long getStackSize()
{
return this.stackSize;
}
@Override
public T setStackSize(final long ss) {
this.stackSize = ss;
return (T) this;
}
@Override
public StackType setStackSize( final long ss )
{
this.stackSize = ss;
return (StackType) this;
}
@Override
public long getCountRequestable() {
return this.countRequestable;
}
@Override
public long getCountRequestable()
{
return this.countRequestable;
}
@Override
public T setCountRequestable(final long countRequestable) {
this.countRequestable = countRequestable;
return (T) this;
}
@Override
public StackType setCountRequestable( final long countRequestable )
{
this.countRequestable = countRequestable;
return (StackType) this;
}
@Override
public boolean isCraftable() {
return this.isCraftable;
}
@Override
public boolean isCraftable()
{
return this.isCraftable;
}
@Override
public T setCraftable(final boolean isCraftable) {
this.isCraftable = isCraftable;
return (T) this;
}
@Override
public StackType setCraftable( final boolean isCraftable )
{
this.isCraftable = isCraftable;
return (StackType) this;
}
@Override
public T reset() {
this.stackSize = 0;
this.setCountRequestable(0);
this.setCraftable(false);
return (T) this;
}
@Override
public StackType reset()
{
this.stackSize = 0;
// priority = Integer.MIN_VALUE;
this.setCountRequestable( 0 );
this.setCraftable( false );
return (StackType) this;
}
@Override
public T empty() {
final T dup = this.copy();
dup.reset();
return dup;
}
@Override
public StackType empty()
{
final StackType dup = this.copy();
dup.reset();
return dup;
}
@Override
public boolean isMeaningful() {
return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable;
}
@Override
public boolean isMeaningful()
{
return this.stackSize != 0 || this.countRequestable > 0 || this.isCraftable;
}
@Override
public void incStackSize(final long i) {
this.stackSize += i;
}
@Override
public void incStackSize( final long i )
{
this.stackSize += i;
}
@Override
public void decStackSize(final long i) {
this.stackSize -= i;
}
@Override
public void decStackSize( final long i )
{
this.stackSize -= i;
}
@Override
public void incCountRequestable(final long i) {
this.countRequestable += i;
}
@Override
public void incCountRequestable( final long i )
{
this.countRequestable += i;
}
@Override
public void decCountRequestable(final long i) {
this.countRequestable -= i;
}
@Override
public void decCountRequestable( final long i )
{
this.countRequestable -= i;
}
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 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 abstract boolean hasTagCompound();
protected abstract boolean hasTagCompound();
protected void putPacketValue( final ByteBuf tag, final long num )
{
if( num <= 255 )
{
tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) );
}
else if( num <= 65535 )
{
tag.writeShort( (short) ( num + Short.MIN_VALUE ) );
}
else if( num <= 4294967295L )
{
tag.writeInt( (int) ( num + Integer.MIN_VALUE ) );
}
else
{
tag.writeLong( num );
}
}
protected void putPacketValue( final ByteBuf tag, final long num )
{
if( num <= 255 )
{
tag.writeByte( (byte) ( num + Byte.MIN_VALUE ) );
}
else if( num <= 65535 )
{
tag.writeShort( (short) ( num + Short.MIN_VALUE ) );
}
else if( num <= 4294967295L )
{
tag.writeInt( (int) ( num + Integer.MIN_VALUE ) );
}
else
{
tag.writeLong( num );
}
}
}
@@ -0,0 +1,192 @@
/*
* 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 appeng.util.Platform;
import com.google.common.base.Preconditions;
import gregtech.common.items.MetaTool;
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);
}
}
+150 -164
View File
@@ -1,6 +1,6 @@
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
* Copyright (c) 2013 - 2020, AlgorithmX2, 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
@@ -18,212 +18,198 @@
package appeng.util.item;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.NoSuchElementException;
import java.util.concurrent.atomic.AtomicInteger;
import net.minecraftforge.oredict.OreDictionary;
import appeng.util.Platform;
import gregtech.common.items.MetaTool;
import net.minecraft.item.Item;
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;
import appeng.api.storage.data.IItemList;
import appeng.util.item.AESharedItemStack.Bounds;
public final class ItemList implements IItemList<IAEItemStack> {
public final class ItemList implements IItemList<IAEItemStack>
{
private final Reference2ObjectMap<Item, ItemVariantList> records = new Reference2ObjectOpenHashMap<>();
/**
* 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);
private final NavigableMap<AESharedItemStack, IAEItemStack> records = new ConcurrentSkipListMap<>();
@Override
public IAEItemStack findPrecise(final IAEItemStack itemStack) {
if (itemStack == null) {
return null;
}
@Override
public void add( final IAEItemStack option )
{
if( option == null )
{
return;
}
ItemVariantList record = this.records.get(itemStack.getItem());
return record != null ? record.findPrecise(itemStack) : null;
}
final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
@Override
public Collection<IAEItemStack> findFuzzy(final IAEItemStack filter, final FuzzyMode fuzzy) {
if (filter == null) {
return Collections.emptyList();
}
if( st != null )
{
st.add( option );
return;
}
ItemVariantList record = this.records.get(filter.getItem());
return record != null ? record.findFuzzy(filter, fuzzy) : Collections.emptyList();
}
final IAEItemStack opt = option.copy();
@Override
public boolean isEmpty() {
return !this.iterator().hasNext();
}
this.putItemRecord( opt );
}
@Override
public void add(final IAEItemStack itemStack) {
version.incrementAndGet();
@Override
public IAEItemStack findPrecise( final IAEItemStack itemStack )
{
if( itemStack == null )
{
return null;
}
if (itemStack == null) {
return;
}
return this.records.get( ( (AEItemStack) itemStack ).getSharedStack() );
}
this.getOrCreateRecord(itemStack.getItem()).add(itemStack);
}
@Override
public Collection<IAEItemStack> findFuzzy( final IAEItemStack filter, final FuzzyMode fuzzy )
{
if( filter == null )
{
return Collections.emptyList();
}
@Override
public void addStorage(final IAEItemStack itemStack) {
version.incrementAndGet();
final AEItemStack ais = (AEItemStack) filter;
if (itemStack == null) {
return;
}
return ais.getOre().map( or ->
{
if( or.getAEEquivalents().size() == 1 )
{
final IAEItemStack is = or.getAEEquivalents().get( 0 );
this.getOrCreateRecord(itemStack.getItem()).addStorage(itemStack);
}
return this.findFuzzyDamage( is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE );
}
else
{
final Collection<IAEItemStack> output = new ArrayList<>();
@Override
public void addCrafting(final IAEItemStack itemStack) {
version.incrementAndGet();
for( final IAEItemStack is : or.getAEEquivalents() )
{
output.addAll( this.findFuzzyDamage( is, fuzzy, is.getItemDamage() == OreDictionary.WILDCARD_VALUE ) );
}
if (itemStack == null) {
return;
}
return output;
}
} ).orElse( this.findFuzzyDamage( ais, fuzzy, false ) );
}
this.getOrCreateRecord(itemStack.getItem()).addCrafting(itemStack);
}
@Override
public boolean isEmpty()
{
return !this.iterator().hasNext();
}
@Override
public void addRequestable(final IAEItemStack itemStack) {
version.incrementAndGet();
@Override
public void addStorage( final IAEItemStack option )
{
if( option == null )
{
return;
}
if (itemStack == null) {
return;
}
final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
this.getOrCreateRecord(itemStack.getItem()).addRequestable(itemStack);
}
if( st != null )
{
st.incStackSize( option.getStackSize() );
return;
}
@Override
public IAEItemStack getFirstItem() {
for (final IAEItemStack stackType : this) {
return stackType;
}
final IAEItemStack opt = option.copy();
return null;
}
this.putItemRecord( opt );
}
@Override
public int size() {
int size = 0;
for (ItemVariantList entry : records.values()) {
size += entry.size();
}
/*
* public void clean() { Iterator<StackType> i = iterator(); while (i.hasNext()) { StackType AEI =
* i.next(); if ( !AEI.isMeaningful() ) i.remove(); } }
*/
return size;
}
@Override
public void addCrafting( final IAEItemStack option )
{
if( option == null )
{
return;
}
@Override
public Iterator<IAEItemStack> iterator() {
return new ChainedIterator(this.records.values().iterator(), version);
}
final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
@Override
public void resetStatus() {
for (final IAEItemStack i : this) {
i.reset();
}
}
if( st != null )
{
st.setCraftable( true );
return;
}
private ItemVariantList getOrCreateRecord(Item item) {
return this.records.computeIfAbsent(item, this::makeRecordMap);
}
final IAEItemStack opt = option.copy();
opt.setStackSize( 0 );
opt.setCraftable( true );
private ItemVariantList makeRecordMap(Item item) {
if (item.isDamageable() ) {
return new FuzzyItemVariantList();
} 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> {
@Override
public void addRequestable( final IAEItemStack option )
{
if( option == null )
{
return;
}
private final AtomicInteger parentVersion;
private final int version;
private final Iterator<ItemVariantList> parent;
private Iterator<IAEItemStack> next;
final IAEItemStack st = this.records.get( ( (AEItemStack) option ).getSharedStack() );
public ChainedIterator(Iterator<ItemVariantList> iterator, AtomicInteger parentVersion) {
this.parent = iterator;
this.parentVersion = parentVersion;
this.version = parentVersion.get();
this.ensureItems();
}
if( st != null )
{
st.setCountRequestable( st.getCountRequestable() + option.getCountRequestable() );
return;
}
@Override
public boolean hasNext() {
return next != null && next.hasNext();
}
final IAEItemStack opt = option.copy();
opt.setStackSize( 0 );
opt.setCraftable( false );
opt.setCountRequestable( option.getCountRequestable() );
@Override
public IAEItemStack next() {
if (this.next == null) {
throw new NoSuchElementException();
}
if (this.version != this.parentVersion.get()) {
throw new ConcurrentModificationException();
}
this.putItemRecord( opt );
}
IAEItemStack result = this.next.next();
this.ensureItems();
return result;
}
@Override
public IAEItemStack getFirstItem()
{
for( final IAEItemStack stackType : this )
{
return stackType;
}
private void ensureItems() {
if (hasNext()) {
return; // Still items left in the current one
}
return null;
}
// Find the next iterator willing to return some items...
while (this.parent.hasNext()) {
this.next = this.parent.next().iterator();
@Override
public int size()
{
return this.records.size();
}
if (this.next.hasNext()) {
return; // Found one!
}
}
@Override
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();
}
// No more items
this.next = null;
}
}
}
@@ -0,0 +1,118 @@
/*
* 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.
* Copyright (c) 2013 - 2015, AlgorithmX2, All rights reserved.
* 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
@@ -18,59 +18,53 @@
package appeng.util.item;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
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 class MeaningfulItemIterator<T extends IAEItemStack> implements Iterator<T>
{
public MeaningfulItemIterator(final Collection<T> collection) {
this.parent = collection.iterator();
this.next = seekNext();
}
private final Iterator<T> parent;
private T next;
@Override
public boolean hasNext() {
return this.next != null;
}
public MeaningfulItemIterator( final Iterator<T> iterator )
{
this.parent = iterator;
}
@Override
public T next() {
if (this.next == null) {
throw new NoSuchElementException();
}
@Override
public boolean hasNext()
{
while( this.parent.hasNext() )
{
this.next = this.parent.next();
T result = this.next;
this.next = this.seekNext();
return result;
}
if( this.next.isMeaningful() )
{
return true;
}
else
{
this.parent.remove(); // self cleaning :3
}
}
private T seekNext() {
while (this.parent.hasNext()) {
T item = this.parent.next();
this.next = null;
return false;
}
if (item.isMeaningful()) {
return item;
} else {
this.parent.remove();
}
}
@Override
public T next()
{
if( this.next == null )
{
throw new NoSuchElementException();
}
return this.next;
}
@Override
public void remove()
{
this.parent.remove();
}
return null;
}
}
@@ -0,0 +1,51 @@
/*
* 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();
}
}
@@ -43,7 +43,7 @@ public class OreReference
return this.otherOptions;
}
List<IAEItemStack> getAEEquivalents()
public List<IAEItemStack> getAEEquivalents()
{
if( this.aeOtherOptions == null )
{
@@ -450,6 +450,7 @@ item.appliedenergistics2.material.basic_card.name=Basic Card
item.appliedenergistics2.material.blank_pattern.name=Blank Pattern
item.appliedenergistics2.material.calculation_processor.name=Calculation Processor
item.appliedenergistics2.material.card_capacity.name=Capacity Card
item.appliedenergistics2.material.card_pattern_expansion.name=Pattern Expansion Card
item.appliedenergistics2.material.card_fuzzy.name=Fuzzy Card
item.appliedenergistics2.material.card_inverter.name=Inverter Card
item.appliedenergistics2.material.card_redstone.name=Redstone Card
@@ -0,0 +1,6 @@
{
"parent": "item/generated",
"textures": {
"layer0": "appliedenergistics2:items/material_card_pattern_expansion"
}
}
@@ -0,0 +1,37 @@
{
"conditions": [
{
"type": "forge:and",
"values": [
{
"type": "appliedenergistics2:material_exists",
"material": "material.card_capacity"
},
{
"type": "appliedenergistics2:material_exists",
"material": "material.basic_card"
}
]
}
],
"result": {
"type": "appliedenergistics2:part",
"part": "material.card_pattern_expansion"
},
"type": "appliedenergistics2:part_shapeless",
"ingredients": [
{
"type": "appliedenergistics2:part",
"part": "material.advanced_card"
},
[
{
"item": "appliedenergistics2:interface"
},
{
"type": "appliedenergistics2:part",
"part": "part.interface"
}
]
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB