60 lines
1.4 KiB
Kotlin
60 lines
1.4 KiB
Kotlin
|
package net.shadowfacts.phycon.network.block.terminal
|
||
|
|
||
|
import alexiil.mc.lib.attributes.item.ItemStackUtil
|
||
|
import net.minecraft.inventory.BasicInventory
|
||
|
import net.minecraft.item.ItemStack
|
||
|
import kotlin.math.min
|
||
|
|
||
|
/**
|
||
|
* @author shadowfacts
|
||
|
*/
|
||
|
class TerminalBufferInventory(size: Int): BasicInventory(size) {
|
||
|
|
||
|
enum class Mode {
|
||
|
TO_NETWORK, FROM_NETWORK, UNASSIGNED
|
||
|
}
|
||
|
|
||
|
private val modes = Array(size) { Mode.UNASSIGNED }
|
||
|
|
||
|
fun insertFromNetwork(stack: ItemStack): ItemStack {
|
||
|
var remaining = stack.copy()
|
||
|
for (slot in 0 until invSize) {
|
||
|
if (modes[slot] == Mode.TO_NETWORK) continue
|
||
|
|
||
|
remaining = insertFromNetwork(stack, slot)
|
||
|
|
||
|
if (remaining.isEmpty) {
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
return remaining
|
||
|
}
|
||
|
|
||
|
private fun insertFromNetwork(stack: ItemStack, slot: Int): ItemStack {
|
||
|
val mode = modes[slot]
|
||
|
if (mode == Mode.TO_NETWORK) return stack
|
||
|
val current = getInvStack(slot)
|
||
|
if (current.isEmpty) {
|
||
|
setInvStack(slot, stack)
|
||
|
modes[slot] = Mode.FROM_NETWORK
|
||
|
return ItemStack.EMPTY
|
||
|
} else if (ItemStackUtil.areEqualIgnoreAmounts(stack, current)) {
|
||
|
val toTransfer = min(current.maxCount - current.count, stack.count)
|
||
|
current.count += toTransfer
|
||
|
stack.count -= toTransfer
|
||
|
modes[slot] = Mode.FROM_NETWORK
|
||
|
return stack
|
||
|
} else {
|
||
|
return stack
|
||
|
}
|
||
|
}
|
||
|
|
||
|
override fun setInvStack(slot: Int, stack: ItemStack) {
|
||
|
if (stack.isEmpty) {
|
||
|
modes[slot] = Mode.UNASSIGNED
|
||
|
}
|
||
|
super.setInvStack(slot, stack)
|
||
|
}
|
||
|
|
||
|
}
|