aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils
diff options
context:
space:
mode:
authorThunderblade73 <85900443+Thunderblade73@users.noreply.github.com>2024-02-10 00:24:52 +0100
committerGitHub <noreply@github.com>2024-02-10 00:24:52 +0100
commit4559e5ff05e19817a21ae49f1c0d8a97d273f6a1 (patch)
treee72dac91d07fc84bea80548c89e13276caa68b81 /src/main/java/at/hannibal2/skyhanni/utils
parentd3a7cc4ab970b457b7950489da781539e45e0dce (diff)
downloadskyhanni-4559e5ff05e19817a21ae49f1c0d8a97d273f6a1.tar.gz
skyhanni-4559e5ff05e19817a21ae49f1c0d8a97d273f6a1.tar.bz2
skyhanni-4559e5ff05e19817a21ae49f1c0d8a97d273f6a1.zip
Splitting many utils functions from LorenzUtils up into other classes: ChatUtils, CollectionUtils, ConditionalUtils. And code cleanup #978
Diffstat (limited to 'src/main/java/at/hannibal2/skyhanni/utils')
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt27
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ChatUtils.kt203
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/CollectionUtils.kt115
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ColorUtils.kt7
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/CombatUtils.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ConditionalUtils.kt33
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ConfigUtils.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/EntityOutlineRenderer.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/EntityUtils.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/GuiRenderUtils.kt8
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/IdentityCharacteristics.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/InventoryUtils.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ItemBlink.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ItemStackTypeAdapter.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ItemUtils.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/KSerializable.kt6
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/KeyboardManager.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzColor.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzDebug.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzLogger.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt435
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzVec.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/MinecraftConsoleFilter.kt5
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/MinecraftDispatcher.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/MultiFilter.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/NBTTypeAdapter.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/NEUInternalName.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt7
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/OSUtils.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ParkourHelper.kt6
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/RecalculatingValue.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/ReflectionUtils.kt62
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/RenderUtils.kt28
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/Season.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/SimpleTimeMark.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/SkyBlockItemModifierUtils.kt9
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/StringUtils.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/TabListData.kt20
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/TimeMark.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/TimeUtils.kt9
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/Timer.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/UtilsPatterns.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/renderables/RenderLineTooltips.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/renderables/Renderable.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPattern.kt3
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGroup.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGui.kt6
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternImpl.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternManager.kt4
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderHelper.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderManager.kt2
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/shader/Uniform.kt5
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/tracker/ItemTrackerData.kt1
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniItemTracker.kt15
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniTracker.kt10
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/tracker/TrackerData.kt1
60 files changed, 605 insertions, 513 deletions
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt
index 2fd634d26..0f561fdff 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/APIUtil.kt
@@ -22,8 +22,8 @@ import java.io.FileInputStream
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
-
object APIUtil {
+
private val parser = JsonParser()
private var showApiErrors = false
@@ -49,7 +49,7 @@ object APIUtil {
fun getJSONResponseAsElement(
urlString: String,
silentError: Boolean = false,
- apiName: String = "Hypixel API"
+ apiName: String = "Hypixel API",
): JsonElement {
val client = builder.build()
try {
@@ -63,16 +63,15 @@ object APIUtil {
if (e.message?.contains("Use JsonReader.setLenient(true)") == true) {
println("MalformedJsonException: Use JsonReader.setLenient(true)")
println(" - getJSONResponse: '$urlString'")
- LorenzUtils.debug("MalformedJsonException: Use JsonReader.setLenient(true)")
+ ChatUtils.debug("MalformedJsonException: Use JsonReader.setLenient(true)")
} else if (retSrc.contains("<center><h1>502 Bad Gateway</h1></center>")) {
if (showApiErrors && apiName == "Hypixel API") {
- LorenzUtils.clickableChat(
+ ChatUtils.clickableChat(
"Problems with detecting the Hypixel API. §eClick here to hide this message for now.",
"shtogglehypixelapierrors"
)
}
e.printStackTrace()
-
} else {
ErrorManager.logErrorWithData(
e, "$apiName error for url: '$urlString'",
@@ -118,7 +117,7 @@ object APIUtil {
val message = "POST request to '$urlString' returned status ${status.statusCode}"
println(message)
- LorenzUtils.error("SkyHanni ran into an error. Status: ${status.statusCode}")
+ ChatUtils.error("SkyHanni ran into an error. Status: ${status.statusCode}")
return ApiResponse(false, message, JsonObject())
}
} catch (throwable: Throwable) {
@@ -126,7 +125,7 @@ object APIUtil {
throw throwable
} else {
throwable.printStackTrace()
- LorenzUtils.error("SkyHanni ran into an ${throwable::class.simpleName ?: "error"} whilst sending a resource. See logs for more details.")
+ ChatUtils.error("SkyHanni ran into an ${throwable::class.simpleName ?: "error"} whilst sending a resource. See logs for more details.")
}
return ApiResponse(false, throwable.message, JsonObject())
} finally {
@@ -139,15 +138,21 @@ object APIUtil {
return parser.parse(retSrc) as JsonObject
}
- fun postJSONIsSuccessful(urlString: String, body: String, silentError: Boolean = false): Boolean {
- val response = postJSON(urlString, body, silentError)
+ fun postJSONIsSuccessful(url: String, body: String, silentError: Boolean = false): Boolean {
+ val response = postJSON(url, body, silentError)
if (response.success) {
return true
}
println(response.message)
- LorenzUtils.error(response.message ?: "An error occurred during the API request")
+ ErrorManager.logErrorStateWithData(
+ "An error occurred during the API request",
+ "unsuccessful API response",
+ "url" to url,
+ "body" to body,
+ "response" to response,
+ )
return false
}
@@ -158,6 +163,6 @@ object APIUtil {
fun toggleApiErrorMessages() {
showApiErrors = !showApiErrors
- LorenzUtils.chat("Hypixel API error messages " + if (showApiErrors) "§chidden" else "§ashown")
+ ChatUtils.chat("Hypixel API error messages " + if (showApiErrors) "§chidden" else "§ashown")
}
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ChatUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ChatUtils.kt
new file mode 100644
index 000000000..34f42e629
--- /dev/null
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ChatUtils.kt
@@ -0,0 +1,203 @@
+package at.hannibal2.skyhanni.utils
+
+import at.hannibal2.skyhanni.SkyHanniMod
+import at.hannibal2.skyhanni.events.LorenzTickEvent
+import at.hannibal2.skyhanni.utils.StringUtils.removeColor
+import net.minecraft.client.Minecraft
+import net.minecraft.event.ClickEvent
+import net.minecraft.event.HoverEvent
+import net.minecraft.util.ChatComponentText
+import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
+import java.util.LinkedList
+import java.util.Queue
+import kotlin.time.Duration.Companion.milliseconds
+
+object ChatUtils {
+
+ // TODO log based on chat category (error, warning, debug, user error, normal)
+ private val log = LorenzLogger("chat/mod_sent")
+ var lastButtonClicked = 0L
+
+ private const val DEBUG_PREFIX = "[SkyHanni Debug] §7"
+ private const val USER_ERROR_PREFIX = "§c[SkyHanni] "
+ private val ERROR_PREFIX by lazy { "§c[SkyHanni-${SkyHanniMod.version}] " }
+ private const val CHAT_PREFIX = "[SkyHanni] "
+
+ /**
+ * Sends a debug message to the chat and the console.
+ * This is only sent if the debug feature is enabled.
+ *
+ * @param message The message to be sent
+ *
+ * @see DEBUG_PREFIX
+ */
+ fun debug(message: String) {
+ if (SkyHanniMod.feature.dev.debug.enabled && internalChat(DEBUG_PREFIX + message)) {
+ LorenzUtils.consoleLog("[Debug] $message")
+ }
+ }
+
+ /**
+ * Sends a message to the user that they did something incorrectly.
+ * We should tell them what to do instead as well.
+ *
+ * @param message The message to be sent
+ *
+ * @see USER_ERROR_PREFIX
+ */
+ fun userError(message: String) {
+ internalChat(USER_ERROR_PREFIX + message)
+ }
+
+ /**
+ * Sends a message to the user that an error occurred caused by something in the code.
+ * This should be used for errors that are not caused by the user.
+ *
+ * Why deprecate this? Even if this message is descriptive for the user and the developer,
+ * we don't want inconsitencies in errors, and we would need to search
+ * for the code line where this error gets printed any way.
+ * so it's better to use the stack trace still.
+ *
+ * @param message The message to be sent
+ * @param prefix Whether to prefix the message with the error prefix, default true
+ *
+ * @see ERROR_PREFIX
+ */
+ @Deprecated(
+ "Do not send the user a non clickable non stacktrace containing error message.",
+ ReplaceWith("ErrorManager.logErrorStateWithData")
+ )
+ fun error(message: String) {
+ println("error: '$message'")
+ internalChat(ERROR_PREFIX + message)
+ }
+
+ /**
+ * Sends a message to the user
+ * @param message The message to be sent
+ * @param prefix Whether to prefix the message with the chat prefix, default true
+ * @param prefixColor Color that the prefix should be, default yellow (§e)
+ *
+ * @see CHAT_PREFIX
+ */
+ fun chat(message: String, prefix: Boolean = true, prefixColor: String = "§e") {
+ if (prefix) {
+ internalChat(prefixColor + CHAT_PREFIX + message)
+ } else {
+ internalChat(message)
+ }
+ }
+
+ private fun internalChat(message: String): Boolean {
+ log.log(message)
+ val minecraft = Minecraft.getMinecraft()
+ if (minecraft == null) {
+ LorenzUtils.consoleLog(message.removeColor())
+ return false
+ }
+
+ val thePlayer = minecraft.thePlayer
+ if (thePlayer == null) {
+ LorenzUtils.consoleLog(message.removeColor())
+ return false
+ }
+
+ thePlayer.addChatMessage(ChatComponentText(message))
+ return true
+ }
+
+ /**
+ * Sends a message to the user that they can click and run a command
+ * @param message The message to be sent
+ * @param command The command to be executed when the message is clicked
+ * @param prefix Whether to prefix the message with the chat prefix, default true
+ * @param prefixColor Color that the prefix should be, default yellow (§e)
+ *
+ * @see CHAT_PREFIX
+ */
+ fun clickableChat(message: String, command: String, prefix: Boolean = true, prefixColor: String = "§e") {
+ val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
+ val text = ChatComponentText(msgPrefix + message)
+ val fullCommand = "/" + command.removePrefix("/")
+ text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, fullCommand)
+ text.chatStyle.chatHoverEvent =
+ HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText("§eExecute $fullCommand"))
+ Minecraft.getMinecraft().thePlayer.addChatMessage(text)
+ }
+
+ /**
+ * Sends a message to the user that they can click and run a command
+ * @param message The message to be sent
+ * @param hover The message to be shown when the message is hovered
+ * @param command The command to be executed when the message is clicked
+ * @param prefix Whether to prefix the message with the chat prefix, default true
+ * @param prefixColor Color that the prefix should be, default yellow (§e)
+ *
+ * @see CHAT_PREFIX
+ */
+ fun hoverableChat(
+ message: String,
+ hover: List<String>,
+ command: String? = null,
+ prefix: Boolean = true,
+ prefixColor: String = "§e",
+ ) {
+ val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
+ val text = ChatComponentText(msgPrefix + message)
+ text.chatStyle.chatHoverEvent =
+ HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText(hover.joinToString("\n")))
+
+ command?.let {
+ text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, "/${it.removePrefix("/")}")
+ }
+
+ Minecraft.getMinecraft().thePlayer.addChatMessage(text)
+ }
+
+ /**
+ * Sends a message to the user that they can click and run a command
+ * @param message The message to be sent
+ * @param url The url to be opened
+ * @param autoOpen Automatically opens the url as well as sending the clickable link message
+ * @param hover The message to be shown when the message is hovered
+ * @param prefix Whether to prefix the message with the chat prefix, default true
+ * @param prefixColor Color that the prefix should be, default yellow (§e)
+ *
+ * @see CHAT_PREFIX
+ */
+ fun clickableLinkChat(
+ message: String,
+ url: String,
+ hover: String = "§eOpen $url",
+ autoOpen: Boolean = false,
+ prefix: Boolean = true,
+ prefixColor: String = "§e"
+ ) {
+ val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
+ val text = ChatComponentText(msgPrefix + message)
+ text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.OPEN_URL, url)
+ text.chatStyle.chatHoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText("$prefixColor$hover"))
+ Minecraft.getMinecraft().thePlayer.addChatMessage(text)
+ if (autoOpen) OSUtils.openBrowser(url)
+ }
+
+ private var lastMessageSent = SimpleTimeMark.farPast()
+ private val sendQueue: Queue<String> = LinkedList()
+
+ @SubscribeEvent
+ fun sendQueuedChatMessages(event: LorenzTickEvent) {
+ val player = Minecraft.getMinecraft().thePlayer
+ if (player == null) {
+ sendQueue.clear()
+ return
+ }
+ if (lastMessageSent.passedSince() > 300.milliseconds) {
+ player.sendChatMessage(sendQueue.poll() ?: return)
+ lastMessageSent = SimpleTimeMark.now()
+ }
+ }
+
+ fun sendMessageToServer(message: String) {
+ sendQueue.add(message)
+ }
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt
index 31008d9b4..b1d8eb68b 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ClipboardUtils.kt
@@ -14,6 +14,7 @@ import java.awt.datatransfer.UnsupportedFlavorException
import kotlin.time.Duration.Companion.milliseconds
object ClipboardUtils {
+
private var dispatcher = Dispatchers.IO
private var lastClipboardAccessTime = SimpleTimeMark.farPast()
@@ -71,4 +72,4 @@ object ClipboardUtils {
}
}
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/CollectionUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/CollectionUtils.kt
new file mode 100644
index 000000000..b93f17fa4
--- /dev/null
+++ b/src/main/java/at/hannibal2/skyhanni/utils/CollectionUtils.kt
@@ -0,0 +1,115 @@
+package at.hannibal2.skyhanni.utils
+
+import java.util.Collections
+import java.util.WeakHashMap
+import java.util.concurrent.ConcurrentLinkedQueue
+
+object CollectionUtils {
+
+ fun <E> ConcurrentLinkedQueue<E>.drainTo(list: MutableCollection<E>) {
+ while (true)
+ list.add(this.poll() ?: break)
+ }
+
+ // Let garbage collector handle the removal of entries in this list
+ fun <T> weakReferenceList(): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>())
+
+ fun <T> MutableCollection<T>.filterToMutable(predicate: (T) -> Boolean) = filterTo(mutableListOf(), predicate)
+
+ fun <T> List<T>.indexOfFirst(vararg args: T) = args.map { indexOf(it) }.firstOrNull { it != -1 }
+
+ infix fun <K, V> MutableMap<K, V>.put(pairs: Pair<K, V>) {
+ this[pairs.first] = pairs.second
+ }
+
+ // Taken and modified from Skytils
+ @JvmStatic
+ fun <T> T.equalsOneOf(vararg other: T): Boolean {
+ for (obj in other) {
+ if (this == obj) return true
+ }
+ return false
+ }
+
+ fun <E> List<E>.getOrNull(index: Int): E? {
+ return if (index in indices) {
+ get(index)
+ } else null
+ }
+
+ fun <T : Any> T?.toSingletonListOrEmpty(): List<T> {
+ if (this == null) return emptyList()
+ return listOf(this)
+ }
+
+ fun <K> MutableMap<K, Int>.addOrPut(key: K, number: Int): Int =
+ this.merge(key, number, Int::plus)!! // Never returns null since "plus" can't return null
+
+ fun <K> MutableMap<K, Long>.addOrPut(key: K, number: Long): Long =
+ this.merge(key, number, Long::plus)!! // Never returns null since "plus" can't return null
+
+ fun <K> MutableMap<K, Double>.addOrPut(key: K, number: Double): Double =
+ this.merge(key, number, Double::plus)!! // Never returns null since "plus" can't return null
+
+ fun <K, N : Number> Map<K, N>.sumAllValues(): Double {
+ if (values.isEmpty()) return 0.0
+
+ return when (values.first()) {
+ is Double -> values.sumOf { it.toDouble() }
+ is Float -> values.sumOf { it.toDouble() }
+ is Long -> values.sumOf { it.toLong() }.toDouble()
+ else -> values.sumOf { it.toInt() }.toDouble()
+ }
+ }
+
+ fun List<String>.nextAfter(after: String, skip: Int = 1) = nextAfter({ it == after }, skip)
+
+ fun List<String>.nextAfter(after: (String) -> Boolean, skip: Int = 1): String? {
+ var missing = -1
+ for (line in this) {
+ if (after(line)) {
+ missing = skip - 1
+ continue
+ }
+ if (missing == 0) {
+ return line
+ }
+ if (missing != -1) {
+ missing--
+ }
+ }
+ return null
+ }
+
+ fun <K, V> Map<K, V>.editCopy(function: MutableMap<K, V>.() -> Unit) =
+ toMutableMap().also { function(it) }.toMap()
+
+ fun <T> List<T>.editCopy(function: MutableList<T>.() -> Unit) =
+ toMutableList().also { function(it) }.toList()
+
+ fun <K, V> Map<K, V>.moveEntryToTop(matcher: (Map.Entry<K, V>) -> Boolean): Map<K, V> {
+ val entry = entries.find(matcher)
+ if (entry != null) {
+ val newMap = linkedMapOf(entry.key to entry.value)
+ newMap.putAll(this)
+ return newMap
+ }
+ return this
+ }
+
+ fun <E> MutableList<List<E>>.addAsSingletonList(text: E) {
+ add(Collections.singletonList(text))
+ }
+
+ fun <K, V : Comparable<V>> List<Pair<K, V>>.sorted(): List<Pair<K, V>> {
+ return sortedBy { (_, value) -> value }
+ }
+
+ fun <K, V : Comparable<V>> Map<K, V>.sorted(): Map<K, V> {
+ return toList().sorted().toMap()
+ }
+
+ fun <K, V : Comparable<V>> Map<K, V>.sortedDesc(): Map<K, V> {
+ return toList().sorted().reversed().toMap()
+ }
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ColorUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ColorUtils.kt
index 076afc0c4..8eab43636 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ColorUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ColorUtils.kt
@@ -1,6 +1,11 @@
package at.hannibal2.skyhanni.utils
+import java.awt.Color
+
object ColorUtils {
+
+ /** transfer string colors from the config to java.awt.Color */
+ fun String.toChromaColor() = Color(SpecialColour.specialToChromaRGB(this), true)
fun getRed(colour: Int) = colour shr 16 and 0xFF
fun getGreen(colour: Int) = colour shr 8 and 0xFF
@@ -8,4 +13,4 @@ object ColorUtils {
fun getBlue(colour: Int) = colour and 0xFF
fun getAlpha(colour: Int) = colour shr 24 and 0xFF
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/CombatUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/CombatUtils.kt
index b0af1d93e..31bfe4416 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/CombatUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/CombatUtils.kt
@@ -111,5 +111,4 @@ object CombatUtils {
}
return interp
}
-
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ConditionalUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ConditionalUtils.kt
new file mode 100644
index 000000000..83a8d03f1
--- /dev/null
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ConditionalUtils.kt
@@ -0,0 +1,33 @@
+package at.hannibal2.skyhanni.utils
+
+import io.github.moulberry.moulconfig.observer.Observer
+import io.github.moulberry.moulconfig.observer.Property
+
+object ConditionalUtils {
+
+ fun <T> T.transformIf(condition: T.() -> Boolean, transofmration: T.() -> T) =
+ if (condition()) transofmration(this) else this
+
+ fun <T> T.conditionalTransform(condition: Boolean, ifTrue: T.() -> Any, ifFalse: T.() -> Any) =
+ if (condition) ifTrue(this) else ifFalse(this)
+
+ // MoulConfig is in Java, I don't want to downgrade this logic
+ fun <T> onChange(vararg properties: Property<out T>, observer: Observer<T>) {
+ for (property in properties) {
+ property.whenChanged { a, b -> observer.observeChange(a, b) }
+ }
+ }
+
+ fun <T> onToggle(vararg properties: Property<out T>, observer: Runnable) {
+ onChange(*properties) { _, _ -> observer.run() }
+ }
+
+ fun <T> Property<out T>.onToggle(observer: Runnable) {
+ whenChanged { _, _ -> observer.run() }
+ }
+
+ fun <T> Property<out T>.afterChange(observer: T.() -> Unit) {
+ whenChanged { _, new -> observer(new) }
+ }
+
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ConfigUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ConfigUtils.kt
index 3d8fd5449..55773a9c7 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ConfigUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ConfigUtils.kt
@@ -39,7 +39,7 @@ object ConfigUtils {
*/
private fun <T> getEnumConstantFromLegacyId(
legacyId: Int,
- enumClass: Class<T>
+ enumClass: Class<T>,
): T? where T : Enum<T>, T : HasLegacyId = enumClass.getEnumConstants().firstOrNull { it.legacyId == legacyId }
/**
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt b/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
index 284946072..3c6491ac3 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
@@ -1,10 +1,11 @@
package at.hannibal2.skyhanni.utils
-import at.hannibal2.skyhanni.utils.LorenzUtils.drainTo
+import at.hannibal2.skyhanni.utils.CollectionUtils.drainTo
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.time.Duration
object DelayedRun {
+
private val tasks = mutableListOf<Pair<() -> Any, SimpleTimeMark>>()
private val futureTasks = ConcurrentLinkedQueue<Pair<() -> Any, SimpleTimeMark>>()
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/EntityOutlineRenderer.kt b/src/main/java/at/hannibal2/skyhanni/utils/EntityOutlineRenderer.kt
index ca4827291..fea82caf7 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/EntityOutlineRenderer.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/EntityOutlineRenderer.kt
@@ -32,6 +32,7 @@ import java.lang.reflect.Method
*
*/
object EntityOutlineRenderer {
+
private val entityRenderCache: CachedInfo = CachedInfo(null, null, null)
private var stopLookingForOptifine = false
private var isMissingMixin = false
@@ -400,6 +401,6 @@ object EntityOutlineRenderer {
private class CachedInfo(
var xrayCache: HashMap<Entity, Int>?,
var noXrayCache: HashMap<Entity, Int>?,
- var noOutlineCache: HashSet<Entity>?
+ var noOutlineCache: HashSet<Entity>?,
)
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/EntityUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/EntityUtils.kt
index 36c01c64d..12a2129bf 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/EntityUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/EntityUtils.kt
@@ -99,13 +99,13 @@ object EntityUtils {
fun EntityLivingBase.hasBossHealth(health: Int): Boolean = this.hasMaxHealth(health, true)
- //TODO remove baseMaxHealth
+ // TODO remove baseMaxHealth
fun EntityLivingBase.hasMaxHealth(health: Int, boss: Boolean = false, maxHealth: Int = baseMaxHealth): Boolean {
val derpyMultiplier = if (LorenzUtils.isDerpy) 2 else 1
if (maxHealth == health * derpyMultiplier) return true
if (!boss && !LorenzUtils.inDungeons) {
- //Corrupted
+ // Corrupted
if (maxHealth == health * 3 * derpyMultiplier) return true
// Runic
if (maxHealth == health * 4 * derpyMultiplier) return true
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/GuiRenderUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/GuiRenderUtils.kt
index 5e4a63452..1d0b42b92 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/GuiRenderUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/GuiRenderUtils.kt
@@ -91,7 +91,7 @@ object GuiRenderUtils {
mouseX: Int,
mouseY: Int,
screenHeight: Int,
- fr: FontRenderer
+ fr: FontRenderer,
) {
if (textLines.isNotEmpty()) {
val borderColor = StringUtils.getColor(textLines[0], 0x505000FF)
@@ -187,7 +187,7 @@ object GuiRenderUtils {
y: Int,
mouseX: Int,
mouseY: Int,
- color: Int = 0xFF43464B.toInt()
+ color: Int = 0xFF43464B.toInt(),
) {
GuiScreen.drawRect(x, y, x + 16, y + 16, color)
if (item != null) {
@@ -206,7 +206,7 @@ object GuiRenderUtils {
y: Float,
mouseX: Float,
mouseY: Float,
- color: Int = 0xFF43464B.toInt()
+ color: Int = 0xFF43464B.toInt(),
) {
renderItemAndTip(list, item, x.toInt(), y.toInt(), mouseX.toInt(), mouseY.toInt(), color)
}
@@ -223,7 +223,7 @@ object GuiRenderUtils {
mouseX: Int,
mouseY: Int,
output: MutableList<String>,
- textScale: Float = .7f
+ textScale: Float = .7f,
) {
var currentVal = currentValue.toDouble()
currentVal = if (currentVal < 0) 0.0 else currentVal
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/IdentityCharacteristics.kt b/src/main/java/at/hannibal2/skyhanni/utils/IdentityCharacteristics.kt
index 5b1399f73..64d059bd3 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/IdentityCharacteristics.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/IdentityCharacteristics.kt
@@ -1,6 +1,7 @@
package at.hannibal2.skyhanni.utils
class IdentityCharacteristics<T>(val value: T) {
+
override fun equals(other: Any?): Boolean {
if (other !is IdentityCharacteristics<*>) return false
return this.value === other.value
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/InventoryUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/InventoryUtils.kt
index 827b87854..1da7170ac 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/InventoryUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/InventoryUtils.kt
@@ -12,6 +12,7 @@ import net.minecraft.item.ItemStack
import kotlin.time.Duration.Companion.seconds
object InventoryUtils {
+
var itemInHandId = NEUInternalName.NONE
var recentItemsInHand = mutableMapOf<Long, NEUInternalName>()
var latestItemInHand: ItemStack? = null
@@ -42,7 +43,7 @@ object InventoryUtils {
fun inStorage() = openInventoryName().let {
(it.contains("Storage") && !it.contains("Rift Storage"))
- || it.contains("Ender Chest") || it.contains("Backpack")
+ || it.contains("Ender Chest") || it.contains("Backpack")
}
fun getItemInHand(): ItemStack? = Minecraft.getMinecraft().thePlayer.heldItem
@@ -54,7 +55,6 @@ object InventoryUtils {
fun getLeggings(): ItemStack? = getArmor()[1]
fun getBoots(): ItemStack? = getArmor()[0]
-
val isNeuStorageEnabled = RecalculatingValue(10.seconds) {
try {
val config = NotEnoughUpdates.INSTANCE.config
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ItemBlink.kt b/src/main/java/at/hannibal2/skyhanni/utils/ItemBlink.kt
index 8afc2a2b7..baa9a8c40 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ItemBlink.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ItemBlink.kt
@@ -4,6 +4,7 @@ import net.minecraft.item.Item
import net.minecraft.item.ItemStack
object ItemBlink {
+
private val offsets = mutableMapOf<Item, Long>()
private var lastOffset = 0L
private var endOfBlink = 0L
@@ -28,4 +29,4 @@ object ItemBlink {
}
return if ((offset + System.currentTimeMillis()) % 1000 > 500) stack else this
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ItemStackTypeAdapter.kt b/src/main/java/at/hannibal2/skyhanni/utils/ItemStackTypeAdapter.kt
index 38002990f..602bffa2d 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ItemStackTypeAdapter.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ItemStackTypeAdapter.kt
@@ -10,6 +10,7 @@ import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
object ItemStackTypeAdapterFactory : TypeAdapterFactory {
+
override fun <T : Any> create(gson: Gson?, type: TypeToken<T>): TypeAdapter<T>? {
if (type.rawType == ItemStack::class.java) {
val nbtCompoundTypeAdapter = gson!!.getAdapter(NBTTagCompound::class.java)
@@ -25,5 +26,4 @@ object ItemStackTypeAdapterFactory : TypeAdapterFactory {
}
return null
}
-
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ItemUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ItemUtils.kt
index d2c9776b7..0f506bacc 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ItemUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ItemUtils.kt
@@ -74,7 +74,7 @@ object ItemUtils {
val list: LinkedList<ItemStack> = LinkedList()
val player = Minecraft.getMinecraft().thePlayer
if (player == null) {
- LorenzUtils.error("getItemsInInventoryWithSlots: player is null!")
+ ChatUtils.error("getItemsInInventoryWithSlots: player is null!")
return list
}
for (slot in player.openContainer.inventorySlots) {
@@ -93,7 +93,7 @@ object ItemUtils {
val map: LinkedHashMap<ItemStack, Int> = LinkedHashMap()
val player = Minecraft.getMinecraft().thePlayer
if (player == null) {
- LorenzUtils.error("getItemsInInventoryWithSlots: player is null!")
+ ChatUtils.error("getItemsInInventoryWithSlots: player is null!")
return map
}
for (slot in player.openContainer.inventorySlots) {
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/KSerializable.kt b/src/main/java/at/hannibal2/skyhanni/utils/KSerializable.kt
index d075f35f7..5b80dc8b3 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/KSerializable.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/KSerializable.kt
@@ -24,19 +24,17 @@ import com.google.gson.internal.`$Gson$Types` as InternalGsonTypes
@Target(AnnotationTarget.CLASS)
annotation class KSerializable
-
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS)
annotation class ExtraData
-
class KotlinTypeAdapterFactory : TypeAdapterFactory {
internal data class ParameterInfo(
val param: KParameter,
val adapter: TypeAdapter<Any?>,
val name: String,
- val field: KProperty1<Any, Any?>
+ val field: KProperty1<Any, Any?>,
)
@OptIn(ExperimentalStdlibApi::class)
@@ -110,4 +108,4 @@ class KotlinTypeAdapterFactory : TypeAdapterFactory {
}
}
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/KeyboardManager.kt b/src/main/java/at/hannibal2/skyhanni/utils/KeyboardManager.kt
index 335ac1202..1050c5c98 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/KeyboardManager.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/KeyboardManager.kt
@@ -13,6 +13,7 @@ import org.lwjgl.input.Keyboard
import org.lwjgl.input.Mouse
object KeyboardManager {
+
private var lastClickedMouseButton = -1
// A mac-only key, represents Windows key on windows (but different key code)
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzColor.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzColor.kt
index e8b0d76bc..39c877db0 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzColor.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzColor.kt
@@ -39,6 +39,7 @@ enum class LorenzColor(private val chatColorCode: Char, private val color: Color
override fun toString(): String = coloredLabel
companion object {
+
fun EnumDyeColor.toLorenzColor() = when (this) {
EnumDyeColor.WHITE -> WHITE
EnumDyeColor.MAGENTA -> LIGHT_PURPLE
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzDebug.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzDebug.kt
index 93bd8419e..664ef5fd6 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzDebug.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzDebug.kt
@@ -10,7 +10,7 @@ object LorenzDebug {
}
fun chatAndLog(text: String) {
- LorenzUtils.debug(text)
+ ChatUtils.debug(text)
log(text)
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzLogger.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzLogger.kt
index e949742cd..26f56fcca 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzLogger.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzLogger.kt
@@ -15,10 +15,12 @@ import java.util.logging.Logger
import kotlin.time.Duration.Companion.days
class LorenzLogger(filePath: String) {
+
private val format = SimpleDateFormat("HH:mm:ss")
private val fileName = "$PREFIX_PATH$filePath.log"
companion object {
+
private var LOG_DIRECTORY = File("config/skyhanni/logs")
private var PREFIX_PATH: String
var hasDone = false
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
index 9c4116da4..33731505f 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
@@ -6,10 +6,11 @@ import at.hannibal2.skyhanni.data.IslandType
import at.hannibal2.skyhanni.data.MayorElection
import at.hannibal2.skyhanni.data.TitleManager
import at.hannibal2.skyhanni.events.GuiContainerEvent
-import at.hannibal2.skyhanni.events.LorenzTickEvent
import at.hannibal2.skyhanni.features.dungeon.DungeonAPI
import at.hannibal2.skyhanni.mixins.transformers.AccessorGuiEditSign
import at.hannibal2.skyhanni.test.TestBingo
+import at.hannibal2.skyhanni.utils.ChatUtils.lastButtonClicked
+import at.hannibal2.skyhanni.utils.CollectionUtils.sortedDesc
import at.hannibal2.skyhanni.utils.NEUItems.getItemStackOrNull
import at.hannibal2.skyhanni.utils.NumberUtil.addSeparators
import at.hannibal2.skyhanni.utils.StringUtils.capAtMinecraftLength
@@ -17,44 +18,20 @@ import at.hannibal2.skyhanni.utils.StringUtils.removeColor
import at.hannibal2.skyhanni.utils.StringUtils.toDashlessUUID
import at.hannibal2.skyhanni.utils.renderables.Renderable
import com.google.gson.JsonPrimitive
-import io.github.moulberry.moulconfig.observer.Observer
-import io.github.moulberry.moulconfig.observer.Property
import io.github.moulberry.notenoughupdates.util.SkyBlockTime
import net.minecraft.client.Minecraft
import net.minecraft.client.gui.inventory.GuiEditSign
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.SharedMonsterAttributes
-import net.minecraft.event.ClickEvent
-import net.minecraft.event.HoverEvent
import net.minecraft.launchwrapper.Launch
import net.minecraft.util.ChatComponentText
import net.minecraftforge.fml.common.FMLCommonHandler
-import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
-import java.awt.Color
-import java.lang.reflect.Constructor
-import java.lang.reflect.Field
-import java.lang.reflect.Modifier
import java.text.DecimalFormat
import java.text.SimpleDateFormat
-import java.util.Collections
-import java.util.LinkedList
-import java.util.Queue
import java.util.Timer
import java.util.TimerTask
-import java.util.WeakHashMap
-import java.util.concurrent.ConcurrentLinkedQueue
import java.util.regex.Matcher
-import kotlin.properties.ReadWriteProperty
-import kotlin.reflect.KMutableProperty1
-import kotlin.reflect.KProperty
-import kotlin.reflect.KProperty0
-import kotlin.reflect.KProperty1
-import kotlin.reflect.full.isSubtypeOf
-import kotlin.reflect.full.memberProperties
-import kotlin.reflect.full.starProjectedType
-import kotlin.reflect.jvm.isAccessible
import kotlin.time.Duration
-import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
object LorenzUtils {
@@ -90,98 +67,6 @@ object LorenzUtils {
val lastWorldSwitch get() = HypixelData.joinedWorld
- // TODO log based on chat category (error, warning, debug, user error, normal)
- private val log = LorenzLogger("chat/mod_sent")
- var lastButtonClicked = 0L
-
- private const val DEBUG_PREFIX = "[SkyHanni Debug] §7"
- private const val USER_ERROR_PREFIX = "§c[SkyHanni] "
- private val ERROR_PREFIX by lazy { "§c[SkyHanni-${SkyHanniMod.version}] " }
- private const val CHAT_PREFIX = "[SkyHanni] "
-
- /**
- * Sends a debug message to the chat and the console.
- * This is only sent if the debug feature is enabled.
- *
- * @param message The message to be sent
- *
- * @see DEBUG_PREFIX
- */
- fun debug(message: String) {
- if (SkyHanniMod.feature.dev.debug.enabled && internalChat(DEBUG_PREFIX + message)) {
- consoleLog("[Debug] $message")
- }
- }
-
- /**
- * Sends a message to the user that they did something incorrectly.
- * We should tell them what to do instead as well.
- *
- * @param message The message to be sent
- *
- * @see USER_ERROR_PREFIX
- */
- fun userError(message: String) {
- internalChat(USER_ERROR_PREFIX + message)
- }
-
- /**
- * Sends a message to the user that an error occurred caused by something in the code.
- * This should be used for errors that are not caused by the user.
- *
- * Why deprecate this? Even if this message is descriptive for the user and the developer,
- * we don't want inconsitencies in errors, and we would need to search
- * for the code line where this error gets printed any way.
- * so it's better to use the stack trace still.
- *
- * @param message The message to be sent
- * @param prefix Whether to prefix the message with the error prefix, default true
- *
- * @see ERROR_PREFIX
- */
- @Deprecated(
- "Do not send the user a non clickable non stacktrace containing error message.",
- ReplaceWith("ErrorManager")
- )
- fun error(message: String) {
- println("error: '$message'")
- internalChat(ERROR_PREFIX + message)
- }
-
- /**
- * Sends a message to the user
- * @param message The message to be sent
- * @param prefix Whether to prefix the message with the chat prefix, default true
- * @param prefixColor Color that the prefix should be, default yellow (§e)
- *
- * @see CHAT_PREFIX
- */
- fun chat(message: String, prefix: Boolean = true, prefixColor: String = "§e") {
- if (prefix) {
- internalChat(prefixColor + CHAT_PREFIX + message)
- } else {
- internalChat(message)
- }
- }
-
- private fun internalChat(message: String): Boolean {
- log.log(message)
- val minecraft = Minecraft.getMinecraft()
- if (minecraft == null) {
- consoleLog(message.removeColor())
- return false
- }
-
- val thePlayer = minecraft.thePlayer
- if (thePlayer == null) {
- consoleLog(message.removeColor())
- return false
- }
-
- thePlayer.addChatMessage(ChatComponentText(message))
- return true
- }
-
fun SimpleDateFormat.formatCurrentTime(): String = this.format(System.currentTimeMillis())
fun stripVanillaMessage(originalMessage: String): String {
@@ -254,18 +139,6 @@ object LorenzUtils {
}
}
- fun <K, V : Comparable<V>> List<Pair<K, V>>.sorted(): List<Pair<K, V>> {
- return sortedBy { (_, value) -> value }
- }
-
- fun <K, V : Comparable<V>> Map<K, V>.sorted(): Map<K, V> {
- return toList().sorted().toMap()
- }
-
- fun <K, V : Comparable<V>> Map<K, V>.sortedDesc(): Map<K, V> {
- return toList().sorted().reversed().toMap()
- }
-
fun getSBMonthByName(month: String): Int {
var monthNr = 0
for (i in 1..12) {
@@ -283,10 +156,6 @@ object LorenzUtils {
fun getPlayerName(): String = Minecraft.getMinecraft().thePlayer.name
- fun <E> MutableList<List<E>>.addAsSingletonList(text: E) {
- add(Collections.singletonList(text))
- }
-
// (key -> value) -> (sorting value -> key item icon)
fun fillTable(list: MutableList<List<Any>>, data: MutableMap<Pair<String, String>, Pair<Double, NEUInternalName>>) {
val keys = data.mapValues { (_, v) -> v.first }.sortedDesc().keys
@@ -321,140 +190,6 @@ object LorenzUtils {
lines[index] = ChatComponentText(text.capAtMinecraftLength(91))
}
- /**
- * Sends a message to the user that they can click and run a command
- * @param message The message to be sent
- * @param command The command to be executed when the message is clicked
- * @param prefix Whether to prefix the message with the chat prefix, default true
- * @param prefixColor Color that the prefix should be, default yellow (§e)
- *
- * @see CHAT_PREFIX
- */
- fun clickableChat(message: String, command: String, prefix: Boolean = true, prefixColor: String = "§e") {
- val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
- val text = ChatComponentText(msgPrefix + message)
- val fullCommand = "/" + command.removePrefix("/")
- text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, fullCommand)
- text.chatStyle.chatHoverEvent =
- HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText("§eExecute $fullCommand"))
- Minecraft.getMinecraft().thePlayer.addChatMessage(text)
- }
-
- /**
- * Sends a message to the user that they can click and run a command
- * @param message The message to be sent
- * @param hover The message to be shown when the message is hovered
- * @param command The command to be executed when the message is clicked
- * @param prefix Whether to prefix the message with the chat prefix, default true
- * @param prefixColor Color that the prefix should be, default yellow (§e)
- *
- * @see CHAT_PREFIX
- */
- fun hoverableChat(
- message: String,
- hover: List<String>,
- command: String? = null,
- prefix: Boolean = true,
- prefixColor: String = "§e",
- ) {
- val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
- val text = ChatComponentText(msgPrefix + message)
- text.chatStyle.chatHoverEvent =
- HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText(hover.joinToString("\n")))
-
- command?.let {
- text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.RUN_COMMAND, "/${it.removePrefix("/")}")
- }
-
- Minecraft.getMinecraft().thePlayer.addChatMessage(text)
- }
-
- /**
- * Sends a message to the user that they can click and run a command
- * @param message The message to be sent
- * @param url The url to be opened
- * @param autoOpen Automatically opens the url as well as sending the clickable link message
- * @param hover The message to be shown when the message is hovered
- * @param prefix Whether to prefix the message with the chat prefix, default true
- * @param prefixColor Color that the prefix should be, default yellow (§e)
- *
- * @see CHAT_PREFIX
- */
- fun clickableLinkChat(
- message: String,
- url: String,
- hover: String = "§eOpen $url",
- autoOpen: Boolean = false,
- prefix: Boolean = true,
- prefixColor: String = "§e"
- ) {
- val msgPrefix = if (prefix) prefixColor + CHAT_PREFIX else ""
- val text = ChatComponentText(msgPrefix + message)
- text.chatStyle.chatClickEvent = ClickEvent(ClickEvent.Action.OPEN_URL, url)
- text.chatStyle.chatHoverEvent = HoverEvent(HoverEvent.Action.SHOW_TEXT, ChatComponentText("$prefixColor$hover"))
- Minecraft.getMinecraft().thePlayer.addChatMessage(text)
- if (autoOpen) OSUtils.openBrowser(url)
- }
-
- fun <K, V> Map<K, V>.moveEntryToTop(matcher: (Map.Entry<K, V>) -> Boolean): Map<K, V> {
- val entry = entries.find(matcher)
- if (entry != null) {
- val newMap = linkedMapOf(entry.key to entry.value)
- newMap.putAll(this)
- return newMap
- }
- return this
- }
-
- private var lastMessageSent = SimpleTimeMark.farPast()
- private val sendQueue: Queue<String> = LinkedList()
-
- @SubscribeEvent
- fun sendQueuedChatMessages(event: LorenzTickEvent) {
- val player = Minecraft.getMinecraft().thePlayer
- if (player == null) {
- sendQueue.clear()
- return
- }
- if (lastMessageSent.passedSince() > 300.milliseconds) {
- player.sendChatMessage(sendQueue.poll() ?: return)
- lastMessageSent = SimpleTimeMark.now()
- }
- }
-
- fun sendCommandToServer(command: String) {
- sendMessageToServer("/$command")
- }
-
- fun sendMessageToServer(message: String) {
- sendQueue.add(message)
- }
-
- // MoulConfig is in Java, I don't want to downgrade this logic
- fun <T> onChange(vararg properties: Property<out T>, observer: Observer<T>) {
- for (property in properties) {
- property.whenChanged { a, b -> observer.observeChange(a, b) }
- }
- }
-
- fun <T> onToggle(vararg properties: Property<out T>, observer: Runnable) {
- onChange(*properties) { _, _ -> observer.run() }
- }
-
- fun <T> Property<out T>.onToggle(observer: Runnable) {
- whenChanged { _, _ -> observer.run() }
- }
-
- fun <T> Property<out T>.afterChange(observer: T.() -> Unit) {
- whenChanged { _, new -> observer(new) }
- }
-
- fun <K, V> Map<K, V>.editCopy(function: MutableMap<K, V>.() -> Unit) =
- toMutableMap().also { function(it) }.toMap()
-
- fun <T> List<T>.editCopy(function: MutableList<T>.() -> Unit) =
- toMutableList().also { function(it) }.toList()
-
fun colorCodeToRarity(colorCode: Char): String {
return when (colorCode) {
'f' -> "Common"
@@ -525,61 +260,6 @@ object LorenzUtils {
})
}
- // TODO nea?
-// fun <T> dynamic(block: () -> KMutableProperty0<T>?): ReadWriteProperty<Any?, T?> {
-// return object : ReadWriteProperty<Any?, T?> {
-// override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
-// return block()?.get()
-// }
-//
-// override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
-// if (value != null)
-// block()?.set(value)
-// }
-// }
-// }
-
- fun <T, R> dynamic(root: KProperty0<R?>, child: KMutableProperty1<R, T>) =
- object : ReadWriteProperty<Any?, T?> {
- override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
- val rootObj = root.get() ?: return null
- return child.get(rootObj)
- }
-
- override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
- if (value == null) return
- val rootObj = root.get() ?: return
- child.set(rootObj, value)
- }
- }
-
- inline fun <reified T : Any> Any.getPropertiesWithType() =
- this::class.memberProperties
- .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) }
- .map {
- it.isAccessible = true
- (it as KProperty1<Any, T>).get(this)
- }
-
- fun List<String>.nextAfter(after: String, skip: Int = 1) = nextAfter({ it == after }, skip)
-
- fun List<String>.nextAfter(after: (String) -> Boolean, skip: Int = 1): String? {
- var missing = -1
- for (line in this) {
- if (after(line)) {
- missing = skip - 1
- continue
- }
- if (missing == 0) {
- return line
- }
- if (missing != -1) {
- missing--
- }
- }
- return null
- }
-
fun GuiEditSign.isRancherSign(): Boolean {
if (this !is AccessorGuiEditSign) return false
@@ -591,74 +271,6 @@ object LorenzUtils {
fun IslandType.isInIsland() = inSkyBlock && skyBlockIsland == this
- fun <K> MutableMap<K, Int>.addOrPut(key: K, number: Int): Int {
- val currentValue = this[key] ?: 0
- val newValue = currentValue + number
- this[key] = newValue
- return newValue
- }
-
- fun <K> MutableMap<K, Long>.addOrPut(key: K, number: Long): Long {
- val currentValue = this[key] ?: 0L
- val newValue = currentValue + number
- this[key] = newValue
- return newValue
- }
-
- fun <K> MutableMap<K, Double>.addOrPut(key: K, number: Double): Double {
- val currentValue = this[key] ?: 0.0
- val newValue = currentValue + number
- this[key] = newValue
- return newValue
- }
-
- fun <K, N : Number> Map<K, N>.sumAllValues(): Double {
- if (values.isEmpty()) return 0.0
-
- return when (values.first()) {
- is Double -> values.sumOf { it.toDouble() }
- is Float -> values.sumOf { it.toDouble() }
- is Long -> values.sumOf { it.toLong() }.toDouble()
- else -> values.sumOf { it.toInt() }.toDouble()
- }
- }
-
- /** transfer string colors from the config to java.awt.Color */
- fun String.toChromaColor() = Color(SpecialColour.specialToChromaRGB(this), true)
-
- fun <E> List<E>.getOrNull(index: Int): E? {
- return if (index in indices) {
- get(index)
- } else null
- }
-
- fun <T : Any> T?.toSingletonListOrEmpty(): List<T> {
- if (this == null) return emptyList()
- return listOf(this)
- }
-
- fun Field.makeAccessible() = also { isAccessible = true }
-
- fun <T> Constructor<T>.makeAccessible() = also { isAccessible = true }
-
- // Taken and modified from Skytils
- @JvmStatic
- fun <T> T.equalsOneOf(vararg other: T): Boolean {
- for (obj in other) {
- if (this == obj) return true
- }
- return false
- }
-
- infix fun <K, V> MutableMap<K, V>.put(pairs: Pair<K, V>) {
- this[pairs.first] = pairs.second
- }
-
- fun Field.removeFinal(): Field {
- javaClass.getDeclaredField("modifiers").makeAccessible().set(this, modifiers and (Modifier.FINAL.inv()))
- return this
- }
-
fun GuiContainerEvent.SlotClickEvent.makeShiftClick() =
slot?.slotNumber?.let { slotNumber ->
Minecraft.getMinecraft().playerController.windowClick(
@@ -666,8 +278,6 @@ object LorenzUtils {
)?.also { isCanceled = true }
}
- fun <T> List<T>.indexOfFirst(vararg args: T) = args.map { indexOf(it) }.firstOrNull { it != -1 }
-
private val recalculateDerpy =
RecalculatingValue(1.seconds) { MayorElection.isPerkActive("Derpy", "DOUBLE MOBS HP!!!") }
@@ -687,12 +297,6 @@ object LorenzUtils {
val JsonPrimitive.asIntOrNull get() = takeIf { it.isNumber }?.asInt
- fun <T> T.transformIf(condition: T.() -> Boolean, transofmration: T.() -> T) =
- if (condition()) transofmration(this) else this
-
- fun <T> T.conditionalTransform(condition: Boolean, ifTrue: T.() -> Any, ifFalse: T.() -> Any) =
- if (condition) ifTrue(this) else ifFalse(this)
-
fun sendTitle(text: String, duration: Duration, height: Double = 1.8, fontSize: Float = 4f) {
TitleManager.sendTitle(text, duration, height, fontSize)
}
@@ -722,6 +326,10 @@ object LorenzUtils {
FMLCommonHandler.instance().handleExit(-1)
}
+ fun sendCommandToServer(command: String) {
+ ChatUtils.sendMessageToServer("/$command")
+ }
+
/**
* Get the group, otherwise, return null
* @param groupName The group name in the pattern
@@ -730,16 +338,29 @@ object LorenzUtils {
return runCatching { this.group(groupName) }.getOrNull()
}
- fun <E> ConcurrentLinkedQueue<E>.drainTo(list: MutableCollection<E>) {
- while (true)
- list.add(this.poll() ?: break)
- }
+ @Deprecated("moved", ReplaceWith("ChatUtils.debug"))
+ fun debug(message: String) = ChatUtils.debug(message)
- // Let garbage collector handle the removal of entries in this list
- fun <T> weakReferenceList(): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>())
+ @Deprecated("moved", ReplaceWith("ChatUtils.userError"))
+ fun userError(message: String) = ChatUtils.userError(message)
- fun <T> MutableCollection<T>.filterToMutable(predicate: (T) -> Boolean) = filterTo(mutableListOf(), predicate)
+ @Deprecated("moved", ReplaceWith("ChatUtils.chat"))
+ fun chat(message: String, prefix: Boolean = true, prefixColor: String = "§e") =
+ ChatUtils.chat(message, prefix, prefixColor)
+
+ @Deprecated("moved", ReplaceWith("ChatUtils.clickableChat"))
+ fun clickableChat(message: String, command: String, prefix: Boolean = true, prefixColor: String = "§e") =
+ ChatUtils.clickableChat(message, command, prefix, prefixColor)
+
+ @Deprecated("moved", ReplaceWith("ChatUtils.hoverableChat"))
+ fun hoverableChat(
+ message: String,
+ hover: List<String>,
+ command: String? = null,
+ prefix: Boolean = true,
+ prefixColor: String = "§e",
+ ) = ChatUtils.hoverableChat(message, hover, command, prefix, prefixColor)
- val Long.ticks get() = (this * 50).milliseconds
- val Int.ticks get() = (this * 50).milliseconds
+ @Deprecated("moved", ReplaceWith("ChatUtils.sendMessageToServer"))
+ fun sendMessageToServer(message: String) = ChatUtils.sendMessageToServer(message)
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzVec.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzVec.kt
index ba337b620..03f623f70 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzVec.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzVec.kt
@@ -144,6 +144,7 @@ data class LorenzVec(
}
companion object {
+
fun getFromYawPitch(yaw: Double, pitch: Double): LorenzVec {
val yaw: Double = (yaw + 90) * Math.PI / 180
val pitch: Double = (pitch + 90) * Math.PI / 180
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/MinecraftConsoleFilter.kt b/src/main/java/at/hannibal2/skyhanni/utils/MinecraftConsoleFilter.kt
index 3e1919d8b..c6ebdd836 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/MinecraftConsoleFilter.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/MinecraftConsoleFilter.kt
@@ -24,6 +24,7 @@ class MinecraftConsoleFilter(private val loggerConfigName: String) : Filter {
private val patternBiomeIdBounds = "Biome ID is out of bounds: (\\d+), defaulting to 0 \\(Ocean\\)".toPattern()
companion object {
+
fun initLogging() {
val ctx: LoggerContext = LogManager.getContext(false) as LoggerContext
@@ -56,7 +57,7 @@ class MinecraftConsoleFilter(private val loggerConfigName: String) : Filter {
filterConsole("Unknown soundEvent (minecraft:)")
return Filter.Result.DENY
}
- //TODO testing
+ // TODO testing
if (filterConfig.filterParticleVillagerHappy && formattedMessage == "Could not spawn particle effect VILLAGER_HAPPY") {
filterConsole("particle VILLAGER_HAPPY")
return Filter.Result.DENY
@@ -83,7 +84,7 @@ class MinecraftConsoleFilter(private val loggerConfigName: String) : Filter {
}
}
- //TODO find a way to load the filter earlier to filter these messages too
+ // TODO find a way to load the filter earlier to filter these messages too
// if (loggerName == "LaunchWrapper") {
// //The jar file C:\Users\Lorenz\AppData\Roaming\.minecraft\libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar has a security seal for path org.lwjgl.opengl, but that path is defined and not secure
// if (formattedMessage.startsWith("The jar file ")) {
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/MinecraftDispatcher.kt b/src/main/java/at/hannibal2/skyhanni/utils/MinecraftDispatcher.kt
index 8771de215..7cbfffe37 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/MinecraftDispatcher.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/MinecraftDispatcher.kt
@@ -5,6 +5,7 @@ import net.minecraft.client.Minecraft
import kotlin.coroutines.CoroutineContext
object MinecraftDispatcher : MainCoroutineDispatcher() {
+
override val immediate: MainCoroutineDispatcher
get() = this
@@ -15,4 +16,4 @@ object MinecraftDispatcher : MainCoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
Minecraft.getMinecraft().addScheduledTask(block)
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/MultiFilter.kt b/src/main/java/at/hannibal2/skyhanni/utils/MultiFilter.kt
index bc3b1789e..f50a5e1dd 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/MultiFilter.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/MultiFilter.kt
@@ -1,7 +1,7 @@
package at.hannibal2.skyhanni.utils
-import at.hannibal2.skyhanni.utils.StringUtils.trimWhiteSpace
import at.hannibal2.skyhanni.data.jsonobjects.repo.MultiFilterJson
+import at.hannibal2.skyhanni.utils.StringUtils.trimWhiteSpace
class MultiFilter {
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/NBTTypeAdapter.kt b/src/main/java/at/hannibal2/skyhanni/utils/NBTTypeAdapter.kt
index dd798d7bf..4e0762895 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/NBTTypeAdapter.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/NBTTypeAdapter.kt
@@ -10,6 +10,7 @@ import java.io.ByteArrayOutputStream
import java.util.Base64
object NBTTypeAdapter : TypeAdapter<NBTTagCompound>() {
+
override fun write(out: JsonWriter, value: NBTTagCompound) {
val baos = ByteArrayOutputStream()
CompressedStreamTools.writeCompressed(value, baos)
@@ -20,4 +21,4 @@ object NBTTypeAdapter : TypeAdapter<NBTTagCompound>() {
val bais = ByteArrayInputStream(Base64.getDecoder().decode(reader.nextString()))
return CompressedStreamTools.readCompressed(bais)
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/NEUInternalName.kt b/src/main/java/at/hannibal2/skyhanni/utils/NEUInternalName.kt
index d4499ab12..26bfcc799 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/NEUInternalName.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/NEUInternalName.kt
@@ -3,6 +3,7 @@ package at.hannibal2.skyhanni.utils
class NEUInternalName private constructor(private val internalName: String) {
companion object {
+
private val map = mutableMapOf<String, NEUInternalName>()
val NONE = "NONE".asInternalName()
@@ -39,4 +40,4 @@ class NEUInternalName private constructor(private val internalName: String) {
fun replace(oldValue: String, newValue: String) =
internalName.replace(oldValue.uppercase(), newValue.uppercase()).asInternalName()
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt b/src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt
index cd1838bdc..06901f239 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/NEUItems.kt
@@ -35,6 +35,7 @@ import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import org.lwjgl.opengl.GL11
object NEUItems {
+
val manager: NEUManager get() = NotEnoughUpdates.INSTANCE.manager
private val itemNameCache = mutableMapOf<String, NEUInternalName>() // item name -> internal name
private val multiplierCache = mutableMapOf<NEUInternalName, Pair<NEUInternalName, Int>>()
@@ -213,7 +214,6 @@ object NEUItems {
fun isVanillaItem(item: ItemStack): Boolean =
manager.auctionManager.isVanillaItem(item.getInternalName().asString())
-
fun ItemStack.renderOnScreen(x: Float, y: Float, scaleMultiplier: Double = 1.0) {
val item = checkBlinkItem()
val isSkull = item.item === Items.skull
@@ -327,7 +327,6 @@ object NEUItems {
val result = Pair(internalName, 1)
multiplierCache[internalName] = result
return result
-
}
@Deprecated("Do not use strings as id", ReplaceWith("getMultiplier with NEUInternalName"))
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt b/src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt
index 31062b559..639d57bd0 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/NumberUtil.kt
@@ -7,6 +7,7 @@ import kotlin.math.pow
import kotlin.math.roundToInt
object NumberUtil {
+
@JvmField
val nf: NumberFormat = NumberFormat.getInstance(Locale.US)
private val suffixes = TreeMap<Long, String>().apply {
@@ -45,15 +46,15 @@ object NumberUtil {
fun format(value: Number, preciseBillions: Boolean = false): String {
@Suppress("NAME_SHADOWING")
val value = value.toLong()
- //Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
+ // Long.MIN_VALUE == -Long.MIN_VALUE so we need an adjustment here
if (value == Long.MIN_VALUE) return format(Long.MIN_VALUE + 1, preciseBillions)
if (value < 0) return "-" + format(-value, preciseBillions)
- if (value < 1000) return value.toString() //deal with small numbers
+ if (value < 1000) return value.toString() // deal with small numbers
val (divideBy, suffix) = suffixes.floorEntry(value)
- val truncated = value / (divideBy / 10) //the number part of the output times 10
+ val truncated = value / (divideBy / 10) // the number part of the output times 10
val truncatedAt = if (suffix == "M") 1000 else if (suffix == "B") 1000000 else 100
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/OSUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/OSUtils.kt
index 1f28effae..0cb4e043e 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/OSUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/OSUtils.kt
@@ -17,7 +17,7 @@ object OSUtils {
}
} else {
copyToClipboard(url)
- LorenzUtils.error("Web browser is not supported! Copied url to clipboard.")
+ ChatUtils.error("Web browser is not supported! Copied url to clipboard.")
}
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ParkourHelper.kt b/src/main/java/at/hannibal2/skyhanni/utils/ParkourHelper.kt
index c9ebdc5a6..14787a980 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/ParkourHelper.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ParkourHelper.kt
@@ -4,8 +4,8 @@ import at.hannibal2.skyhanni.SkyHanniMod
import at.hannibal2.skyhanni.data.jsonobjects.repo.ParkourJson.ShortCut
import at.hannibal2.skyhanni.events.LorenzRenderWorldEvent
import at.hannibal2.skyhanni.test.command.ErrorManager
+import at.hannibal2.skyhanni.utils.CollectionUtils.toSingletonListOrEmpty
import at.hannibal2.skyhanni.utils.LocationUtils.distanceToPlayer
-import at.hannibal2.skyhanni.utils.LorenzUtils.toSingletonListOrEmpty
import at.hannibal2.skyhanni.utils.RenderUtils.draw3DLine_nea
import at.hannibal2.skyhanni.utils.RenderUtils.drawDynamicText
import at.hannibal2.skyhanni.utils.RenderUtils.drawFilledBoundingBox_nea
@@ -22,8 +22,9 @@ class ParkourHelper(
val platformSize: Double = 1.0,
val detectionRange: Double = 1.0,
val depth: Boolean = true,
- val onEndReach: () -> Unit = {}
+ val onEndReach: () -> Unit = {},
) {
+
private var current = -1
private var visible = false
@@ -105,7 +106,6 @@ class ParkourHelper(
event.drawFilledBoundingBox_nea(aabb, Color.RED, 1f)
if (outline) event.outlineTopFace(aabb, 2, Color.BLACK, depth)
}
-
}
for ((index, location) in locations.asSequence().withIndex().drop(current)
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/RecalculatingValue.kt b/src/main/java/at/hannibal2/skyhanni/utils/RecalculatingValue.kt
index 7c734c57e..76f0c0c94 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/RecalculatingValue.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/RecalculatingValue.kt
@@ -3,6 +3,7 @@ package at.hannibal2.skyhanni.utils
import kotlin.time.Duration
class RecalculatingValue<T>(private val expireTime: Duration, val calculation: () -> T) {
+
private var currentValue = calculation()
private var lastAccessTime = SimpleTimeMark.farPast()
@@ -13,4 +14,4 @@ class RecalculatingValue<T>(private val expireTime: Duration, val calculation: (
}
return currentValue
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/ReflectionUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/ReflectionUtils.kt
new file mode 100644
index 000000000..2cf613b39
--- /dev/null
+++ b/src/main/java/at/hannibal2/skyhanni/utils/ReflectionUtils.kt
@@ -0,0 +1,62 @@
+package at.hannibal2.skyhanni.utils
+
+import java.lang.reflect.Constructor
+import java.lang.reflect.Field
+import java.lang.reflect.Modifier
+import kotlin.properties.ReadWriteProperty
+import kotlin.reflect.KMutableProperty1
+import kotlin.reflect.KProperty
+import kotlin.reflect.KProperty0
+import kotlin.reflect.KProperty1
+import kotlin.reflect.full.isSubtypeOf
+import kotlin.reflect.full.memberProperties
+import kotlin.reflect.full.starProjectedType
+import kotlin.reflect.jvm.isAccessible
+
+object ReflectionUtils {
+
+ // TODO nea?
+// fun <T> dynamic(block: () -> KMutableProperty0<T>?): ReadWriteProperty<Any?, T?> {
+// return object : ReadWriteProperty<Any?, T?> {
+// override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
+// return block()?.get()
+// }
+//
+// override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
+// if (value != null)
+// block()?.set(value)
+// }
+// }
+// }
+
+ fun <T, R> dynamic(root: KProperty0<R?>, child: KMutableProperty1<R, T>) =
+ object : ReadWriteProperty<Any?, T?> {
+ override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
+ val rootObj = root.get() ?: return null
+ return child.get(rootObj)
+ }
+
+ override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
+ if (value == null) return
+ val rootObj = root.get() ?: return
+ child.set(rootObj, value)
+ }
+ }
+
+ inline fun <reified T : Any> Any.getPropertiesWithType() =
+ this::class.memberProperties
+ .filter { it.returnType.isSubtypeOf(T::class.starProjectedType) }
+ .map {
+ it.isAccessible = true
+ (it as KProperty1<Any, T>).get(this)
+ }
+
+ fun Field.makeAccessible() = also { isAccessible = true }
+
+ fun <T> Constructor<T>.makeAccessible() = also { isAccessible = true }
+
+ fun Field.removeFinal(): Field {
+ javaClass.getDeclaredField("modifiers").makeAccessible().set(this, modifiers and (Modifier.FINAL.inv()))
+ return this
+ }
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/RenderUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/RenderUtils.kt
index c85937309..7c26c03e2 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/RenderUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/RenderUtils.kt
@@ -309,7 +309,7 @@ object RenderUtils {
val z =
pos.z - player.lastTickPosZ + (pos.z - player.posZ - (pos.z - player.lastTickPosZ)) * partialTicks
- //7 – 25
+ // 7 – 25
val translate = LorenzVec(x, y, z)
val length = translate.length().toFloat()
@@ -467,7 +467,7 @@ object RenderUtils {
}
}
e.printStackTrace()
- LorenzUtils.debug("NPE in renderStringsAndItems!")
+ ChatUtils.debug("NPE in renderStringsAndItems!")
}
GuiEditManager.add(this, posLabel, longestX, offsetY)
}
@@ -665,7 +665,7 @@ object RenderUtils {
val distToPlayerSq =
(x - renderOffsetX) * (x - renderOffsetX) + (y - (renderOffsetY + eyeHeight)) * (y - (renderOffsetY + eyeHeight)) + (z - renderOffsetZ) * (z - renderOffsetZ)
var distToPlayer = sqrt(distToPlayerSq)
- //TODO this is optional maybe?
+ // TODO this is optional maybe?
distToPlayer = distToPlayer.coerceAtLeast(smallestDistanceVew)
if (distToPlayer < hideTooCloseAt) return
@@ -799,7 +799,7 @@ object RenderUtils {
val worldRenderer = tessellator.worldRenderer
GlStateManager.color(c.red / 255f, c.green / 255f, c.blue / 255f, c.alpha / 255f * alphaMultiplier)
- //vertical
+ // vertical
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
worldRenderer.pos(aabb.minX, aabb.minY, aabb.minZ).endVertex()
worldRenderer.pos(aabb.maxX, aabb.minY, aabb.minZ).endVertex()
@@ -819,7 +819,7 @@ object RenderUtils {
c.alpha / 255f * alphaMultiplier
)
- //x
+ // x
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
worldRenderer.pos(aabb.minX, aabb.minY, aabb.maxZ).endVertex()
worldRenderer.pos(aabb.minX, aabb.maxY, aabb.maxZ).endVertex()
@@ -838,7 +838,7 @@ object RenderUtils {
c.blue / 255f * 0.9f,
c.alpha / 255f * alphaMultiplier
)
- //z
+ // z
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
worldRenderer.pos(aabb.minX, aabb.maxY, aabb.minZ).endVertex()
worldRenderer.pos(aabb.maxX, aabb.maxY, aabb.minZ).endVertex()
@@ -865,7 +865,7 @@ object RenderUtils {
* If set to `false`, will be relativized to [RenderUtils.getViewerPos].
*/
renderRelativeToCamera: Boolean = false,
- drawVerticalBarriers: Boolean = true
+ drawVerticalBarriers: Boolean = true,
) {
drawFilledBoundingBox_nea(aabb, c, alphaMultiplier, renderRelativeToCamera, drawVerticalBarriers, partialTicks)
}
@@ -965,7 +965,7 @@ object RenderUtils {
val tessellator = Tessellator.getInstance()
val worldRenderer = tessellator.worldRenderer
- //vertical
+ // vertical
if (drawVerticalBarriers) {
GlStateManager.color(c.red / 255f, c.green / 255f, c.blue / 255f, c.alpha / 255f * alphaMultiplier)
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
@@ -990,7 +990,7 @@ object RenderUtils {
c.alpha / 255f * alphaMultiplier
)
- //x
+ // x
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
with(effectiveAABB) {
worldRenderer.pos(minX, minY, maxZ).endVertex()
@@ -1011,7 +1011,7 @@ object RenderUtils {
c.blue / 255f * 0.9f,
c.alpha / 255f * alphaMultiplier
)
- //z
+ // z
worldRenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION)
with(effectiveAABB) {
worldRenderer.pos(minX, maxY, minZ).endVertex()
@@ -1035,7 +1035,7 @@ object RenderUtils {
boundingBox: AxisAlignedBB,
lineWidth: Int,
colour: Color,
- depth: Boolean
+ depth: Boolean,
) {
val cornerOne = LorenzVec(boundingBox.minX, boundingBox.maxY, boundingBox.minZ)
val cornerTwo = LorenzVec(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ)
@@ -1049,7 +1049,7 @@ object RenderUtils {
// TODO nea please merge with 'draw3DLine'
fun LorenzRenderWorldEvent.draw3DLine_nea(
- p1: LorenzVec, p2: LorenzVec, color: Color, lineWidth: Int, depth: Boolean
+ p1: LorenzVec, p2: LorenzVec, color: Color, lineWidth: Int, depth: Boolean,
) {
GlStateManager.disableDepth()
GlStateManager.disableCull()
@@ -1094,7 +1094,7 @@ object RenderUtils {
offset: Float = 0f,
saturation: Float = 1F,
brightness: Float = 0.8F,
- timeOverride: Long = System.currentTimeMillis()
+ timeOverride: Long = System.currentTimeMillis(),
): Color {
return Color(
Color.HSBtoRGB(
@@ -1109,7 +1109,7 @@ object RenderUtils {
xPos: Int,
yPos: Int,
text: String,
- scale: Float
+ scale: Float,
) {
val fontRenderer = Minecraft.getMinecraft().fontRendererObj
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/Season.kt b/src/main/java/at/hannibal2/skyhanni/utils/Season.kt
index ef139c15c..33dd9a221 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/Season.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/Season.kt
@@ -23,7 +23,7 @@ enum class Season(
fun getCurrentSeason(): Season? = getSeasonByName(SkyBlockTime.now().monthName)
- private fun getSeasonByName(name: String): Season? = seasonPattern.matchMatcher(name) { entries.find { it.season.endsWith(group("season")) } }
+ private fun getSeasonByName(name: String): Season? =
+ seasonPattern.matchMatcher(name) { entries.find { it.season.endsWith(group("season")) } }
}
-
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/SimpleTimeMark.kt b/src/main/java/at/hannibal2/skyhanni/utils/SimpleTimeMark.kt
index 66629d11d..728a9f4ba 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/SimpleTimeMark.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/SimpleTimeMark.kt
@@ -36,6 +36,7 @@ value class SimpleTimeMark(private val millis: Long) : Comparable<SimpleTimeMark
fun toSkyBlockTime() = SkyBlockTime.fromInstant(Instant.ofEpochMilli(millis))
companion object {
+
fun now() = SimpleTimeMark(System.currentTimeMillis())
fun farPast() = SimpleTimeMark(0)
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/SkyBlockItemModifierUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/SkyBlockItemModifierUtils.kt
index d485e2c99..e4bc8b074 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/SkyBlockItemModifierUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/SkyBlockItemModifierUtils.kt
@@ -15,6 +15,7 @@ import net.minecraft.util.ResourceLocation
import java.util.Locale
object SkyBlockItemModifierUtils {
+
private val drillPartTypes = listOf("drill_part_upgrade_module", "drill_part_engine", "drill_part_fuel_tank")
fun ItemStack.getHotPotatoCount() = getAttributeInt("hot_potato_count")
@@ -225,7 +226,7 @@ object SkyBlockItemModifierUtils {
val quality = GemstoneQuality.getByName(value)
if (quality == null) {
- LorenzUtils.debug("Gemstone quality is null for item $name: ('$key' = '$value')")
+ ChatUtils.debug("Gemstone quality is null for item $name: ('$key' = '$value')")
continue
}
if (type != null) {
@@ -234,7 +235,7 @@ object SkyBlockItemModifierUtils {
val newKey = gemstones.getString(key + "_gem")
val newType = GemstoneType.getByName(newKey)
if (newType == null) {
- LorenzUtils.debug("Gemstone type is null for item $name: ('$newKey' with '$key' = '$value')")
+ ChatUtils.debug("Gemstone type is null for item $name: ('$newKey' with '$key' = '$value')")
continue
}
list.add(GemstoneSlot(newType, quality))
@@ -260,6 +261,7 @@ object SkyBlockItemModifierUtils {
fun ItemStack.getExtraAttributes() = tagCompound?.getCompoundTag("ExtraAttributes")
class GemstoneSlot(val type: GemstoneType, val quality: GemstoneQuality) {
+
fun getInternalName() = "${quality}_${type}_GEM".asInternalName()
}
@@ -272,6 +274,7 @@ object SkyBlockItemModifierUtils {
;
companion object {
+
fun getByName(name: String) = entries.firstOrNull { it.name == name }
}
}
@@ -288,6 +291,7 @@ object SkyBlockItemModifierUtils {
;
companion object {
+
fun getByName(name: String) = entries.firstOrNull { it.name == name }
}
}
@@ -309,6 +313,7 @@ object SkyBlockItemModifierUtils {
;
companion object {
+
fun getColorCode(name: String) = entries.stream().filter {
name.uppercase(Locale.ENGLISH).contains(it.name)
}.findFirst().get().colorCode
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt
index c9892a9bf..42ca4ee00 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/SoundUtils.kt
@@ -7,6 +7,7 @@ import net.minecraft.client.audio.SoundCategory
import net.minecraft.util.ResourceLocation
object SoundUtils {
+
private val beepSound by lazy { createSound("random.orb", 1f) }
private val clickSound by lazy { createSound("gui.button.press", 1f) }
private val errorSound by lazy { createSound("mob.endermen.portal", 0f) }
@@ -58,7 +59,7 @@ object SoundUtils {
fun command(args: Array<String>) {
if (args.isEmpty()) {
- LorenzUtils.userError("Specify a sound effect to test")
+ ChatUtils.userError("Specify a sound effect to test")
return
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/StringUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/StringUtils.kt
index 11b843b64..10c2eebfd 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/StringUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/StringUtils.kt
@@ -16,6 +16,7 @@ import java.util.regex.Matcher
import java.util.regex.Pattern
object StringUtils {
+
// TODO USE SH-REPO
private val playerChatPattern = "(?<important>.*?)(?:§[f7r])*: .*".toPattern()
private val chatUsernamePattern =
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/TabListData.kt b/src/main/java/at/hannibal2/skyhanni/utils/TabListData.kt
index fe07509be..4fd442c09 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/TabListData.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/TabListData.kt
@@ -5,8 +5,8 @@ import at.hannibal2.skyhanni.events.LorenzTickEvent
import at.hannibal2.skyhanni.events.TabListUpdateEvent
import at.hannibal2.skyhanni.mixins.hooks.tabListGuard
import at.hannibal2.skyhanni.mixins.transformers.AccessorGuiPlayerTabOverlay
-import at.hannibal2.skyhanni.utils.LorenzUtils.conditionalTransform
-import at.hannibal2.skyhanni.utils.LorenzUtils.transformIf
+import at.hannibal2.skyhanni.utils.ConditionalUtils.conditionalTransform
+import at.hannibal2.skyhanni.utils.ConditionalUtils.transformIf
import at.hannibal2.skyhanni.utils.StringUtils.removeColor
import com.google.common.collect.ComparisonChain
import com.google.common.collect.Ordering
@@ -21,6 +21,7 @@ import net.minecraftforge.fml.relauncher.SideOnly
class TabListData {
companion object {
+
private var cache = emptyList<String>()
private var debugCache: List<String>? = null
@@ -29,20 +30,20 @@ class TabListData {
fun toggleDebugCommand() {
if (debugCache != null) {
- LorenzUtils.chat("Disabled tab list debug.")
+ ChatUtils.chat("Disabled tab list debug.")
debugCache = null
return
}
SkyHanniMod.coroutineScope.launch {
val clipboard = OSUtils.readFromClipboard() ?: return@launch
debugCache = clipboard.lines()
- LorenzUtils.chat("Enabled tab list debug with your clipboard.")
+ ChatUtils.chat("Enabled tab list debug with your clipboard.")
}
}
fun copyCommand(args: Array<String>) {
if (debugCache != null) {
- LorenzUtils.clickableChat("Tab list debug is enabled!", "shdebugtablist")
+ ChatUtils.clickableChat("Tab list debug is enabled!", "shdebugtablist")
return
}
@@ -53,11 +54,13 @@ class TabListData {
if (tabListLine != "") resultList.add("'$tabListLine'")
}
val tabList = Minecraft.getMinecraft().ingameGUI.tabList as AccessorGuiPlayerTabOverlay
- val tabHeader = tabList.header_skyhanni.conditionalTransform(noColor, { unformattedText }, { formattedText })
- val tabFooter = tabList.footer_skyhanni.conditionalTransform(noColor, { unformattedText }, { formattedText })
+ val tabHeader =
+ tabList.header_skyhanni.conditionalTransform(noColor, { unformattedText }, { formattedText })
+ val tabFooter =
+ tabList.footer_skyhanni.conditionalTransform(noColor, { unformattedText }, { formattedText })
val string = "Header:\n\n$tabHeader\n\nBody:\n\n${resultList.joinToString("\n")}\n\nFooter:\n\n$tabFooter"
OSUtils.copyToClipboard(string)
- LorenzUtils.chat("Tab list copied into the clipboard!")
+ ChatUtils.chat("Tab list copied into the clipboard!")
}
}
@@ -65,6 +68,7 @@ class TabListData {
@SideOnly(Side.CLIENT)
internal class PlayerComparator : Comparator<NetworkPlayerInfo> {
+
override fun compare(o1: NetworkPlayerInfo, o2: NetworkPlayerInfo): Int {
val team1 = o1.playerTeam
val team2 = o2.playerTeam
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/TimeMark.kt b/src/main/java/at/hannibal2/skyhanni/utils/TimeMark.kt
index 83285550d..be5f59322 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/TimeMark.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/TimeMark.kt
@@ -3,14 +3,14 @@ package at.hannibal2.skyhanni.utils
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
-
data class TimeMark(val long: Long) {
fun hasNeverHappened() = long == 0L
fun passedTime() = if (long == 0L) Duration.Companion.INFINITE else (System.currentTimeMillis() - long).milliseconds
companion object {
+
fun never() = TimeMark(0)
fun now() = TimeMark(System.currentTimeMillis())
}
-} \ No newline at end of file
+}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/TimeUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/TimeUtils.kt
index e8175cb6d..43af202a8 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/TimeUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/TimeUtils.kt
@@ -6,12 +6,14 @@ import io.github.moulberry.notenoughupdates.util.SkyBlockTime
import java.time.LocalDate
import java.time.ZoneId
import kotlin.time.Duration
+import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.DurationUnit
import kotlin.time.toDuration
object TimeUtils {
+
private val pattern =
"(?:(?<y>\\d+) ?y(?:\\w* ?)?)?(?:(?<d>\\d+) ?d(?:\\w* ?)?)?(?:(?<h>\\d+) ?h(?:\\w* ?)?)?(?:(?<m>\\d+) ?m(?:\\w* ?)?)?(?:(?<s>\\d+) ?s(?:\\w* ?)?)?".toPattern()
@@ -19,7 +21,7 @@ object TimeUtils {
biggestUnit: TimeUnit = TimeUnit.YEAR,
showMilliSeconds: Boolean = false,
longName: Boolean = false,
- maxUnits: Int = -1
+ maxUnits: Int = -1,
): String = formatDuration(
inWholeMilliseconds - 999, biggestUnit, showMilliSeconds, longName, maxUnits
)
@@ -37,7 +39,7 @@ object TimeUtils {
biggestUnit: TimeUnit = TimeUnit.YEAR,
showMilliSeconds: Boolean = false,
longName: Boolean = false,
- maxUnits: Int = -1
+ maxUnits: Int = -1,
): String {
// TODO: if this weird offset gets removed, also remove that subtraction from formatDuration(kotlin.time.Duration)
var milliseconds = millis + 999
@@ -143,6 +145,9 @@ object TimeUtils {
}
fun getCurrentLocalDate(): LocalDate = LocalDate.now(ZoneId.of("UTC"))
+
+ val Long.ticks get() = (this * 50).milliseconds
+ val Int.ticks get() = (this * 50).milliseconds
}
private const val FACTOR_SECONDS = 1000L
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/Timer.kt b/src/main/java/at/hannibal2/skyhanni/utils/Timer.kt
index 2a6d1f5ab..60f13a089 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/Timer.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/Timer.kt
@@ -10,7 +10,7 @@ class Timer(
@Expose
private var started: SimpleTimeMark = SimpleTimeMark.now(),
- startPaused: Boolean = false
+ startPaused: Boolean = false,
) : Comparable<Timer> {
@Expose
@@ -39,5 +39,4 @@ class Timer(
}
override fun compareTo(other: Timer): Int = remaining.compareTo(other.remaining)
-
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/UtilsPatterns.kt b/src/main/java/at/hannibal2/skyhanni/utils/UtilsPatterns.kt
index b381ddf1c..014a1ad54 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/UtilsPatterns.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/UtilsPatterns.kt
@@ -18,7 +18,9 @@ object UtilsPatterns {
**/
val rarityLoreLinePattern by patternGroup.pattern(
"item.lore.rarity.line",
- "^(?:§.){2,3}(?:.§. (?:§.){4})?(?:SHINY )?(?<rarity>${enumJoinToPattern<LorenzRarity> { it.name.replace("_", " ") }}) ?(?:DUNGEON )?(?<itemCategory>[^§]*)(?: (?:§.){3}.)?$"
+ "^(?:§.){2,3}(?:.§. (?:§.){4})?(?:SHINY )?(?<rarity>" +
+ enumJoinToPattern<LorenzRarity> { it.name.replace("_", " ") } +
+ ") ?(?:DUNGEON )?(?<itemCategory>[^§]*)(?: (?:§.){3}.)?$"
)
val abiPhonePattern by patternGroup.pattern(
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/renderables/RenderLineTooltips.kt b/src/main/java/at/hannibal2/skyhanni/utils/renderables/RenderLineTooltips.kt
index 9cb7457ff..ec39dc7af 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/renderables/RenderLineTooltips.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/renderables/RenderLineTooltips.kt
@@ -16,7 +16,7 @@ object RenderLineTooltips {
fun drawHoveringText(
posX: Int, posY: Int, tips: List<String?>, stack: ItemStack? = null,
mouseX: Int = Utils.getMouseX(),
- mouseY: Int = Utils.getMouseY()
+ mouseY: Int = Utils.getMouseY(),
) {
if (tips.isNotEmpty()) {
var textLines = tips
@@ -198,7 +198,7 @@ object RenderLineTooltips {
right: Int,
bottom: Int,
startColor: Int,
- endColor: Int
+ endColor: Int,
) {
val startAlpha = (startColor shr 24 and 255).toFloat() / 255.0f
val startRed = (startColor shr 16 and 255).toFloat() / 255.0f
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/renderables/Renderable.kt b/src/main/java/at/hannibal2/skyhanni/utils/renderables/Renderable.kt
index 68b29e2fc..933b61d38 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/renderables/Renderable.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/renderables/Renderable.kt
@@ -18,6 +18,7 @@ import java.util.Collections
import kotlin.math.max
interface Renderable {
+
val width: Int
val height: Int
@@ -35,6 +36,7 @@ interface Renderable {
fun render(posX: Int, posY: Int)
companion object {
+
val logger = LorenzLogger("debug/renderable")
val list = mutableMapOf<Pair<Int, Int>, List<Int>>()
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPattern.kt b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPattern.kt
index 6af2cf2fe..715c907e4 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPattern.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPattern.kt
@@ -42,6 +42,7 @@ import kotlin.reflect.KProperty
* of slightly more options.
*/
interface RepoPattern : ReadOnlyProperty<Any?, Pattern> {
+
/**
* Check whether [value] has been loaded remotely or from the fallback value at [defaultPattern]. In case this is
* accessed off-thread there are no guarantees for the correctness of this value in relation to any specific call
@@ -78,8 +79,8 @@ interface RepoPattern : ReadOnlyProperty<Any?, Pattern> {
return value
}
-
companion object {
+
/**
* Obtain a reference to a [Pattern] backed by either a local regex, or a remote regex.
* Check the documentation of [RepoPattern] for more information.
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGroup.kt b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGroup.kt
index 326f447d5..1b00e4d83 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGroup.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGroup.kt
@@ -6,6 +6,7 @@ import org.intellij.lang.annotations.Language
* A utility class for allowing easier definitions of [RepoPattern]s with a common prefix.
*/
class RepoPatternGroup internal constructor(val prefix: String) {
+
init {
RepoPatternManager.verifyKeyShape(prefix)
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGui.kt b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGui.kt
index 2a2393686..efc41bffa 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGui.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternGui.kt
@@ -12,7 +12,9 @@ import io.github.moulberry.moulconfig.xml.XMLUniverse
* Gui for analyzing [RepoPattern]s
*/
class RepoPatternGui private constructor() {
+
companion object {
+
/**
* Open the [RepoPatternGui]
*/
@@ -34,10 +36,10 @@ class RepoPatternGui private constructor() {
.map { RepoPatternInfo(it) }
private var searchCache = ObservableList(mutableListOf<RepoPatternInfo>())
-
class RepoPatternInfo(
- repoPatternImpl: RepoPatternImpl
+ repoPatternImpl: RepoPatternImpl,
) {
+
@field:Bind
val key: String = repoPatternImpl.key
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternImpl.kt b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternImpl.kt
index 89e9f99ec..1116bbf76 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternImpl.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternImpl.kt
@@ -10,6 +10,7 @@ class RepoPatternImpl(
override val defaultPattern: String,
override val key: String,
) : RepoPattern {
+
var compiledPattern: Pattern = Pattern.compile(defaultPattern)
var wasLoadedRemotely = false
override var wasOverridden = false
@@ -37,7 +38,6 @@ class RepoPatternImpl(
RepoPatternManager.checkExclusivity(owner, key)
}
-
override val value: Pattern
get() {
return compiledPattern
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternManager.kt b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternManager.kt
index a0bc09da7..3e32cbcb9 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternManager.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/repopatterns/RepoPatternManager.kt
@@ -6,7 +6,7 @@ import at.hannibal2.skyhanni.events.ConfigLoadEvent
import at.hannibal2.skyhanni.events.LorenzEvent
import at.hannibal2.skyhanni.events.PreInitFinishedEvent
import at.hannibal2.skyhanni.events.RepositoryReloadEvent
-import at.hannibal2.skyhanni.utils.LorenzUtils.afterChange
+import at.hannibal2.skyhanni.utils.ConditionalUtils.afterChange
import at.hannibal2.skyhanni.utils.StringUtils.matches
import net.minecraft.launchwrapper.Launch
import net.minecraftforge.fml.common.FMLCommonHandler
@@ -19,6 +19,7 @@ import java.util.regex.PatternSyntaxException
* Manages [RepoPattern]s.
*/
object RepoPatternManager {
+
val allPatterns: Collection<RepoPatternImpl> get() = usedKeys.values
/**
@@ -77,7 +78,6 @@ object RepoPatternManager {
reloadPatterns()
}
-
@SubscribeEvent
fun onConfigInit(event: ConfigLoadEvent) {
config.forceLocal.afterChange { reloadPatterns() }
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderHelper.kt b/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderHelper.kt
index 2576b4248..6f24d0e89 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderHelper.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderHelper.kt
@@ -17,7 +17,9 @@ import org.lwjgl.opengl.GLContext
* Credit: [ShaderHelper.java](https://github.com/BiscuitDevelopment/SkyblockAddons/blob/main/src/main/java/codes/biscuit/skyblockaddons/shader/ShaderHelper.java)
*/
class ShaderHelper {
+
companion object {
+
private var SHADERS_SUPPORTED: Boolean
private var USING_ARB_SHADERS: Boolean
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderManager.kt b/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderManager.kt
index 3dbec3c6e..6df5c92f8 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderManager.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/shader/ShaderManager.kt
@@ -18,9 +18,11 @@ object ShaderManager {
* in the when expression
*/
enum class Shaders(val shader: Shader) {
+
CHROMA(ChromaShader.INSTANCE);
companion object {
+
fun getShaderInstance(shaderName: String): Shader? = when (shaderName) {
"chroma" -> CHROMA.shader
else -> {
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/shader/Uniform.kt b/src/main/java/at/hannibal2/skyhanni/utils/shader/Uniform.kt
index d57398ea4..c9602d423 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/shader/Uniform.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/shader/Uniform.kt
@@ -1,6 +1,6 @@
package at.hannibal2.skyhanni.utils.shader
-import java.util.*
+import java.util.Objects
import java.util.function.Supplier
/**
@@ -14,11 +14,12 @@ class Uniform<T>(
shader: Shader,
private val uniformType: UniformType<T>,
val name: String,
- private val uniformValuesSupplier: Supplier<T>
+ private val uniformValuesSupplier: Supplier<T>,
) {
class UniformType<T> {
companion object {
+
val FLOAT: UniformType<Float> = UniformType()
val VEC3: UniformType<FloatArray> = UniformType()
val BOOL: UniformType<Boolean> = UniformType()
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/tracker/ItemTrackerData.kt b/src/main/java/at/hannibal2/skyhanni/utils/tracker/ItemTrackerData.kt
index 7aa2cf4f9..8aeec5f32 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/tracker/ItemTrackerData.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/tracker/ItemTrackerData.kt
@@ -36,6 +36,7 @@ abstract class ItemTrackerData : TrackerData() {
var items: MutableMap<NEUInternalName, TrackedItem> = HashMap()
class TrackedItem {
+
@Expose
var internalName: NEUInternalName? = null
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniItemTracker.kt b/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniItemTracker.kt
index b831ade3f..ce10ecbee 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniItemTracker.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniItemTracker.kt
@@ -5,12 +5,13 @@ import at.hannibal2.skyhanni.config.Storage
import at.hannibal2.skyhanni.config.features.misc.TrackerConfig.PriceFromEntry
import at.hannibal2.skyhanni.data.SlayerAPI
import at.hannibal2.skyhanni.test.PriceSource
+import at.hannibal2.skyhanni.utils.ChatUtils
+import at.hannibal2.skyhanni.utils.CollectionUtils.addAsSingletonList
+import at.hannibal2.skyhanni.utils.CollectionUtils.sortedDesc
import at.hannibal2.skyhanni.utils.ItemUtils.getNameWithEnchantment
import at.hannibal2.skyhanni.utils.KeyboardManager
import at.hannibal2.skyhanni.utils.LorenzUtils
-import at.hannibal2.skyhanni.utils.LorenzUtils.addAsSingletonList
import at.hannibal2.skyhanni.utils.LorenzUtils.addSelector
-import at.hannibal2.skyhanni.utils.LorenzUtils.sortedDesc
import at.hannibal2.skyhanni.utils.NEUInternalName
import at.hannibal2.skyhanni.utils.NEUInternalName.Companion.asInternalName
import at.hannibal2.skyhanni.utils.NumberUtil
@@ -27,6 +28,7 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
) : SkyHanniTracker<Data>(name, createNewSession, getStorage, drawDisplay) {
companion object {
+
val SKYBLOCK_COIN by lazy { "SKYBLOCK_COIN".asInternalName() }
}
@@ -47,7 +49,7 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
val (itemName, price) = SlayerAPI.getItemNameAndPrice(internalName, amount)
if (config.warnings.chat && price >= config.warnings.minimumChat) {
- LorenzUtils.chat("§a+Tracker Drop§7: §r$itemName")
+ ChatUtils.chat("§a+Tracker Drop§7: §r$itemName")
}
if (config.warnings.title && price >= config.warnings.minimumTitle) {
LorenzUtils.sendTitle("§a+ $itemName", 5.seconds)
@@ -71,7 +73,7 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
fun drawItems(
data: Data,
filter: (NEUInternalName) -> Boolean,
- lists: MutableList<List<Any>>
+ lists: MutableList<List<Any>>,
): Double {
var profit = 0.0
val items = mutableMapOf<Renderable, Long>()
@@ -106,7 +108,7 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
if (System.currentTimeMillis() > lastClickDelay + 150) {
if (KeyboardManager.isModifierKeyDown()) {
data.items.remove(internalName)
- LorenzUtils.chat("Removed $cleanName §efrom $name.")
+ ChatUtils.chat("Removed $cleanName §efrom $name.")
lastClickDelay = System.currentTimeMillis() + 500
} else {
modify {
@@ -152,7 +154,7 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
item: ItemTrackerData.TrackedItem,
hidden: Boolean,
newDrop: Boolean,
- internalName: NEUInternalName
+ internalName: NEUInternalName,
) = buildList {
if (internalName == SKYBLOCK_COIN) {
addAll(data.getCoinDescription(item))
@@ -185,5 +187,4 @@ class SkyHanniItemTracker<Data : ItemTrackerData>(
val text = "§eTotal Profit: $profitPrefix$profitFormat coins"
return Renderable.hoverTips(text, tips)
}
-
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniTracker.kt b/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniTracker.kt
index 4a78641ef..b4f7bfef0 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniTracker.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/tracker/SkyHanniTracker.kt
@@ -8,8 +8,9 @@ import at.hannibal2.skyhanni.data.ProfileStorageData
import at.hannibal2.skyhanni.data.TrackerManager
import at.hannibal2.skyhanni.features.bazaar.BazaarApi.Companion.getBazaarData
import at.hannibal2.skyhanni.features.misc.items.EstimatedItemValue
+import at.hannibal2.skyhanni.utils.ChatUtils
+import at.hannibal2.skyhanni.utils.CollectionUtils.addAsSingletonList
import at.hannibal2.skyhanni.utils.LorenzUtils
-import at.hannibal2.skyhanni.utils.LorenzUtils.addAsSingletonList
import at.hannibal2.skyhanni.utils.NEUInternalName
import at.hannibal2.skyhanni.utils.NEUItems.getNpcPriceOrNull
import at.hannibal2.skyhanni.utils.NEUItems.getPriceOrNull
@@ -26,6 +27,7 @@ open class SkyHanniTracker<Data : TrackerData>(
private val getStorage: (Storage.ProfileSpecific) -> Data,
private val drawDisplay: (Data) -> List<List<Any>>,
) {
+
private var inventoryOpen = false
private var displayMode: DisplayMode? = null
private val currentSessions = mutableMapOf<Storage.ProfileSpecific, Data>()
@@ -34,6 +36,7 @@ open class SkyHanniTracker<Data : TrackerData>(
private var dirty = false
companion object {
+
val config get() = SkyHanniMod.feature.misc.tracker
private val storedTrackers get() = SkyHanniMod.feature.storage.trackerDisplayModes
@@ -53,7 +56,7 @@ open class SkyHanniTracker<Data : TrackerData>(
return
}
- LorenzUtils.clickableChat(
+ ChatUtils.clickableChat(
"Are you sure you want to reset your total $name? Click here to confirm.",
"$command confirm"
)
@@ -145,7 +148,7 @@ open class SkyHanniTracker<Data : TrackerData>(
private fun reset(displayMode: DisplayMode, message: String) {
getSharedTracker()?.let {
it.get(displayMode).reset()
- LorenzUtils.chat(message)
+ ChatUtils.chat(message)
update()
}
}
@@ -163,6 +166,7 @@ open class SkyHanniTracker<Data : TrackerData>(
}
class SharedTracker<Data : TrackerData>(private val total: Data, private val currentSession: Data) {
+
fun modify(modifyFunction: (Data) -> Unit) {
modifyFunction(total)
modifyFunction(currentSession)
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/tracker/TrackerData.kt b/src/main/java/at/hannibal2/skyhanni/utils/tracker/TrackerData.kt
index 3c4a8bbd0..24f417850 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/tracker/TrackerData.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/tracker/TrackerData.kt
@@ -1,5 +1,6 @@
package at.hannibal2.skyhanni.utils.tracker
abstract class TrackerData {
+
abstract fun reset()
}