// First, check if the stack can fit.
int missingSpace = itemStack.stackSize;
int emptySlots = 0;
for( int i = indexMin; i < indexMax && missingSpace > 0; i++ ) {
Slot tempSlot = (Slot) this.inventorySlots.get( i );
ItemStack stackInSlot = tempSlot.getStack();
if( stackInSlot == null ) {
emptySlots++;
continue;
}
if( stackInSlot.itemID == itemStack.itemID
&& itemStack.getItemDamage() == stackInSlot.getItemDamage()
&& ItemStack.areItemStackTagsEqual( itemStack, stackInSlot ) ) {
missingSpace -= Math.min( stackInSlot.getMaxStackSize(), tempSlot.getSlotStackLimit() ) - stackInSlot.stackSize;
}
}
// prevent crafting if there is no space for the crafted item.
if( missingSpace > 0 )
if( emptySlots == 0 )
return false;
// Try to merge with existing stacks.
if( itemStack.isStackable() ) {
for( int i = indexMin; i < indexMax; i++ ) {
if( itemStack.stackSize <= 0 )
break;
Slot targetSlot = (Slot) this.inventorySlots.get( i );
ItemStack stackInSlot = targetSlot.getStack();
if( stackInSlot == null )
continue;
if( stackInSlot.itemID == itemStack.itemID
&& (!itemStack.getHasSubtypes() || itemStack.getItemDamage() == stackInSlot.getItemDamage())
&& ItemStack.areItemStackTagsEqual( itemStack, stackInSlot ) ) {
int sum = itemStack.stackSize + stackInSlot.stackSize;
int maxStackSize = Math.min( stackInSlot.getMaxStackSize(), targetSlot.getSlotStackLimit() );
if( sum <= maxStackSize ) {
stackInSlot.stackSize = sum;
targetSlot.onSlotChanged();
return true;
} else if( stackInSlot.stackSize < maxStackSize ) {
itemStack.stackSize -= maxStackSize - stackInSlot.stackSize;
stackInSlot.stackSize = maxStackSize;
targetSlot.onSlotChanged();
}
}
}
}
// Add to an empty slot.
if( itemStack.stackSize > 0 ) {
for( int i = indexMin; i < indexMax; i++ ) {
Slot targetSlot = (Slot) this.inventorySlots.get( i );
ItemStack stackInSlot = targetSlot.getStack();
if( stackInSlot != null )
continue;
targetSlot.putStack( itemStack );
targetSlot.onSlotChanged();
return true;
}
}
return true;