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
This commit is contained in:
firenoo authored and GitHub committed 2023-07-17 10:52:04 -07:00
1 parent d147681c26
commit de3a08f02a
8 files changed
+216 -69

No files matched your search

@@ -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
@@ -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<out PartP2PTunnel<*>>) {
private fun registerTunnel(def: IItemDefinition, type: Int, classType: Class<out PartP2PTunnel<*>>) {
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
}
}
@@ -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
}
/**
@@ -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<out PartP
fun listAllGridP2P(grid: IGrid?, player: EntityPlayer): List<PartP2PTunnel<*>> {
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<PartP2PTunnel<*>> = mutableListOf()
classes.forEach{ c -> ret.addAll(grid?.getMachines(c)?.map { it.machine as PartP2PTunnel<*> } ?: emptyList()) }
return ret
@@ -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<*>, 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<ItemStack>()
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<ItemStack>(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)