PhysicalConnectivity/src/main/kotlin/net/shadowfacts/phycon/util/BasicInventoryExtensions.kt

64 lines
1.6 KiB
Kotlin

package net.shadowfacts.phycon.util
import alexiil.mc.lib.attributes.item.ItemStackUtil
import net.minecraft.inventory.BasicInventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag
import java.lang.RuntimeException
import kotlin.math.min
/**
* @author shadowfacts
*/
fun BasicInventory.toTag(): ListTag {
val list = ListTag()
for (slot in 0 until invSize) {
val stack = getInvStack(slot)
if (!stack.isEmpty) {
val stackTag = stack.toTag(CompoundTag())
stackTag.putInt("Slot", slot)
list.add(stackTag)
}
}
return list
}
fun BasicInventory.fromTag(list: ListTag) {
if (list.listType != 10) throw RuntimeException("Can't decode BasicInventory from list tag that does not contain compound tags")
this.clear()
for (tag in list) {
val compound = tag as CompoundTag
val stack = ItemStack.fromTag(compound)
val slot = compound.getInt("Slot")
setInvStack(slot, stack)
}
}
fun BasicInventory.insert(stack: ItemStack, slot: Int): ItemStack {
@Suppress("NAME_SHADOWING") val stack = stack.copy()
val current = getInvStack(slot)
if (current.isEmpty) {
setInvStack(slot, stack)
return ItemStack.EMPTY
} else if (ItemStackUtil.areEqualIgnoreAmounts(stack, current)) {
val toTransfer = min(current.maxCount - current.count, stack.count)
current.count += toTransfer
stack.count -= toTransfer
return stack
} else {
return stack
}
}
fun BasicInventory.insert(stack: ItemStack): ItemStack {
var remaining = stack
for (slot in 0 until invSize) {
remaining = insert(stack, slot)
if (remaining.isEmpty) {
break
}
}
return remaining
}