From de3a08f02ad188dc0d41deed2e5dc31e6ba24d49 Mon Sep 17 00:00:00 2001 From: firenoo <49818773+firenoo@users.noreply.github.com> Date: Mon, 17 Jul 2023 10:52:04 -0700 Subject: [PATCH] Fix bad hash function + Add new P2P compat (#31) * Update buildscript * Use CityHash64 Should fix an insidious bug where two p2ps could have the same hash if the first p2p has coords (x=a,y=b,z=c,facing=F,dim=D) and the second p2p has coords (x=-a-1,y=b,z=c,facing=F,dim=D). This is because using XOR with a negative coord causes it to flip in two's complement. * Add support for new static p2p types Add some error messages too * Pre-merge cleanup --- build.gradle | 134 +++++++++++++++--- dependencies.gradle | 2 +- .../com/projecturanus/betterp2p/BetterP2P.kt | 2 +- .../java/com/projecturanus/betterp2p/Proxy.kt | 29 ++-- .../betterp2p/network/HashHelper.kt | 55 ++++--- .../betterp2p/util/CableBusUtil.kt | 6 +- .../betterp2p/util/p2p/P2PUtil.kt | 56 ++++++-- .../assets/betterp2p/lang/en_US.lang | 1 + 8 files changed, 216 insertions(+), 69 deletions(-) diff --git a/build.gradle b/build.gradle index a8b7532..35dd43e 100644 --- a/build.gradle +++ b/build.gradle @@ -1,4 +1,4 @@ -//version: 1684218858 +//version: 1689101527 /* DO NOT CHANGE THIS FILE! Also, you may replace this file at any time if there is an update available. @@ -69,7 +69,7 @@ plugins { id 'com.diffplug.spotless' version '6.13.0' apply false // 6.13.0 is the last jvm8 supporting version id 'com.modrinth.minotaur' version '2.+' apply false id 'com.matthewprenger.cursegradle' version '1.4.0' apply false - id 'com.gtnewhorizons.retrofuturagradle' version '1.3.14' + id 'com.gtnewhorizons.retrofuturagradle' version '1.3.19' } print("You might want to check out './gradlew :faq' if your build fails.\n") @@ -115,6 +115,8 @@ propertyDefaultIfUnset("usesMixinDebug", project.usesMixins) propertyDefaultIfUnset("forceEnableMixins", false) propertyDefaultIfUnset("channel", "stable") propertyDefaultIfUnset("mappingsVersion", "12") +propertyDefaultIfUnset("usesMavenPublishing", true) +propertyDefaultIfUnset("mavenPublishUrl", "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases") propertyDefaultIfUnset("modrinthProjectId", "") propertyDefaultIfUnset("modrinthRelations", "") propertyDefaultIfUnset("curseForgeProjectId", "") @@ -357,7 +359,24 @@ catch (Exception ignored) { String identifiedVersion String versionOverride = System.getenv("VERSION") ?: null try { - identifiedVersion = versionOverride == null ? gitVersion() : versionOverride + // Produce a version based on the tag, or for branches something like 0.2.2-configurable-maven-and-extras.38+43090270b6-dirty + if (versionOverride == null) { + def gitDetails = versionDetails() + def isDirty = gitVersion().endsWith(".dirty") // No public API for this, isCleanTag has a different meaning + String branchName = gitDetails.branchName + branchName = branchName.replaceAll("[^a-zA-Z0-9-]+", "-") // sanitize branch names for semver + identifiedVersion = gitDetails.lastTag + if (gitDetails.commitDistance > 0) { + identifiedVersion += "-${branchName}.${gitDetails.commitDistance}+${gitDetails.gitHash}" + if (isDirty) { + identifiedVersion += "-dirty" + } + } else if (isDirty) { + identifiedVersion += "-${branchName}+${gitDetails.gitHash}-dirty" + } + } else { + identifiedVersion = versionOverride + } } catch (Exception ignored) { out.style(Style.Failure).text( @@ -465,10 +484,19 @@ sourceSets { } } -if (file('addon.gradle').exists()) { +if (file('addon.gradle.kts').exists()) { + apply from: 'addon.gradle.kts' +} else if (file('addon.gradle').exists()) { apply from: 'addon.gradle' } +// File for local tweaks not commited to Git +if (file('addon.local.gradle.kts').exists()) { + apply from: 'addon.local.gradle.kts' +} else if (file('addon.local.gradle').exists()) { + apply from: 'addon.local.gradle' +} + // Allow unsafe repos but warn repositories.configureEach { repo -> if (repo instanceof org.gradle.api.artifacts.repositories.UrlArtifactRepository) { @@ -479,7 +507,14 @@ repositories.configureEach { repo -> } } -apply from: 'repositories.gradle' +if (file('repositories.gradle.kts').exists()) { + apply from: 'repositories.gradle.kts' +} else if (file('repositories.gradle').exists()) { + apply from: 'repositories.gradle' +} else { + logger.error("Neither repositories.gradle.kts nor repositories.gradle was found, make sure you extracted the full ExampleMod template.") + throw new RuntimeException("Missing repositories.gradle[.kts]") +} configurations { runtimeClasspath.extendsFrom(runtimeOnlyNonPublishable) @@ -611,7 +646,32 @@ configurations.all { } } -apply from: 'dependencies.gradle' +dependencies { + constraints { + def minGtnhLibVersion = "0.0.13" + implementation("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + runtimeOnly("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + devOnlyNonPublishable("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + runtimeOnlyNonPublishable("com.github.GTNewHorizons:GTNHLib:${minGtnhLibVersion}") { + because("fixes duplicate mod errors in java 17 configurations using old gtnhlib") + } + } +} + +if (file('dependencies.gradle.kts').exists()) { + apply from: 'dependencies.gradle.kts' +} else if (file('dependencies.gradle').exists()) { + apply from: 'dependencies.gradle' +} else { + logger.error("Neither dependencies.gradle.kts nor dependencies.gradle was found, make sure you extracted the full ExampleMod template.") + throw new RuntimeException("Missing dependencies.gradle[.kts]") +} def mixingConfigRefMap = 'mixins.' + modId + '.refmap.json' def mixinTmpDir = buildDir.path + File.separator + 'tmp' + File.separator + 'mixins' @@ -724,13 +784,13 @@ ext.java17PatchDependenciesCfg = configurations.create("java17PatchDependencies" } dependencies { - def lwjgl3ifyVersion = '1.3.5' + def lwjgl3ifyVersion = '1.4.0' def asmVersion = '9.4' if (modId != 'lwjgl3ify') { java17Dependencies("com.github.GTNewHorizons:lwjgl3ify:${lwjgl3ifyVersion}") } if (modId != 'hodgepodge') { - java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.2.13') + java17Dependencies('com.github.GTNewHorizons:Hodgepodge:2.2.19') } java17PatchDependencies('net.minecraft:launchwrapper:1.15') {transitive = false} @@ -979,6 +1039,9 @@ idea { } } runConfigurations { + "0. Build and Test"(Gradle) { + taskNames = ["build"] + } "1. Run Client"(Gradle) { taskNames = ["runClient"] } @@ -1098,6 +1161,11 @@ tasks.named("processIdeaSettings").configure { dependsOn("injectTags") } +tasks.named("ideVirtualMainClasses").configure { + // Make IntelliJ "Build project" build the mod jars + dependsOn("jar", "reobfJar", "spotlessCheck") +} + // workaround variable hiding in pom processing def projectConfigs = project.configurations @@ -1118,12 +1186,14 @@ publishing { } repositories { - maven { - url = "http://jenkins.usrv.eu:8081/nexus/content/repositories/releases" - allowInsecureProtocol = true - credentials { - username = System.getenv("MAVEN_USER") ?: "NONE" - password = System.getenv("MAVEN_PASSWORD") ?: "NONE" + if (usesMavenPublishing.toBoolean()) { + maven { + url = mavenPublishUrl + allowInsecureProtocol = mavenPublishUrl.startsWith("http://") // Mostly for the GTNH maven + credentials { + username = System.getenv("MAVEN_USER") ?: "NONE" + password = System.getenv("MAVEN_PASSWORD") ?: "NONE" + } } } } @@ -1276,12 +1346,14 @@ tasks.register('faq') { description = 'Prints frequently asked questions about building a project' doLast { - print("If your build fails to fetch dependencies, they might have been deleted and replaced by newer " + - "versions.\nCheck if the versions you try to fetch are still on the distributing sites.\n" + - "The links can be found in repositories.gradle and build.gradle:repositories, " + - "not build.gradle:buildscript.repositories - this one is for gradle plugin metadata.\n\n" + + print("If your build fails to fetch dependencies, run './gradlew updateDependencies'. " + + "Or you can manually check if the versions are still on the distributing sites - " + + "the links can be found in repositories.gradle and build.gradle:repositories, " + + "but not build.gradle:buildscript.repositories - those ones are for gradle plugin metadata.\n\n" + "If your build fails to recognize the syntax of new Java versions, enable Jabel in your " + - "gradle.properties. See how it's done in GTNH ExampleMod/gradle.properties.") + "gradle.properties. See how it's done in GTNH ExampleMod/gradle.properties. " + + "However, keep in mind that Jabel enables only syntax features, but not APIs that were introduced in " + + "Java 9 or later.") } } @@ -1342,8 +1414,14 @@ boolean isNewBuildScriptVersionAvailable() { String currentBuildScript = getFile("build.gradle").getText() String currentBuildScriptHash = getVersionHash(currentBuildScript) - String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() - String availableBuildScriptHash = getVersionHash(availableBuildScript) + String availableBuildScriptHash + try { + String availableBuildScript = availableBuildScriptUrl().newInputStream(parameters).getText() + availableBuildScriptHash = getVersionHash(availableBuildScript) + } catch (IOException e) { + logger.warn("Could not check for buildscript update availability: {}", e.message) + return false + } boolean isUpToDate = currentBuildScriptHash.empty || availableBuildScriptHash.empty || currentBuildScriptHash == availableBuildScriptHash return !isUpToDate @@ -1508,3 +1586,17 @@ def getSecondaryArtifacts() { if (apiPackage) secondaryArtifacts += [apiJar] return secondaryArtifacts } + +// For easier scripting of things that require variables defined earlier in the buildscript +if (file('addon.late.gradle.kts').exists()) { + apply from: 'addon.late.gradle.kts' +} else if (file('addon.late.gradle').exists()) { + apply from: 'addon.late.gradle' +} + +// File for local tweaks not commited to Git +if (file('addon.late.local.gradle.kts').exists()) { + apply from: 'addon.late.local.gradle.kts' +} else if (file('addon.late.local.gradle').exists()) { + apply from: 'addon.late.local.gradle' +} diff --git a/dependencies.gradle b/dependencies.gradle index 9890c13..4af852a 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -1,7 +1,7 @@ // Add your dependencies here dependencies { - api('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-204-GTNH:dev') + api('com.github.GTNewHorizons:Applied-Energistics-2-Unofficial:rv3-beta-240-GTNH:dev') api('com.github.GTNewHorizons:Forgelin:1.9.2-GTNH-1.7.10-Edition') api('com.github.GTNewHorizons:BuildCraft:7.1.27:dev') // Some optional P2P tunnel support diff --git a/src/main/java/com/projecturanus/betterp2p/BetterP2P.kt b/src/main/java/com/projecturanus/betterp2p/BetterP2P.kt index 9fc43b7..e3d6fe0 100644 --- a/src/main/java/com/projecturanus/betterp2p/BetterP2P.kt +++ b/src/main/java/com/projecturanus/betterp2p/BetterP2P.kt @@ -20,7 +20,7 @@ const val MODID = "betterp2p" * * MODVER below is handled by gradle, ignore IDE errors. */ -@Mod(modid = MODID, version = MODVER, modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", dependencies = "required-after:appliedenergistics2; required-after:forgelin;") +@Mod(modid = MODID, version = MODVER, modLanguageAdapter = "net.shadowfacts.forgelin.KotlinAdapter", dependencies = "required-after:appliedenergistics2@[rv3-beta-238,); required-after:forgelin;") object BetterP2P { lateinit var logger: Logger diff --git a/src/main/java/com/projecturanus/betterp2p/Proxy.kt b/src/main/java/com/projecturanus/betterp2p/Proxy.kt index 09d1e94..10688a1 100644 --- a/src/main/java/com/projecturanus/betterp2p/Proxy.kt +++ b/src/main/java/com/projecturanus/betterp2p/Proxy.kt @@ -52,58 +52,59 @@ open class CommonProxy { */ open fun initTunnels() { val partDefs = AEApi.instance().definitions().parts() + var typeId = 0 registerTunnel( def = partDefs.p2PTunnelME(), - type = TunnelType.ME, + type = typeId++, classType = PartP2PTunnelME::class.java) registerTunnel( def = partDefs.p2PTunnelEU(), - type = TunnelType.IC2_POWER, + type = typeId++, classType = PartP2PIC2Power::class.java) registerTunnel( def = partDefs.p2PTunnelRF(), - type = TunnelType.RF_POWER, + type = typeId++, classType = PartP2PRFPower::class.java) registerTunnel( def = partDefs.p2PTunnelRedstone(), - type = TunnelType.REDSTONE, + type = typeId++, classType = PartP2PRedstone::class.java) registerTunnel( def = partDefs.p2PTunnelLiquids(), - type = TunnelType.FLUID, + type = typeId++, classType = PartP2PLiquids::class.java) registerTunnel( def = partDefs.p2PTunnelItems(), - type = TunnelType.ITEM, + type = typeId++, classType = PartP2PItems::class.java) registerTunnel( def = partDefs.p2PTunnelLight(), - type = TunnelType.LIGHT, + type = typeId++, classType = PartP2PLight::class.java) registerTunnel( def = partDefs.p2PTunnelOpenComputers(), - type = TunnelType.COMPUTER_MESSAGE, + type = typeId++, classType = PartP2POpenComputers::class.java) registerTunnel( def = partDefs.p2PTunnelPneumaticCraft(), - type = TunnelType.PRESSURE, + type = typeId++, classType = PartP2PPressure::class.java) registerTunnel( def = partDefs.p2PTunnelGregtech(), - type = TunnelType.GT_POWER, + type = typeId++, classType = PartP2PGT5Power::class.java) registerTunnel( def = partDefs.p2PTunnelMEInterface(), - type = TunnelType.ME_INTERFACE, + type = typeId++, classType = PartP2PInterface::class.java) } - private fun registerTunnel(def: IItemDefinition, type: TunnelType, classType: Class>) { + private fun registerTunnel(def: IItemDefinition, type: Int, classType: Class>) { if (def.isEnabled) { val stack = def.maybeStack(1).get() - val info = TunnelInfo(type.ordinal, stack, classType) + val info = TunnelInfo(type, stack, classType) tunnelTypes[classType] = info - tunnelIndices[type.ordinal] = info + tunnelIndices[type] = info } } diff --git a/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt b/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt index 444f97c..0162e77 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt @@ -2,46 +2,57 @@ package com.projecturanus.betterp2p.network import appeng.parts.p2p.PartP2PTunnel + /** * Generates a 64-bit hash code from X, Y, Z, Facing, and Dimension info. - * bits 0-15: x - * bits 16-31: y - * bits 32-47: z + * bits 0-47: FashHash of (x, y, z) -> * bits 48-59: dim * bits 60-62: facing * bit 63: Reserved */ fun hashP2P(x: Int, y: Int, z: Int, facing: Int, dim: Int): Long { - var ret = facing.toLong() shl 60 - ret = ret or xorCollapse16(x).toLong() - ret = ret or (xorCollapse16(y).toLong() shl 16) - ret = ret or (xorCollapse16(z).toLong() shl 32) - ret = ret or (xorCollapse12(dim).toLong() shl 48) - return ret + var ret = facing.toULong() shl 61 + val lo: ULong = x.toULong() or (y.toULong() shl 32) + val hi: ULong = z.toULong() or (dim.toULong() shl 32) + var hash = hashLen16(lo, hi) + hash = hash xor (hash shr 60) + return (ret or hash).toLong() } fun hashP2P(p: PartP2PTunnel<*>): Long = hashP2P(p.location.x, p.location.y, p.location.z, p.side.ordinal, p.location.dimension) +const val k2 = 0x9ae16a3b2f90404fUL + /** - * Collapse an 32-bit integer into a 16-bit integer through - * the XOR operator. + * Fetches the contiguous byte-aligned 64 bits from the 128 bit "register". Only works for indexes 1-7. + * lo - low 64 bits + * hi - high 64 bits + * idx - start byte index, should be 1-7. don't even bother using this method for other amounts */ -private fun xorCollapse16(input: Int): Int { - var ret = input and 0xFFFF - ret = ret xor ((input ushr 16) and 0xFFFF) - return ret +private fun fetch64(lo: ULong, hi: ULong, idx: Int): ULong { + return (lo shr (idx * Byte.SIZE_BITS)) or (hi shl ULong.SIZE_BITS - (idx * Byte.SIZE_BITS)) } /** - * Collapse an 32-bit integer into a 12-bit integer through - * the XOR operator. + * City64 hash. It's basically black magic, but here's a link + * https://opensource.googleblog.com/2011/04/introducing-cityhash.html */ -private fun xorCollapse12(input: Int): Int { - var ret = input and 0xFFF - ret = ret xor ((input ushr 12) and 0xFFF) - ret = ret xor ((input ushr 12) and 0xFFF) - return ret +@OptIn(kotlin.ExperimentalStdlibApi::class) +private fun hashLen16(lo: ULong, hi: ULong): ULong { + val mul: ULong = k2 + 32U + val a: ULong = lo + k2 + val b: ULong = hi + val c: ULong = b.rotateRight(37) * mul + a + val d: ULong = (a.rotateRight(25) + b) * mul + + var e: ULong = (c xor d) * mul + e = e xor (e shr 47) + var f: ULong = (d xor e) * mul + f = f xor (f shr 47) + f *= mul + + return f } /** diff --git a/src/main/java/com/projecturanus/betterp2p/util/CableBusUtil.kt b/src/main/java/com/projecturanus/betterp2p/util/CableBusUtil.kt index 81940ca..2bc171c 100644 --- a/src/main/java/com/projecturanus/betterp2p/util/CableBusUtil.kt +++ b/src/main/java/com/projecturanus/betterp2p/util/CableBusUtil.kt @@ -9,6 +9,7 @@ import appeng.api.parts.SelectedPart import appeng.parts.AEBasePart import appeng.parts.ICableBusContainer import appeng.parts.p2p.PartP2PTunnel +import appeng.parts.p2p.PartP2PTunnelNormal import appeng.tile.networking.TileCableBus import net.minecraft.entity.player.EntityPlayer import net.minecraft.tileentity.TileEntity @@ -54,7 +55,10 @@ fun listTargetGridP2P(grid: IGrid?, player: EntityPlayer, clazz: Class> { if (grid is ISecurityGrid && !grid.hasPermission(player, SecurityPermissions.BUILD)) return emptyList() - val classes = grid?.machinesClasses?.filter { c -> c.superclass == PartP2PTunnel::class.java } ?: emptyList() + val classes = grid?.machinesClasses?.filter { + // Find all P2P tunnels... + c -> c.superclass.superclass == PartP2PTunnel::class.java + } ?: emptyList() val ret: MutableList> = mutableListOf() classes.forEach{ c -> ret.addAll(grid?.getMachines(c)?.map { it.machine as PartP2PTunnel<*> } ?: emptyList()) } return ret diff --git a/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt b/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt index 14db77c..35fef51 100644 --- a/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt +++ b/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt @@ -5,12 +5,15 @@ import appeng.api.networking.IGrid import appeng.api.networking.security.ISecurityGrid import appeng.api.parts.IPart import appeng.api.parts.PartItemStack +import appeng.helpers.IInterfaceHost import appeng.me.GridAccessException import appeng.me.GridNode import appeng.me.cache.P2PCache import appeng.parts.automation.UpgradeInventory import appeng.parts.p2p.PartP2PInterface import appeng.parts.p2p.PartP2PTunnel +import appeng.parts.p2p.PartP2PTunnelNormal +import appeng.parts.p2p.PartP2PTunnelStatic import appeng.tile.inventory.AppEngInternalInventory import appeng.util.Platform import com.projecturanus.betterp2p.BetterP2P @@ -19,6 +22,8 @@ import com.projecturanus.betterp2p.network.P2PInfo import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound +import net.minecraft.util.ChatComponentText +import net.minecraft.util.ChatComponentTranslation import net.minecraftforge.common.util.ForgeDirection fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P2PStatus) : Pair, PartP2PTunnel<*>>? { @@ -57,10 +62,10 @@ fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P } val inputResult: PartP2PTunnel<*> = updateP2P(input, frequency, false, player, input.customName) val outputResult: PartP2PTunnel<*> = updateP2P(output, frequency, true, player, input.customName) - if (input is PartP2PInterface && output is PartP2PInterface) { + if (input is IInterfaceHost && output is IInterfaceHost) { // For input and output, retain upgrades, items, and settings. - inputResult as PartP2PInterface - outputResult as PartP2PInterface + inputResult as IInterfaceHost + outputResult as IInterfaceHost val upgradesIn = input.interfaceDuality.getInventoryByName("upgrades") as UpgradeInventory upgradesIn.forEachIndexed { index, stack -> (inputResult.interfaceDuality.getInventoryByName("upgrades") as UpgradeInventory).setInventorySlotContents(index, stack) @@ -129,15 +134,33 @@ fun changeP2P(tunnel: PartP2PTunnel<*>, newType: TunnelInfo, player: EntityPlaye } } if (BetterP2P.proxy.getP2PFromClass(tunnel.javaClass) == newType) { + player.addChatMessage(ChatComponentText("P2P already this type.")) return null } - if (tunnel is PartP2PInterface) { - // For output, drop items. - val dropItems = mutableListOf() - val patternsOut = tunnel.interfaceDuality.patterns as AppEngInternalInventory - dropItems.addAll(patternsOut) - Platform.spawnDrops(player.worldObj, tunnel.location.x, tunnel.location.y, tunnel.location.z, dropItems) + if (newType.clazz.superclass == PartP2PTunnelStatic::class.java) { + var canConvert = false + for ((i, stack) in player.inventory.mainInventory.withIndex()) { + if (stack?.isItemEqual(newType.stack) == true) { + player.inventory.decrStackSize(i, 1) + canConvert = true + break + } + } + if (!canConvert) { + player.addChatMessage(ChatComponentTranslation("gui.advanced_memory_card.error.missing_items", 1, newType.stack.displayName)) + return null + } } + if (tunnel is PartP2PTunnelStatic<*>) { + val drop = ItemStack.copyItemStack(tunnel.itemStack) + drop.stackSize = 1 + if (!player.inventory.addItemStackToInventory(drop)) { + val drops = mutableListOf(drop) + tunnel.getDrops(drops, false) + Platform.spawnDrops(player.worldObj, player.serverPosX, player.serverPosY, player.serverPosZ, drops) + } + } + val host = tunnel.host host.removePart(tunnel.side, false) val dir = host.addPart(newType.stack, tunnel.side, player) @@ -171,6 +194,21 @@ fun changeAllP2Ps(tunnel: PartP2PTunnel<*>, newType: TunnelInfo, player: EntityP return changeAllP2Ps(tunnel.input, newType, player) } else { val outputs = tunnel.outputs.toMutableList() + if (newType.clazz.superclass == PartP2PTunnelStatic::class.java) { + val amt = outputs.size + 1 + var hasItems = false + for ((i, stack) in player.inventory.mainInventory.withIndex()) { + if (stack?.isItemEqual(newType.stack) == true && stack.stackSize >= amt) { + player.inventory.decrStackSize(i, 1) + hasItems = true + break + } + } + if (!hasItems) { + player.addChatMessage(ChatComponentTranslation("gui.advanced_memory_card.error.missing_items", amt, newType.stack.displayName)) + return false + } + } changeP2P(tunnel, newType, player) for (o in outputs) { changeP2P(o, newType, player) diff --git a/src/main/resources/assets/betterp2p/lang/en_US.lang b/src/main/resources/assets/betterp2p/lang/en_US.lang index aa3b3bd..559c000 100644 --- a/src/main/resources/assets/betterp2p/lang/en_US.lang +++ b/src/main/resources/assets/betterp2p/lang/en_US.lang @@ -44,3 +44,4 @@ gui.advanced_memory_card.p2p_status.output=Output gui.advanced_memory_card.p2p_status.offline=Offline gui.advanced_memory_card.types.filtered=Showing: %s gui.advanced_memory_card.types.any=§aAll +gui.advanced_memory_card.error.missing_items=Cannot change P2P type without %dx %s(s).