Fix block energy storage "deserializing" stuff even if it is missing

This commit is contained in:
DBotThePony 2023-03-11 12:05:30 +07:00
parent 92c9339dbb
commit d811a671c5
Signed by: DBot
GPG Key ID: DCC23B5715498507
2 changed files with 15 additions and 4 deletions

View File

@ -20,6 +20,7 @@ import ru.dbotthepony.mc.otm.capability.FlowDirection
import ru.dbotthepony.mc.otm.core.math.Decimal import ru.dbotthepony.mc.otm.core.math.Decimal
import ru.dbotthepony.mc.otm.core.math.defineDecimal import ru.dbotthepony.mc.otm.core.math.defineDecimal
import ru.dbotthepony.mc.otm.core.nbt.map import ru.dbotthepony.mc.otm.core.nbt.map
import ru.dbotthepony.mc.otm.core.nbt.mapPresent
import ru.dbotthepony.mc.otm.core.nbt.set import ru.dbotthepony.mc.otm.core.nbt.set
sealed class BlockEnergyStorageImpl( sealed class BlockEnergyStorageImpl(
@ -139,10 +140,10 @@ sealed class BlockEnergyStorageImpl(
override fun deserializeNBT(nbt: CompoundTag?) { override fun deserializeNBT(nbt: CompoundTag?) {
if (nbt == null) return if (nbt == null) return
batteryLevel = nbt.map(ENERGY_STORED_KEY, Decimal.Companion::deserializeNBT) ?: Decimal.ZERO batteryLevel = nbt.mapPresent(ENERGY_STORED_KEY, Decimal.Companion::deserializeNBT) ?: Decimal.ZERO
maxBatteryLevelStorage = nbt.map(ENERGY_STORED_MAX_KEY, Decimal.Companion::deserializeNBT) maxBatteryLevelStorage = nbt.mapPresent(ENERGY_STORED_MAX_KEY, Decimal.Companion::deserializeNBT)
maxInputStorage = nbt.map(MAX_INPUT_KEY, Decimal.Companion::deserializeNBT) maxInputStorage = nbt.mapPresent(MAX_INPUT_KEY, Decimal.Companion::deserializeNBT)
maxOutputStorage = nbt.map(MAX_OUTPUT_KEY, Decimal.Companion::deserializeNBT) maxOutputStorage = nbt.mapPresent(MAX_OUTPUT_KEY, Decimal.Companion::deserializeNBT)
} }
var resolver: LazyOptional<IMatteryEnergyStorage> = LazyOptional.of { this } var resolver: LazyOptional<IMatteryEnergyStorage> = LazyOptional.of { this }

View File

@ -59,6 +59,16 @@ inline fun <R, reified T : Tag?> CompoundTag.map(key: String, consumer: (T) -> R
return null return null
} }
inline fun <R, reified T : Tag> CompoundTag.mapPresent(key: String, consumer: (T) -> R): R? {
val tag = get(key)
if (tag is T) {
return consumer(tag)
}
return null
}
fun <T> CompoundTag.mapString(index: String, mapper: (String) -> T, orElse: T): T { fun <T> CompoundTag.mapString(index: String, mapper: (String) -> T, orElse: T): T {
val tag = this[index] as? StringTag ?: return orElse val tag = this[index] as? StringTag ?: return orElse
return mapper.invoke(tag.asString) return mapper.invoke(tag.asString)