From 47dc8d2008dd4e065f3538ee78433817fe53cef7 Mon Sep 17 00:00:00 2001 From: Firenoo <49818773+firenoo@users.noreply.github.com> Date: Thu, 23 Feb 2023 20:49:35 -0800 Subject: [PATCH] Rework the Advanced Memory Card's internal mechanisms. Changes how the advanced memory card internally stores P2P Tunnel information: - Now uses its own custom class. No more sortedInfos/infos discrepency; you can now access the sorted and filtered fields only. The master map cannot be accessed directly. - P2PInfo now uses a hash, which removes AE2 P2P tunnel dupes. It depends on the coordinates, facing, and dimension information. - Corresponding equals() function implemented for P2PInfo. - Send the entire P2P list when binding. A new packet type is likely in order, though. - The rest of the changes is to fit this new data structure into the existing infrastructure. Hopefully this makes the mod more resilient to crashes. --- .../betterp2p/capability/MemoryInfo.kt | 3 +- .../client/gui/GuiAdvancedMemoryCard.kt | 145 +++++------------- .../betterp2p/client/gui/InfoList.kt | 121 +++++++++++++++ .../betterp2p/client/gui/InfoWrapper.kt | 23 ++- .../client/gui/widget/WidgetP2PDevice.kt | 16 +- .../betterp2p/item/ItemAdvancedMemoryCard.kt | 23 +-- .../betterp2p/network/C2SLinkP2P.kt | 10 +- .../betterp2p/network/C2SUpdateInfo.kt | 4 +- .../betterp2p/network/ClientOpenGuiHandler.kt | 2 +- .../network/ClientRefreshInfoHandler.kt | 2 +- .../betterp2p/network/HashHelper.kt | 50 ++++++ .../betterp2p/network/P2PInfo.kt | 19 ++- .../betterp2p/network/S2CRefreshInfo.kt | 4 +- .../betterp2p/network/ServerLinkP2PHandler.kt | 4 +- .../network/ServerRenameP2PTunnel.kt | 4 +- .../betterp2p/util/p2p/P2PStatus.kt | 10 +- .../betterp2p/util/p2p/P2PUtil.kt | 13 +- 17 files changed, 294 insertions(+), 159 deletions(-) create mode 100644 src/main/java/com/projecturanus/betterp2p/client/gui/InfoList.kt create mode 100644 src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt diff --git a/src/main/java/com/projecturanus/betterp2p/capability/MemoryInfo.kt b/src/main/java/com/projecturanus/betterp2p/capability/MemoryInfo.kt index 5354f10..eba4d77 100644 --- a/src/main/java/com/projecturanus/betterp2p/capability/MemoryInfo.kt +++ b/src/main/java/com/projecturanus/betterp2p/capability/MemoryInfo.kt @@ -1,7 +1,8 @@ package com.projecturanus.betterp2p.capability import com.projecturanus.betterp2p.item.BetterMemoryCardModes +import com.projecturanus.betterp2p.network.NONE -data class MemoryInfo(var selectedIndex: Int = -1, +data class MemoryInfo(var selectedEntry: Long = NONE, var frequency: Long = 0, var mode: BetterMemoryCardModes = BetterMemoryCardModes.OUTPUT) diff --git a/src/main/java/com/projecturanus/betterp2p/client/gui/GuiAdvancedMemoryCard.kt b/src/main/java/com/projecturanus/betterp2p/client/gui/GuiAdvancedMemoryCard.kt index d91b42e..f67c348 100644 --- a/src/main/java/com/projecturanus/betterp2p/client/gui/GuiAdvancedMemoryCard.kt +++ b/src/main/java/com/projecturanus/betterp2p/client/gui/GuiAdvancedMemoryCard.kt @@ -33,21 +33,14 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { private val tableX = 9 private val tableY = 19 - private var selectedIndex = -1 - private lateinit var scrollBar: WidgetScrollBar private lateinit var searchBar: MEGuiTextField private lateinit var renameBar: IGuiTextField - private val infos = msg.infos.map(::InfoWrapper).toMutableList() + private var infos = InfoList(msg.infos.map(::InfoWrapper), ::searchText) - private var sortedInfo = infos.toList() - - private var selectedInfo: InfoWrapper? - get() = infos.find { it.index == selectedIndex } - set(value) { - selectedIndex = value?.index ?: -1 - } + private val searchText: String + get() = searchBar.text private val widgetDevices: List // private var infoOnScreen: List @@ -57,25 +50,15 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { private var modeString = getModeString() private val modeButton by lazy { GuiButton(0, guiLeft + 8, guiTop + 190, 256, 20, modeString) } - init { - val tmp = mutableSetOf() - sortedInfo = sortedInfo.filter { tmp.add(it.toString()) } - selectedIndex = mapSelected(msg.memoryInfo.selectedIndex) - sortedInfo.sortedBy { if (it.index == selectedIndex) { - -2 // Put the selected p2p in the front - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency && !it.output) { - -3 // Put input in the beginning - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency) { - -1 // Put same frequency in the front - } else { - it.frequency + Short.MAX_VALUE - } } -// infoOnScreen = sortedInfo.take(5) - selectInfo(selectedIndex) + private val selectedInfo: InfoWrapper? + get() = infos.selectedInfo + init { + infos.select(msg.memoryInfo.selectedEntry) val list = mutableListOf() + // TODO: Expand this selection to >4 for larger screens for (i in 0..3) { - list += WidgetP2PDevice(::selectedInfo, ::mode, { sortedInfo.getOrNull(i + scrollBar.currentScroll) }, 0, 0) + list += WidgetP2PDevice(::selectedInfo, ::mode, { infos.filtered.getOrNull(i + scrollBar.currentScroll) }, 0, 0) } widgetDevices = list.toList() } @@ -100,73 +83,26 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { widgetDevices[i].y = guiTop + tableY + 42 * i } searchBar.text = ClientCache.searchText - reGenInfoFromText() - } - - private fun reGenInfoFromText() { - if (searchBar.text.isEmpty()) { - sortInfo() - } else { - val tmp = mutableSetOf() - val tmpInfo = infos.filter { - it.frequency.toHexString().contains(searchBar.text.uppercase()) || - it.frequency.toHexString().format4().contains(searchBar.text.uppercase()) || - it.name.lowercase().contains(searchBar.text.lowercase()) - } - sortedInfo = tmpInfo.filter { - tmp.add(it.toString()) - }.sortedBy { - if (it.index == selectedIndex) { - -2 // Put the selected p2p in the front - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency && !it.output) { - -3 // Put input in the beginning - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency) { - -1 // Put same frequency in the front - } else { - it.frequency + Short.MAX_VALUE - } - } - } - } - - private fun sortInfo() { - val tmp = mutableSetOf() - sortedInfo = infos.filter { - tmp.add(it.toString()) - } - sortedInfo = sortedInfo.sortedBy { - if (it.index == selectedIndex) { - -2 // Put the selected p2p in the front - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency && !it.output) { - -3 // Put input in the beginning - } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency) { - -1 // Put same frequency in the front - } else { - it.frequency + Short.MAX_VALUE - } - } + infos.refresh() + refreshOverlay() } private fun checkInfo() { - infos.forEach { it.error = false } - infos.groupBy { it.frequency }.filter { it.value.none { x -> !x.output } }.forEach { it.value.forEach { info -> + infos.filtered.forEach { it.error = false } + // A P2P entry is considered "errored" if it is an output, and has no inputs. + infos.filtered.groupBy { it.frequency }.filter { it.value.none { x -> !x.output } }.forEach { it.value.forEach { info -> info.error = true } } } - fun refreshInfo(infos: List,reGenInfo:Boolean=false) { - infos.forEach { this.infos[it.index] = InfoWrapper(it) } + fun refreshInfo(infos: List) { + this.infos.rebuild(infos.map(::InfoWrapper)) checkInfo() - if(reGenInfo) { - reGenInfoFromText() - } else { - sortInfo() - } refreshOverlay() } private fun syncMemoryInfo() { - ModNetwork.channel.sendToServer(C2SUpdateInfo(MemoryInfo(selectedIndex, selectedInfo?.frequency ?: 0, mode))) + ModNetwork.channel.sendToServer(C2SUpdateInfo(MemoryInfo(infos.selectedEntry, selectedInfo?.frequency ?: 0, mode))) } private fun drawInformation() { @@ -219,22 +155,15 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { return I18n.format("gui.advanced_memory_card.mode.${mode.name.lowercase(Locale.getDefault())}") } - private fun findInput(frequency: Long) = - infos.find { it.frequency == frequency && !it.output } + private fun findInput(frequency: Long?) = + infos.filtered.find { it.frequency == frequency && !it.output } - /* - * Maps the index to one that exists in the filtered/sorted list. + /** + * Selects the info with the hashCode, if it exists. Otherwise, + * deselect the entry. */ - private fun mapSelected(index: Int) : Int { - return if (index >= 0) { - sortedInfo.find { - it.toString() == infos[index].toString() - }?.index ?: -1 - } else -1 - } - - private fun selectInfo(index: Int) { - selectedIndex = mapSelected(index) + private fun selectInfo(hash: Long) { + infos.select(hash) syncMemoryInfo() refreshOverlay() } @@ -249,11 +178,11 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { ClientCache.selectedFacing = selectedInfo?.facing } ClientCache.positions.clear() - ClientCache.positions.addAll(sortedInfo.filter { it.frequency == selectedInfo?.frequency && it != selectedInfo }.map { arrayListOf(it.posX, it.posY, it.posZ) to it.facing }) + ClientCache.positions.addAll(infos.sorted.filter { it.frequency == selectedInfo?.frequency && it != selectedInfo }.map { arrayListOf(it.posX, it.posY, it.posZ) to it.facing }) } private fun onSelectButtonClicked(info: InfoWrapper) { - selectInfo(info.index) + selectInfo(info.code) } private fun onRenameButtonClicked(info:InfoWrapper,index: Int){ if(isShiftKeyDown()) { @@ -276,7 +205,7 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { if(renameBar.info != null && renameBar.info.name != renameBar.text){ val info:InfoWrapper = renameBar.info renameBar.text = renameBar.text.trim() - ModNetwork.channel.sendToServer(C2SP2PTunnelInfo(P2PTunnelInfo(info.posX,info.posY,info.posZ,info.world, ForgeDirection.valueOf(info.facing.name).ordinal,renameBar.text))) + ModNetwork.channel.sendToServer(C2SP2PTunnelInfo(P2PTunnelInfo(info.posX,info.posY,info.posZ,info.dim, ForgeDirection.valueOf(info.facing.name).ordinal,renameBar.text))) } renameBar.isVisible = false renameBar.text = "" @@ -285,27 +214,27 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { } private fun onBindButtonClicked(info: InfoWrapper) { - if (selectedIndex == -1) return + if (infos.selectedEntry == NONE) return when (mode) { BetterMemoryCardModes.INPUT -> { - BetterP2P.logger.debug("Bind ${info.index} as input") - ModNetwork.channel.sendToServer(C2SLinkP2P(info.index, selectedIndex)) + BetterP2P.logger.debug("Bind ${info.code} as input") + ModNetwork.channel.sendToServer(C2SLinkP2P(info.code, infos.selectedEntry)) } BetterMemoryCardModes.OUTPUT -> { - BetterP2P.logger.debug("Bind ${info.index} as output") - ModNetwork.channel.sendToServer(C2SLinkP2P(selectedIndex, info.index)) + BetterP2P.logger.debug("Bind ${info.code} as output") + ModNetwork.channel.sendToServer(C2SLinkP2P(infos.selectedEntry, info.code)) } BetterMemoryCardModes.COPY -> { - val input = selectedInfo?.frequency?.let { findInput(it) } + val input = findInput(selectedInfo?.frequency) if (input != null) - ModNetwork.channel.sendToServer(C2SLinkP2P(input.index, info.index)) + ModNetwork.channel.sendToServer(C2SLinkP2P(input.code, info.code)) } } } private fun transportPlayer(info: InfoWrapper){ Minecraft.getMinecraft().thePlayer.closeScreen() - ModNetwork.channel.sendToServer(C2STransportPlayer(P2PTunnelInfo(info.posX,info.posY,info.posZ,info.world,0))) + ModNetwork.channel.sendToServer(C2STransportPlayer(P2PTunnelInfo(info.posX,info.posY,info.posZ,info.dim,0))) } @@ -336,7 +265,7 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { renameBar.mouseClicked(mouseX,mouseY,mouseButton) if (mouseButton == 1 && searchBar.isMouseIn(mouseX, mouseY)) { this.searchBar.text = "" - reGenInfoFromText() + infos.refilter() } super.mouseClicked(mouseX, mouseY, mouseButton) } @@ -393,7 +322,7 @@ class GuiAdvancedMemoryCard(msg: S2CListP2P) : GuiScreen(), TextureBound { } }else if (searchBar.isFocused && !(char == ' ' && searchBar.text.isEmpty())){ searchBar.textboxKeyTyped(char, key) - reGenInfoFromText() + infos.refilter() } return super.keyTyped(char, key) } diff --git a/src/main/java/com/projecturanus/betterp2p/client/gui/InfoList.kt b/src/main/java/com/projecturanus/betterp2p/client/gui/InfoList.kt new file mode 100644 index 0000000..2f60e06 --- /dev/null +++ b/src/main/java/com/projecturanus/betterp2p/client/gui/InfoList.kt @@ -0,0 +1,121 @@ +package com.projecturanus.betterp2p.client.gui + +import com.projecturanus.betterp2p.network.NONE +import com.projecturanus.betterp2p.network.hashP2P +import kotlin.reflect.KProperty0 + +/** + * InfoList + * Dedicated list to hold "InfoWrappers". Internally, stores + * them in a HashMap. This is an opaque type, and access to + * it is restricted. External access is instead directed to + * a sorted view and a filtered view of the internal map. + */ +class InfoList (initList: Collection, + private val search: KProperty0) { + + /** + * The master map, acts as the source of truth for all items + * in this list. + */ + private val masterMap: HashMap = hashMapOf() + + /** + * Sorted view of the master map. This is resorted whenever + * the map is updated. + */ + val sorted: MutableList = mutableListOf() + + /** + * Filtered view of the sorted view (not the master map) + */ + var filtered: List = listOf() + + /** + * Binding to the search string in the text box + */ + private val searchStr: String + get() = search.get() + + val selectedInfo: InfoWrapper? + get() = masterMap[selectedEntry] + + var selectedEntry: Long = NONE + + val size: Int + get() = masterMap.size + + init { + initList.forEach { masterMap[it.code] = it } + } + + fun resort() { + sorted.sortBy { + if (it.code == selectedEntry) { + -2 // Put the selected p2p in the front + // Non-Zero frequencies + } else if (it.frequency != 0L && it.frequency == selectedInfo?.frequency && !it.output) { + -3 // Put input in the beginning + } else if (it.frequency != 0.toLong() && it.frequency == selectedInfo?.frequency) { + -1 // Put same frequency in the front + } else { + // Frequencies from highest to lowest + it.frequency + Short.MAX_VALUE + } + } + } + + /** + * Updates the filtered list. + */ + fun refilter() { + filtered = sorted.filter { + it.frequency.toHexString().contains(searchStr.uppercase()) || + it.frequency.toHexString().format4().contains(searchStr.uppercase()) || + it.name.lowercase().contains(searchStr.lowercase()) || + it.code == selectedEntry + } + } + + /** + * Updates the sorted list and applies the filter again. + */ + fun refresh() { + sorted.addAll(masterMap.values) + resort() + refilter() + } + + /** + * Completely refresh the master list. + */ + fun rebuild(updateList: Collection) { + masterMap.clear() + updateList.forEach { masterMap[it.code] = it } + sorted.clear() + sorted.addAll(masterMap.values) + resort() + // TODO: Extend the filtering mechanism. + refilter() + } + + /** + * Update the master list, and send the changes downstream to sorted/filtered + */ + fun update(updateList: Collection) { + updateList.forEach { masterMap[it.code] = it } + sorted.clear() + sorted.addAll(masterMap.values) + resort() + // TODO: Extend the filtering mechanism. + refilter() + } + + fun select(hashCode: Long) { + if (masterMap.containsKey(hashCode)) { + selectedEntry = hashCode + } else { + selectedEntry = NONE + } + } +} diff --git a/src/main/java/com/projecturanus/betterp2p/client/gui/InfoWrapper.kt b/src/main/java/com/projecturanus/betterp2p/client/gui/InfoWrapper.kt index 82d03ef..0c4b3ba 100644 --- a/src/main/java/com/projecturanus/betterp2p/client/gui/InfoWrapper.kt +++ b/src/main/java/com/projecturanus/betterp2p/client/gui/InfoWrapper.kt @@ -1,6 +1,7 @@ package com.projecturanus.betterp2p.client.gui import com.projecturanus.betterp2p.network.P2PInfo +import com.projecturanus.betterp2p.network.hashP2P import net.minecraft.client.gui.GuiButton import net.minecraft.client.resources.I18n import net.minecraftforge.common.util.ForgeDirection @@ -8,13 +9,15 @@ import java.util.* class InfoWrapper(info: P2PInfo) { // Basic information - val index: Int = info.index + val code: Long by lazy { + hashP2P(posX, posY, posZ, facing.ordinal, dim) + } val frequency: Long = info.frequency val hasChannel = info.hasChannel val posX: Int = info.posX val posY: Int = info.posY val posZ: Int = info.posZ - val world: Int = info.world + val dim: Int = info.world val facing: ForgeDirection = info.facing val description: String val output: Boolean = info.output @@ -40,8 +43,20 @@ class InfoWrapper(info: P2PInfo) { } } - override fun toString() : String { - return "${posX}_${posY}_${posZ}_${world}_${facing}" + override fun hashCode(): Int { + return code.hashCode() + } + + override fun equals(other: Any?): Boolean { + return if (other is InfoWrapper) { + this.posX == other.posX && + this.posY == other.posY && + this.posZ == other.posZ && + this.dim == other.dim && + this.facing == other.facing + } else { + false + } } } diff --git a/src/main/java/com/projecturanus/betterp2p/client/gui/widget/WidgetP2PDevice.kt b/src/main/java/com/projecturanus/betterp2p/client/gui/widget/WidgetP2PDevice.kt index 117afb6..f74b3e0 100644 --- a/src/main/java/com/projecturanus/betterp2p/client/gui/widget/WidgetP2PDevice.kt +++ b/src/main/java/com/projecturanus/betterp2p/client/gui/widget/WidgetP2PDevice.kt @@ -10,9 +10,9 @@ import net.minecraft.client.resources.I18n import net.minecraftforge.common.DimensionManager import net.minecraftforge.common.util.ForgeDirection import java.awt.Color -import kotlin.reflect.KMutableProperty0 +import kotlin.reflect.KProperty0 -class WidgetP2PDevice(private val selectedInfoProperty: KMutableProperty0, val modeSupplier: () -> BetterMemoryCardModes, val infoSupplier: () -> InfoWrapper?, var x: Int, var y: Int): Widget() { +class WidgetP2PDevice(private val selectedInfoProperty: KProperty0, val modeSupplier: () -> BetterMemoryCardModes, val infoSupplier: () -> InfoWrapper?, var x: Int, var y: Int): Widget() { private val outputColor = 0x4566ccff private val selectedColor = 0x4545DA75 private val errorColor = 0x45DA4527 @@ -22,17 +22,15 @@ class WidgetP2PDevice(private val selectedInfoProperty: KMutableProperty0 p2p.getInfo(index) }, info), + S2CListP2P(status.listP2P.values.map { p2p -> p2p.toInfo() }, info), player ) } @@ -71,17 +74,18 @@ object ItemAdvancedMemoryCard : Item() { val stack = player.heldItem val info = getInfo(stack) if (part is PartP2PTunnel<*>) { - val status = P2PStatus(player, 0, part.gridNode.grid, part) - info.selectedIndex = status.listP2P.indexOfFirst { it == status.targetP2P } + val status = P2PStatus(player, part.gridNode.grid, part) + val p2p = status.listP2P.values.first { it == status.targetP2P } + info.selectedEntry = hashP2P(p2p) writeInfo(stack, info) sendStatus(status, info, player as EntityPlayerMP) return true } else { val node = te.getGridNode(ForgeDirection.getOrientation(side))!! - info.selectedIndex = -1 + info.selectedEntry = NONE writeInfo(stack, info) - sendStatus(P2PStatus(player, 0, node.grid), info, player as EntityPlayerMP) + sendStatus(P2PStatus(player, node.grid), info, player as EntityPlayerMP) return true } } @@ -103,9 +107,8 @@ object ItemAdvancedMemoryCard : Item() { if (stack.tagCompound == null) stack.tagCompound = NBTTagCompound() val compound = stack.tagCompound!! - if (!compound.hasKey("selectedIndex")) compound.setInteger("selectedIndex", -1) - - return MemoryInfo(compound.getInteger("selectedIndex"), compound.getLong("frequency"), BetterMemoryCardModes.values()[compound.getInteger("mode")]) + if (!compound.hasKey("selectedIndex", Constants.NBT.TAG_LONG)) compound.setLong("selectedIndex", NONE) + return MemoryInfo(compound.getLong("selectedIndex"), compound.getLong("frequency"), BetterMemoryCardModes.values()[compound.getInteger("mode")]) } fun writeInfo(stack: ItemStack, info: MemoryInfo) { @@ -113,7 +116,7 @@ object ItemAdvancedMemoryCard : Item() { if (stack.tagCompound == null) stack.tagCompound = NBTTagCompound() val compound = stack.tagCompound!! - compound.setInteger("selectedIndex", info.selectedIndex) + compound.setLong("selectedIndex", info.selectedEntry) compound.setLong("frequency", info.frequency) compound.setInteger("mode", info.mode.ordinal) } diff --git a/src/main/java/com/projecturanus/betterp2p/network/C2SLinkP2P.kt b/src/main/java/com/projecturanus/betterp2p/network/C2SLinkP2P.kt index 7304bec..0b72d03 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/C2SLinkP2P.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/C2SLinkP2P.kt @@ -3,14 +3,14 @@ package com.projecturanus.betterp2p.network import cpw.mods.fml.common.network.simpleimpl.IMessage import io.netty.buffer.ByteBuf -class C2SLinkP2P(var input: Int = -1, var output: Int = -1): IMessage { +class C2SLinkP2P(var input: Long = NONE, var output: Long = NONE): IMessage { override fun fromBytes(buf: ByteBuf) { - input = buf.readInt() - output = buf.readInt() + input = buf.readLong() + output = buf.readLong() } override fun toBytes(buf: ByteBuf) { - buf.writeInt(input) - buf.writeInt(output) + buf.writeLong(input) + buf.writeLong(output) } } diff --git a/src/main/java/com/projecturanus/betterp2p/network/C2SUpdateInfo.kt b/src/main/java/com/projecturanus/betterp2p/network/C2SUpdateInfo.kt index 1cbd742..11a04fd 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/C2SUpdateInfo.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/C2SUpdateInfo.kt @@ -6,13 +6,13 @@ import cpw.mods.fml.common.network.simpleimpl.IMessage import io.netty.buffer.ByteBuf fun writeMemoryInfo(buf: ByteBuf, info: MemoryInfo) { - buf.writeInt(info.selectedIndex) + buf.writeLong(info.selectedEntry) buf.writeLong(info.frequency) buf.writeInt(info.mode.ordinal) } fun readMemoryInfo(buf: ByteBuf): MemoryInfo { - return MemoryInfo(buf.readInt(), buf.readLong(), BetterMemoryCardModes.values()[buf.readInt()]) + return MemoryInfo(buf.readLong(), buf.readLong(), BetterMemoryCardModes.values()[buf.readInt()]) } class C2SUpdateInfo(var info: MemoryInfo = MemoryInfo()) : IMessage { diff --git a/src/main/java/com/projecturanus/betterp2p/network/ClientOpenGuiHandler.kt b/src/main/java/com/projecturanus/betterp2p/network/ClientOpenGuiHandler.kt index d5a7e01..c2de49e 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/ClientOpenGuiHandler.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/ClientOpenGuiHandler.kt @@ -13,7 +13,7 @@ class ClientOpenGuiHandler : IMessageHandler { override fun onMessage(message: S2CListP2P, ctx: MessageContext): IMessage? { val gui = Minecraft.getMinecraft().currentScreen if(gui is GuiAdvancedMemoryCard){ - gui.refreshInfo(message.infos,true) + gui.refreshInfo(message.infos) }else { Minecraft.getMinecraft().displayGuiScreen(GuiAdvancedMemoryCard(message)) } diff --git a/src/main/java/com/projecturanus/betterp2p/network/ClientRefreshInfoHandler.kt b/src/main/java/com/projecturanus/betterp2p/network/ClientRefreshInfoHandler.kt index c08dde7..3ea8548 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/ClientRefreshInfoHandler.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/ClientRefreshInfoHandler.kt @@ -13,7 +13,7 @@ class ClientRefreshInfoHandler : IMessageHandler { override fun onMessage(message: S2CRefreshInfo, ctx: MessageContext): IMessage? { val gui = Minecraft.getMinecraft().currentScreen if (gui is GuiAdvancedMemoryCard) { - gui.refreshInfo(message.infos, true) + gui.refreshInfo(message.infos) } return null } diff --git a/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt b/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt new file mode 100644 index 0000000..24f1ff2 --- /dev/null +++ b/src/main/java/com/projecturanus/betterp2p/network/HashHelper.kt @@ -0,0 +1,50 @@ +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 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 +} + +fun hashP2P(p: PartP2PTunnel<*>): Long + = hashP2P(p.location.x, p.location.y, p.location.z, p.side.ordinal, p.location.dimension) + +/** + * Collapse an 32-bit integer into a 16-bit integer through + * the XOR operator. + */ +private fun xorCollapse16(input: Int): Int { + var ret = input and 0xFFFF + ret = ret xor ((input ushr 16) and 0xFFFF) + return ret +} + +/** + * Collapse an 32-bit integer into a 12-bit integer through + * the XOR operator. + */ +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 +} + +/** + * Using `0x80000000` to represent none is selected (aka MSB set) + */ +const val NONE: Long = Long.MIN_VALUE diff --git a/src/main/java/com/projecturanus/betterp2p/network/P2PInfo.kt b/src/main/java/com/projecturanus/betterp2p/network/P2PInfo.kt index d8c0d4d..1eab5ac 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/P2PInfo.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/P2PInfo.kt @@ -1,9 +1,9 @@ package com.projecturanus.betterp2p.network +import com.projecturanus.betterp2p.client.gui.InfoWrapper import net.minecraftforge.common.util.ForgeDirection -class P2PInfo(val index: Int, - val frequency: Long, +class P2PInfo(val frequency: Long, val posX: Int, val posY: Int, val posZ: Int, @@ -11,4 +11,17 @@ class P2PInfo(val index: Int, val facing: ForgeDirection, val name: String, val output: Boolean, - val hasChannel: Boolean) + val hasChannel: Boolean) { + + override fun equals(other: Any?): Boolean { + return if (other is InfoWrapper) { + this.posX == other.posX && + this.posY == other.posY && + this.posZ == other.posZ && + this.facing == other.facing + } else { + false + } + } + +} diff --git a/src/main/java/com/projecturanus/betterp2p/network/S2CRefreshInfo.kt b/src/main/java/com/projecturanus/betterp2p/network/S2CRefreshInfo.kt index f250442..ba2a661 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/S2CRefreshInfo.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/S2CRefreshInfo.kt @@ -5,7 +5,6 @@ import io.netty.buffer.ByteBuf import net.minecraftforge.common.util.ForgeDirection fun readInfo(buf: ByteBuf): P2PInfo { - val index = buf.readInt() val freq = buf.readLong() val posX = buf.readInt() val posY = buf.readInt() @@ -17,11 +16,10 @@ fun readInfo(buf: ByteBuf): P2PInfo { for (i in 0..nameLength) { name += buf.readChar() } - return P2PInfo(index, freq, posX, posY, posZ,world, facing, name, buf.readBoolean(), buf.readBoolean()) + return P2PInfo(freq, posX, posY, posZ,world, facing, name, buf.readBoolean(), buf.readBoolean()) } fun writeInfo(buf: ByteBuf, info: P2PInfo) { - buf.writeInt(info.index) buf.writeLong(info.frequency) buf.writeInt(info.posX) buf.writeInt(info.posY) diff --git a/src/main/java/com/projecturanus/betterp2p/network/ServerLinkP2PHandler.kt b/src/main/java/com/projecturanus/betterp2p/network/ServerLinkP2PHandler.kt index 69adf12..00f6724 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/ServerLinkP2PHandler.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/ServerLinkP2PHandler.kt @@ -1,7 +1,7 @@ package com.projecturanus.betterp2p.network import com.projecturanus.betterp2p.util.p2p.P2PCache -import com.projecturanus.betterp2p.util.p2p.getInfo +import com.projecturanus.betterp2p.util.p2p.toInfo import com.projecturanus.betterp2p.util.p2p.linkP2P import cpw.mods.fml.common.network.simpleimpl.IMessage import cpw.mods.fml.common.network.simpleimpl.IMessageHandler @@ -16,7 +16,7 @@ class ServerLinkP2PHandler : IMessageHandler { if (result != null) { status.listP2P[message.input] = result.first status.listP2P[message.output] = result.second - ModNetwork.channel.sendTo(S2CRefreshInfo(listOf(result.first.getInfo(message.input), result.second.getInfo(message.output))), ctx.serverHandler.playerEntity) + ModNetwork.channel.sendTo(S2CRefreshInfo(status.listP2P.values.map { it.toInfo() }), ctx.serverHandler.playerEntity) } return null } diff --git a/src/main/java/com/projecturanus/betterp2p/network/ServerRenameP2PTunnel.kt b/src/main/java/com/projecturanus/betterp2p/network/ServerRenameP2PTunnel.kt index e1af6b7..669ec18 100644 --- a/src/main/java/com/projecturanus/betterp2p/network/ServerRenameP2PTunnel.kt +++ b/src/main/java/com/projecturanus/betterp2p/network/ServerRenameP2PTunnel.kt @@ -4,7 +4,7 @@ import appeng.api.parts.IPartHost import appeng.parts.p2p.PartP2PTunnel import com.projecturanus.betterp2p.item.ItemAdvancedMemoryCard import com.projecturanus.betterp2p.util.p2p.P2PStatus -import com.projecturanus.betterp2p.util.p2p.getInfo +import com.projecturanus.betterp2p.util.p2p.toInfo import cpw.mods.fml.common.network.simpleimpl.IMessage import cpw.mods.fml.common.network.simpleimpl.IMessageHandler import cpw.mods.fml.common.network.simpleimpl.MessageContext @@ -22,7 +22,7 @@ class ServerRenameP2PTunnel : IMessageHandler { val p = (te as IPartHost).getPart(ForgeDirection.getOrientation(message.info.side)) as PartP2PTunnel<*> p.customName = message.info.name ModNetwork.channel.sendTo(S2CListP2P( - P2PStatus(player, 0, p.gridNode.grid,p).listP2P.mapIndexed { index, p2p -> p2p.getInfo(index) }, + P2PStatus(player, p.gridNode.grid,p).listP2P.values.map { it.toInfo() }, ItemAdvancedMemoryCard.getInfo(player.heldItem) ),player) } diff --git a/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PStatus.kt b/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PStatus.kt index c7a15c9..eaaee93 100644 --- a/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PStatus.kt +++ b/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PStatus.kt @@ -3,9 +3,15 @@ package com.projecturanus.betterp2p.util.p2p import appeng.api.networking.IGrid import appeng.parts.p2p.PartP2PTunnel import appeng.parts.p2p.PartP2PTunnelME +import com.projecturanus.betterp2p.network.hashP2P import com.projecturanus.betterp2p.util.listTargetGridP2P import net.minecraft.entity.player.EntityPlayer -class P2PStatus(player: EntityPlayer, val id: Int, val grid: IGrid, val targetP2P: PartP2PTunnel<*>? = null) { - val listP2P: MutableList> = listTargetGridP2P(grid, player, targetP2P?.javaClass ?: PartP2PTunnelME::class.java).toMutableList() +class P2PStatus(player: EntityPlayer, grid: IGrid, val targetP2P: PartP2PTunnel<*>? = null) { + val listP2P: MutableMap> = mutableMapOf() + + init { + listTargetGridP2P(grid, player, targetP2P?.javaClass ?: PartP2PTunnelME::class.java) + .forEach { listP2P[hashP2P(it)] = it } + } } 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 38c2ecc..e197768 100644 --- a/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt +++ b/src/main/java/com/projecturanus/betterp2p/util/p2p/P2PUtil.kt @@ -13,9 +13,10 @@ import net.minecraft.item.ItemStack import net.minecraft.nbt.NBTTagCompound import net.minecraftforge.common.util.ForgeDirection -fun linkP2P(player: EntityPlayer, inputIndex: Int, outputIndex: Int, status: P2PStatus) : Pair, PartP2PTunnel<*>>? { - val input = status.listP2P[inputIndex] - val output = status.listP2P[outputIndex] +fun linkP2P(player: EntityPlayer, inputIndex: Long, outputIndex: Long, status: P2PStatus) : Pair, PartP2PTunnel<*>>? { + // If these calls mess up we have bigger problems... + val input = status.listP2P[inputIndex]!! + val output = status.listP2P[outputIndex]!! val grid: IGrid? = input.gridNode?.grid if (grid is ISecurityGrid) { @@ -59,7 +60,7 @@ fun updateP2P(tunnel: PartP2PTunnel<*>, frequency: Long, output: Boolean, player val data = NBTTagCompound() val p2pItem: ItemStack = tunnel.getItemStack(PartItemStack.Wrench) - p2pItem.unlocalizedName +// p2pItem.unlocalizedName tunnel.outputProperty = output tunnel.customName = name @@ -96,5 +97,5 @@ var PartP2PTunnel<*>.outputProperty val PartP2PTunnel<*>.hasChannel get() = isPowered && isActive -fun PartP2PTunnel<*>.getInfo(index: Int) - = P2PInfo(index, frequency, location.x, location.y, location.z, location.dimension, side, customName, isOutput, hasChannel) +fun PartP2PTunnel<*>.toInfo() + = P2PInfo(frequency, location.x, location.y, location.z, location.dimension, side, customName, isOutput, hasChannel)