MatteryContainer now save only non empty itemstacks

This commit is contained in:
DBotThePony 2022-10-21 14:02:16 +07:00
parent 5a70c22acc
commit cac0b2fadb
Signed by: DBot
GPG Key ID: DCC23B5715498507

View File

@ -1,5 +1,6 @@
package ru.dbotthepony.mc.otm.container package ru.dbotthepony.mc.otm.container
import it.unimi.dsi.fastutil.ints.IntAVLTreeSet
import net.minecraft.world.item.ItemStack import net.minecraft.world.item.ItemStack
import net.minecraft.nbt.CompoundTag import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.ListTag import net.minecraft.nbt.ListTag
@ -9,6 +10,7 @@ import kotlin.jvm.JvmOverloads
import net.minecraft.world.entity.player.Player import net.minecraft.world.entity.player.Player
import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntity
import ru.dbotthepony.mc.otm.core.ifHas import ru.dbotthepony.mc.otm.core.ifHas
import ru.dbotthepony.mc.otm.core.set
import java.util.* import java.util.*
@Suppress("UNUSED") @Suppress("UNUSED")
@ -59,7 +61,7 @@ open class MatteryContainer(val watcher: Runnable, private val size: Int) : Cont
setChanged() setChanged()
} }
fun deserializeNBT(tag: ListTag?) { private fun deserializeNBT(tag: ListTag?) {
Arrays.fill(slots, ItemStack.EMPTY) Arrays.fill(slots, ItemStack.EMPTY)
if (tag == null) { if (tag == null) {
@ -67,9 +69,40 @@ open class MatteryContainer(val watcher: Runnable, private val size: Int) : Cont
return return
} }
var isIndexed = true
for (i in 0 until tag.size.coerceAtMost(size)) {
if (!(tag[i] as CompoundTag).contains("slotIndex")) {
isIndexed = false
break
}
}
if (isIndexed) {
val freeSlots = IntAVLTreeSet()
for (i in 0 until size)
freeSlots.add(i)
for (i in 0 until tag.size.coerceAtMost(size)) {
val nbt = tag[i] as CompoundTag
var slotID = nbt.getInt("slotIndex")
if (freeSlots.remove(slotID)) {
slots[slotID] = ItemStack.of(nbt)
} else if (freeSlots.isEmpty()) {
break
} else {
slotID = freeSlots.firstInt()
freeSlots.remove(slotID)
slots[slotID] = ItemStack.of(nbt)
}
}
} else {
for (i in 0 until tag.size.coerceAtMost(size)) { for (i in 0 until tag.size.coerceAtMost(size)) {
slots[i] = ItemStack.of(tag[i] as CompoundTag) slots[i] = ItemStack.of(tag[i] as CompoundTag)
} }
}
setChanged() setChanged()
} }
@ -91,8 +124,12 @@ open class MatteryContainer(val watcher: Runnable, private val size: Int) : Cont
fun serializeNBT(): ListTag { fun serializeNBT(): ListTag {
return ListTag().also { return ListTag().also {
for (i in 0 until size) { for ((i, item) in slots.withIndex()) {
it.add(this[i].serializeNBT()) if (!item.isEmpty) {
it.add(item.serializeNBT().also {
it["slotIndex"] = i
})
}
} }
} }
} }