diff options
author | nea <romangraef@gmail.com> | 2022-09-28 12:45:56 +0200 |
---|---|---|
committer | nea <romangraef@gmail.com> | 2022-09-28 12:45:56 +0200 |
commit | 4d73331a449f0b0647066f7dde0628730fe0e178 (patch) | |
tree | 047f463e13d14ea6cf9c8b37602a756f6880f9a0 /src/main/kotlin/moe/nea/notenoughupdates/util | |
parent | ec66c82198fe2d61d699d553c1254f08b43fcc65 (diff) | |
download | Firmament-4d73331a449f0b0647066f7dde0628730fe0e178.tar.gz Firmament-4d73331a449f0b0647066f7dde0628730fe0e178.tar.bz2 Firmament-4d73331a449f0b0647066f7dde0628730fe0e178.zip |
Fairy souls
Diffstat (limited to 'src/main/kotlin/moe/nea/notenoughupdates/util')
9 files changed, 455 insertions, 131 deletions
diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/ConfigHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/ConfigHolder.kt deleted file mode 100644 index 50a3d9b..0000000 --- a/src/main/kotlin/moe/nea/notenoughupdates/util/ConfigHolder.kt +++ /dev/null @@ -1,131 +0,0 @@ -package moe.nea.notenoughupdates.util - -import java.io.IOException -import java.nio.file.Path -import java.util.concurrent.CopyOnWriteArrayList -import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents -import kotlinx.serialization.KSerializer -import kotlinx.serialization.SerializationException -import kotlin.io.path.exists -import kotlin.io.path.readText -import kotlin.io.path.writeText -import kotlin.reflect.KClass -import net.minecraft.client.MinecraftClient -import net.minecraft.server.command.CommandOutput -import net.minecraft.text.Text -import moe.nea.notenoughupdates.NotEnoughUpdates -import moe.nea.notenoughupdates.events.ScreenOpenEvent - -abstract class ConfigHolder<T>( - val serializer: KSerializer<T>, - val name: String, - val default: () -> T -) { - - var config: T - private set - - init { - config = readValueOrDefault() - putConfig(this::class, this) - } - - val file: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("$name.json") - - protected fun readValueOrDefault(): T { - if (file.exists()) - try { - return NotEnoughUpdates.json.decodeFromString( - serializer, - file.readText() - ) - } catch (e: IOException) { - badLoads.add(name) - NotEnoughUpdates.logger.error( - "IO exception during loading of config file $name. This will reset this config.", - e - ) - } catch (e: SerializationException) { - badLoads.add(name) - NotEnoughUpdates.logger.error( - "Serialization exception during loading of config file $name. This will reset this config.", - e - ) - } - return default() - } - - private fun writeValue(t: T) { - file.writeText(NotEnoughUpdates.json.encodeToString(serializer, t)) - } - - fun save() { - writeValue(config) - } - - fun load() { - config = readValueOrDefault() - } - - fun markDirty() { - Companion.markDirty(this::class) - } - - companion object { - private var badLoads: MutableList<String> = CopyOnWriteArrayList() - private val allConfigs: MutableMap<KClass<out ConfigHolder<*>>, ConfigHolder<*>> = mutableMapOf() - private val dirty: MutableSet<KClass<out ConfigHolder<*>>> = mutableSetOf() - - private fun <T : ConfigHolder<K>, K> putConfig(kClass: KClass<T>, inst: ConfigHolder<K>) { - allConfigs[kClass] = inst - } - - fun <T : ConfigHolder<K>, K> markDirty(kClass: KClass<T>) { - if (kClass !in allConfigs) { - NotEnoughUpdates.logger.error("Tried to markDirty '${kClass.qualifiedName}', which isn't registered as 'ConfigHolder'") - return - } - dirty.add(kClass) - } - - private fun performSaves() { - val toSave = dirty.toList().also { - dirty.clear() - } - for (it in toSave) { - val obj = allConfigs[it] - if (obj == null) { - NotEnoughUpdates.logger.error("Tried to save '${it}', which isn't registered as 'ConfigHolder'") - continue - } - obj.save() - } - } - - private fun warnForResetConfigs(player: CommandOutput) { - if (badLoads.isNotEmpty()) { - player.sendMessage( - Text.literal( - "The following configs have been reset: ${badLoads.joinToString(", ")}. " + - "This can be intentional, but probably isn't." - ) - ) - badLoads.clear() - } - } - - fun registerEvents() { - ScreenOpenEvent.subscribe { event -> - performSaves() - val p = MinecraftClient.getInstance().player - if (p != null) { - warnForResetConfigs(p) - } - } - ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { - performSaves() - }) - } - - } -} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt new file mode 100644 index 0000000..400842f --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/Locraw.kt @@ -0,0 +1,8 @@ +package moe.nea.notenoughupdates.util + +import kotlinx.serialization.Serializable + +@Serializable +data class Locraw(val server: String, val gametype: String? = null, val mode: String? = null, val map: String? = null) { + val skyblockLocation = if (gametype == "SKYBLOCK") mode else null +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt new file mode 100644 index 0000000..da06c68 --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/MC.kt @@ -0,0 +1,7 @@ +package moe.nea.notenoughupdates.util + +import net.minecraft.client.MinecraftClient + +object MC { + inline val player get() = MinecraftClient.getInstance().player +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt new file mode 100644 index 0000000..5391206 --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/SBData.kt @@ -0,0 +1,63 @@ +package moe.nea.notenoughupdates.util + +import dev.architectury.event.events.client.ClientPlayerEvent +import kotlinx.serialization.SerializationException +import kotlinx.serialization.decodeFromString +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds +import kotlin.time.ExperimentalTime +import kotlin.time.TimeSource +import moe.nea.notenoughupdates.NotEnoughUpdates +import moe.nea.notenoughupdates.events.ServerChatLineReceivedEvent +import moe.nea.notenoughupdates.events.SkyblockServerUpdateEvent + +@OptIn(ExperimentalTime::class) +object SBData { + val profileRegex = "(?:Your profile was changed to: |You are playing on profile: )(.+)".toRegex() + var profileCuteName: String? = null + + private var lastLocrawSent: TimeSource.Monotonic.ValueTimeMark? = null + private val locrawRoundtripTime: Duration = 5.seconds + var locraw: Locraw? = null + val skyblockLocation get() = locraw?.skyblockLocation + + + fun init() { + ServerChatLineReceivedEvent.subscribe { event -> + val profileMatch = profileRegex.matchEntire(event.unformattedString) + if (profileMatch != null) { + profileCuteName = profileMatch.groupValues[1] + } + if (event.unformattedString.startsWith("{")) { + val lLS = lastLocrawSent + if (tryReceiveLocraw(event.unformattedString) && lLS != null && lLS.elapsedNow() < locrawRoundtripTime) { + lastLocrawSent = null + event.cancel() + } + } + } + + ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ClientPlayerEvent.ClientPlayerJoin { + locraw = null + sendLocraw() + }) + } + + private fun tryReceiveLocraw(unformattedString: String): Boolean = try { + val lastLocraw = locraw + locraw = NotEnoughUpdates.json.decodeFromString<Locraw>(unformattedString) + SkyblockServerUpdateEvent.publish(SkyblockServerUpdateEvent(lastLocraw, locraw)) + true + } catch (e: SerializationException) { + false + } catch (e: IllegalArgumentException) { + false + } + + fun sendLocraw() { + lastLocrawSent = TimeSource.Monotonic.markNow() + MC.player?.sendCommand("locraw") + } + + +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/config/ConfigHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/config/ConfigHolder.kt new file mode 100644 index 0000000..e8a9649 --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/config/ConfigHolder.kt @@ -0,0 +1,60 @@ +package moe.nea.notenoughupdates.util.config + +import java.nio.file.Path +import kotlinx.serialization.KSerializer +import kotlin.io.path.exists +import kotlin.io.path.readText +import kotlin.io.path.writeText +import moe.nea.notenoughupdates.NotEnoughUpdates + +abstract class ConfigHolder<T>( + val serializer: KSerializer<T>, + val name: String, + val default: () -> T +) : IConfigHolder<T> { + + + final override var config: T + private set + + init { + config = readValueOrDefault() + IConfigHolder.putConfig(this::class, this) + } + + private val file: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("$name.json") + + protected fun readValueOrDefault(): T { + if (file.exists()) + try { + return NotEnoughUpdates.json.decodeFromString( + serializer, + file.readText() + ) + } catch (e: Exception) {/* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ + IConfigHolder.badLoads.add(name) + NotEnoughUpdates.logger.error( + "Exception during loading of config file $name. This will reset this config.", + e + ) + } + return default() + } + + private fun writeValue(t: T) { + file.writeText(NotEnoughUpdates.json.encodeToString(serializer, t)) + } + + override fun save() { + writeValue(config) + } + + override fun load() { + config = readValueOrDefault() + } + + override fun markDirty() { + IConfigHolder.markDirty(this::class) + } + +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/config/IConfigHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/config/IConfigHolder.kt new file mode 100644 index 0000000..2acc99d --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/config/IConfigHolder.kt @@ -0,0 +1,75 @@ +package moe.nea.notenoughupdates.util.config + +import java.util.concurrent.CopyOnWriteArrayList +import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents +import kotlin.reflect.KClass +import net.minecraft.client.MinecraftClient +import net.minecraft.server.command.CommandOutput +import net.minecraft.text.Text +import moe.nea.notenoughupdates.NotEnoughUpdates +import moe.nea.notenoughupdates.events.ScreenOpenEvent + +interface IConfigHolder<T> { + companion object { + internal var badLoads: MutableList<String> = CopyOnWriteArrayList() + private val allConfigs: MutableMap<KClass<out IConfigHolder<*>>, IConfigHolder<*>> = mutableMapOf() + private val dirty: MutableSet<KClass<out IConfigHolder<*>>> = mutableSetOf() + + internal fun <T : IConfigHolder<K>, K> putConfig(kClass: KClass<T>, inst: IConfigHolder<K>) { + allConfigs[kClass] = inst + } + + fun <T : IConfigHolder<K>, K> markDirty(kClass: KClass<T>) { + if (kClass !in allConfigs) { + NotEnoughUpdates.logger.error("Tried to markDirty '${kClass.qualifiedName}', which isn't registered as 'IConfigHolder'") + return + } + dirty.add(kClass) + } + + private fun performSaves() { + val toSave = dirty.toList().also { + dirty.clear() + } + for (it in toSave) { + val obj = allConfigs[it] + if (obj == null) { + NotEnoughUpdates.logger.error("Tried to save '${it}', which isn't registered as 'ConfigHolder'") + continue + } + obj.save() + } + } + + private fun warnForResetConfigs(player: CommandOutput) { + if (badLoads.isNotEmpty()) { + player.sendMessage( + Text.literal( + "The following configs have been reset: ${badLoads.joinToString(", ")}. " + + "This can be intentional, but probably isn't." + ) + ) + badLoads.clear() + } + } + + fun registerEvents() { + ScreenOpenEvent.subscribe { event -> + performSaves() + val p = MinecraftClient.getInstance().player + if (p != null) { + warnForResetConfigs(p) + } + } + ClientLifecycleEvents.CLIENT_STOPPING.register(ClientLifecycleEvents.ClientStopping { + performSaves() + }) + } + + } + + val config: T + fun save() + fun markDirty() + fun load() +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/config/ProfileSpecificConfigHolder.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/config/ProfileSpecificConfigHolder.kt new file mode 100644 index 0000000..44a79c4 --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/config/ProfileSpecificConfigHolder.kt @@ -0,0 +1,81 @@ +package moe.nea.notenoughupdates.util.config + +import java.nio.file.Path +import kotlinx.serialization.KSerializer +import kotlin.io.path.createDirectories +import kotlin.io.path.deleteExisting +import kotlin.io.path.exists +import kotlin.io.path.extension +import kotlin.io.path.listDirectoryEntries +import kotlin.io.path.nameWithoutExtension +import kotlin.io.path.readText +import kotlin.io.path.writeText +import moe.nea.notenoughupdates.NotEnoughUpdates +import moe.nea.notenoughupdates.util.SBData + +abstract class ProfileSpecificConfigHolder<S>( + private val configSerializer: KSerializer<S>, + val configName: String, + private val configDefault: () -> S +) : IConfigHolder<S?> { + + var allConfigs: MutableMap<String, S> + + override val config: S? + get() = SBData.profileCuteName?.let { + allConfigs.computeIfAbsent(it) { configDefault() } + } + + init { + allConfigs = readValues() + readValues() + } + + private val configDirectory: Path get() = NotEnoughUpdates.CONFIG_DIR.resolve("profiles") + + private fun readValues(): MutableMap<String, S> { + if (!configDirectory.exists()) { + configDirectory.createDirectories() + } + val profileFiles = configDirectory.listDirectoryEntries() + return profileFiles + .filter { it.extension == "json" } + .mapNotNull { + try { + it.nameWithoutExtension to NotEnoughUpdates.json.decodeFromString(configSerializer, it.readText()) + } catch (e: Exception) { /* Expecting IOException and SerializationException, but Kotlin doesn't allow multi catches*/ + IConfigHolder.badLoads.add(configName) + NotEnoughUpdates.logger.error( + "Exception during loading of profile specific config file $it ($configName). This will reset that profiles config.", + e + ) + null + } + }.toMap().toMutableMap() + } + + override fun save() { + if (!configDirectory.exists()) { + configDirectory.createDirectories() + } + val c = allConfigs + configDirectory.listDirectoryEntries().forEach { + if (it.nameWithoutExtension !in c) { + it.deleteExisting() + } + } + c.forEach { (name, value) -> + val f = configDirectory.resolve("$name.json") + f.writeText(NotEnoughUpdates.json.encodeToString(configSerializer, value)) + } + } + + override fun markDirty() { + IConfigHolder.markDirty(this::class) + } + + override fun load() { + allConfigs = readValues() + } + +} diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt new file mode 100644 index 0000000..9b5432a --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/render/block.kt @@ -0,0 +1,91 @@ +package moe.nea.notenoughupdates.util.render + +import com.mojang.blaze3d.systems.RenderSystem +import net.minecraft.client.gl.VertexBuffer +import net.minecraft.client.render.BufferBuilder +import net.minecraft.client.render.Camera +import net.minecraft.client.render.GameRenderer +import net.minecraft.client.render.Tessellator +import net.minecraft.client.render.VertexFormat +import net.minecraft.client.render.VertexFormats +import net.minecraft.util.math.BlockPos +import net.minecraft.util.math.Vec3d + +class RenderBlockContext(val tesselator: Tessellator, val camPos: Vec3d) { + val buffer = tesselator.buffer + fun color(red: Float, green: Float, blue: Float, alpha: Float) { + RenderSystem.setShaderColor(red, green, blue, alpha) + } + + fun block(blockPos: BlockPos) { + val matrixStack = RenderSystem.getModelViewStack() + matrixStack.push() + matrixStack.translate(blockPos.x - camPos.x, blockPos.y - camPos.y, blockPos.z - camPos.z) + RenderSystem.applyModelViewMatrix() + RenderSystem.setShader(GameRenderer::getPositionColorShader) + buildCube(buffer) + tesselator.draw() + matrixStack.pop() + } + + companion object { + fun buildCube(buf: BufferBuilder) { + buf.begin(VertexFormat.DrawMode.TRIANGLES, VertexFormats.POSITION_COLOR) + buf.fixedColor(255, 255, 255, 255) + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(0.0, 0.0, 1.0).next() + buf.vertex(0.0, 1.0, 1.0).next() + buf.vertex(1.0, 1.0, 0.0).next() + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(0.0, 1.0, 0.0).next() + buf.vertex(1.0, 0.0, 1.0).next() + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(1.0, 0.0, 0.0).next() + buf.vertex(1.0, 1.0, 0.0).next() + buf.vertex(1.0, 0.0, 0.0).next() + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(0.0, 1.0, 1.0).next() + buf.vertex(0.0, 1.0, 0.0).next() + buf.vertex(1.0, 0.0, 1.0).next() + buf.vertex(0.0, 0.0, 1.0).next() + buf.vertex(0.0, 0.0, 0.0).next() + buf.vertex(0.0, 1.0, 1.0).next() + buf.vertex(0.0, 0.0, 1.0).next() + buf.vertex(1.0, 0.0, 1.0).next() + buf.vertex(1.0, 1.0, 1.0).next() + buf.vertex(1.0, 0.0, 0.0).next() + buf.vertex(1.0, 1.0, 0.0).next() + buf.vertex(1.0, 0.0, 0.0).next() + buf.vertex(1.0, 1.0, 1.0).next() + buf.vertex(1.0, 0.0, 1.0).next() + buf.vertex(1.0, 1.0, 1.0).next() + buf.vertex(1.0, 1.0, 0.0).next() + buf.vertex(0.0, 1.0, 0.0).next() + buf.vertex(1.0, 1.0, 1.0).next() + buf.vertex(0.0, 1.0, 0.0).next() + buf.vertex(0.0, 1.0, 1.0).next() + buf.vertex(1.0, 1.0, 1.0).next() + buf.vertex(0.0, 1.0, 1.0).next() + buf.vertex(1.0, 0.0, 1.0).next() + buf.unfixColor() + } + + fun renderBlocks(camera: Camera, block: RenderBlockContext. () -> Unit) { + RenderSystem.disableDepthTest() + RenderSystem.disableTexture() + RenderSystem.enableBlend() + RenderSystem.defaultBlendFunc() + + val ctx = RenderBlockContext(Tessellator.getInstance(), camera.pos) + block(ctx) + + VertexBuffer.unbind() + RenderSystem.enableDepthTest() + RenderSystem.enableTexture() + RenderSystem.disableBlend() + } + } +} + + diff --git a/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt b/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt new file mode 100644 index 0000000..ac640be --- /dev/null +++ b/src/main/kotlin/moe/nea/notenoughupdates/util/textutil.kt @@ -0,0 +1,70 @@ +package moe.nea.notenoughupdates.util + +import net.minecraft.text.LiteralTextContent +import net.minecraft.text.Text +import net.minecraft.text.TextContent +import moe.nea.notenoughupdates.NotEnoughUpdates + + +class TextMatcher(text: Text) { + data class State( + var iterator: MutableList<Text>, + var currentText: Text?, + var offset: Int, + var textContent: String, + ) + + var state = State( + mutableListOf(text), + null, + 0, + "" + ) + + fun pollChunk(): Boolean { + val firstOrNull = state.iterator.removeFirstOrNull() ?: return false + state.offset = 0 + state.currentText = firstOrNull + state.textContent = when (val content = firstOrNull.content) { + is LiteralTextContent -> content.string + TextContent.EMPTY -> "" + else -> { + NotEnoughUpdates.logger.warn("TextContent of type ${content.javaClass} not understood.") + return false + } + } + state.iterator.addAll(0, firstOrNull.siblings) + return true + } + + fun pollChunks(): Boolean { + while (state.offset !in state.textContent.indices) { + if (!pollChunk()) { + return false + } + } + return true + } + + fun pollChar(): Char? { + if (!pollChunks()) return null + return state.textContent[state.offset++] + } + + + fun expectString(string: String): Boolean { + var found = "" + while (found.length < string.length) { + if (!pollChunks()) return false + val takeable = state.textContent.drop(state.offset).take(string.length - found.length) + state.offset += takeable.length + found += takeable + } + return found == string + } +} + + +val Text.unformattedString + get() = string.replace("ยง.".toRegex(), "") + |