Add ViaAxiom
Deploy / Build (push) Skipped
Pull Request Build / Build (pull_request) Failing after 17s

This commit is contained in:
Jakob Schulz
2026-11-01 15:30:21 +01:00
parent e198772885
commit f373e3d6d9
76 changed files with 4496 additions and 896 deletions
+95
View File
@@ -0,0 +1,95 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm")
id("net.fabricmc.fabric-loom")
}
base {
archivesName.set(project.property("archives_base_name") as String)
}
val targetJavaVersion = 25
java {
toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion)
// Minecraft 26.2 uses official names; Loom packages the JAR without remapping.
withSourcesJar()
}
loom {
splitEnvironmentSourceSets()
mods {
register("viaaxiom") {
sourceSet("main")
sourceSet("client")
}
}
}
val bundledCore: Configuration by configurations.creating {
isCanBeConsumed = false
isTransitive = false
}
dependencies {
minecraft("com.mojang:minecraft:${project.property("minecraft_version")}")
implementation("net.fabricmc:fabric-loader:${project.property("loader_version")}")
implementation("net.fabricmc:fabric-language-kotlin:${project.property("kotlin_loader_version")}")
implementation("net.fabricmc.fabric-api:fabric-api:${project.property("fabric_version")}")
implementation(project(":core"))
bundledCore(project(":core"))
testImplementation(kotlin("test"))
include("com.github.luben:zstd-jni:1.5.5-4")
}
tasks.processResources {
val minecraftVersion = project.property("minecraft_version") as String
val loaderVersion = project.property("loader_version") as String
val kotlinLoaderVersion = project.property("kotlin_loader_version") as String
inputs.property("version", project.version)
inputs.property("minecraft_version", minecraftVersion)
inputs.property("loader_version", loaderVersion)
filteringCharset = "UTF-8"
filesMatching("fabric.mod.json") {
expand(
"version" to project.version,
"minecraft_version" to minecraftVersion,
"loader_version" to loaderVersion,
"kotlin_loader_version" to kotlinLoaderVersion
)
}
}
tasks.withType<JavaCompile>().configureEach {
options.encoding = "UTF-8"
options.release.set(targetJavaVersion)
}
tasks.withType<KotlinCompile>().configureEach {
compilerOptions.jvmTarget.set(JvmTarget.fromTarget(targetJavaVersion.toString()))
}
tasks.test {
useJUnitPlatform()
}
sourceSets.test {
compileClasspath += sourceSets["client"].output + sourceSets["client"].compileClasspath
runtimeClasspath += sourceSets["client"].output + sourceSets["client"].runtimeClasspath
}
tasks.jar {
from(bundledCore.elements.map { jars -> jars.map { zipTree(it) } }) {
exclude("META-INF/**")
}
from(files(rootProject.file("LICENSE.txt"), rootProject.file("NOTICE.txt"))) {
rename { "${it}_${project.base.archivesName.get()}" }
}
}
@@ -0,0 +1,44 @@
package me.wargearsystems.viaaxiom.mixin.client;
import io.netty.channel.ChannelHandlerContext;
import me.wargearsystems.viaaxiom.client.network.AxiomNettyBridge;
import net.minecraft.network.Connection;
import net.minecraft.network.ConnectionProtocol;
import net.minecraft.network.ProtocolInfo;
import net.minecraft.network.PacketListener;
import io.netty.channel.Channel;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Final;
import net.minecraft.network.protocol.PacketFlow;
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(Connection.class)
public abstract class ClientConnectionMixin {
@Shadow private Channel channel;
@Shadow @Final private PacketFlow receiving;
@Inject(method = "channelActive", at = @At("TAIL"))
private void viaaxiom$installAxiomTranslator(ChannelHandlerContext context, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
AxiomNettyBridge.INSTANCE.install(context.pipeline());
}
@Inject(method = "setupInboundProtocol", at = @At("TAIL"))
private void viaaxiom$inboundProtocol(ProtocolInfo<?> protocol, PacketListener listener, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
Runnable update = () -> AxiomNettyBridge.INSTANCE.protocolChanged(channel.pipeline(),
AxiomPayloadDirection.CLIENTBOUND, protocol.id() == ConnectionProtocol.PLAY);
if (channel.eventLoop().inEventLoop()) update.run(); else channel.eventLoop().execute(update);
}
@Inject(method = "setupOutboundProtocol", at = @At("TAIL"))
private void viaaxiom$outboundProtocol(ProtocolInfo<?> protocol, CallbackInfo ci) {
if (receiving != PacketFlow.CLIENTBOUND) return;
Runnable update = () -> AxiomNettyBridge.INSTANCE.protocolChanged(channel.pipeline(),
AxiomPayloadDirection.SERVERBOUND, protocol.id() == ConnectionProtocol.PLAY);
if (channel.eventLoop().inEventLoop()) update.run(); else channel.eventLoop().execute(update);
}
}
@@ -0,0 +1,214 @@
package me.wargearsystems.viaaxiom.client.network
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrame
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
import me.wargearsystems.viaaxiom.protocol.AxiomEnable
import me.wargearsystems.viaaxiom.protocol.AxiomHello
import me.wargearsystems.viaaxiom.protocol.AxiomHandshakeTracker
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import me.wargearsystems.viaaxiom.protocol.AxiomProtocol
import me.wargearsystems.viaaxiom.protocol.AxiomTranslationSession
import me.wargearsystems.viaaxiom.translation.AxiomFrameTranslationEngine
import me.wargearsystems.viaaxiom.translation.AxiomTranslationEngine
import me.wargearsystems.viaaxiom.translation.BlockStateIdTranslator
import me.wargearsystems.viaaxiom.translation.BlockStatePaletteWidths
import org.slf4j.LoggerFactory
import io.netty.channel.ChannelHandlerContext
import io.netty.buffer.Unpooled
import me.wargearsystems.viaaxiom.protocol.AxiomLegacyBridge
import java.util.concurrent.TimeUnit
import io.netty.channel.Channel
class AxiomClientTranslationState(
private val legacyBridgeFactory: (Channel) -> AxiomLegacyBridge = ViaFabricPlusMappingProvider::createLegacyBridge,
) {
private val logger = LoggerFactory.getLogger("ViaAxiom")
private val handshake = AxiomHandshakeTracker()
private var frameTranslationEngine: AxiomFrameTranslationEngine? = null
private var serverProtocolVersion: Int? = null
private var clientboundPlay = false
private var serverboundPlay = false
private var legacyBridge: AxiomLegacyBridge? = null
private var bridgeAttempted = false
private var modernHandshakeSeen = false
private val registeredChannels = linkedSetOf<String>()
private var generation = 0L
fun protocolChanged(direction: AxiomPayloadDirection, play: Boolean) {
if (direction == AxiomPayloadDirection.CLIENTBOUND) {
generation++
clientboundPlay = play
clientboundCustomPayloadPacketId = null
handshake.reset()
legacyBridge = null
bridgeAttempted = false
modernHandshakeSeen = false
registeredChannels.clear()
} else {
serverboundPlay = play
serverboundCustomPayloadPacketId = null
}
}
fun receive(context: ChannelHandlerContext, bytes: ByteArray): ByteArray {
if (!clientboundPlay) return bytes
val frame = readFrame(bytes, clientboundCustomPayloadPacketId) ?: return bytes
if (frame.channel == "minecraft:register") {
clientboundCustomPayloadPacketId = frame.packetId
registeredChannels.addAll(frame.payloadBytes.toString(Charsets.UTF_8).split('\u0000'))
val axiomChannels = registeredChannels.filter(AxiomProtocol::isAxiomChannel)
if (axiomChannels.isNotEmpty()) logger.info("Axiom server channels (packet {}): {}", frame.packetId, axiomChannels.joinToString(", "))
legacyBridge?.register(frame.payloadBytes)
if (!modernHandshakeSeen && "axiom:hello" in registeredChannels && "axiom:tunnel" !in registeredChannels && !bridgeAttempted) {
bridgeAttempted = true
val scheduledGeneration = generation
context.executor().schedule({
if (!context.channel().isActive || !clientboundPlay || generation != scheduledGeneration || modernHandshakeSeen || "axiom:tunnel" in registeredChannels) return@schedule
runCatching {
val bridge = legacyBridgeFactory(context.channel())
bridge.register(registeredChannels.joinToString("\u0000").toByteArray(Charsets.UTF_8))
legacyBridge = bridge
val challenge = bridge.createChallenge(frame.packetId) ?: return@runCatching
logger.info("Starting API 10 -> API 9 Axiom handshake bridge")
context.fireChannelRead(Unpooled.wrappedBuffer(AxiomCustomPayloadFrameCodec.write(challenge)))
context.fireChannelReadComplete()
}.onFailure { logger.warn("Legacy Axiom bridge unavailable: {}", it.cause?.message ?: it.message) }
}, 500, TimeUnit.MILLISECONDS)
}
return bytes
}
if (!AxiomProtocol.isAxiomChannel(frame.channel)) return bytes
clientboundCustomPayloadPacketId = frame.packetId
if (frame.channel == "axiom:hello" || frame.channel == "axiom:goodbye") modernHandshakeSeen = true
legacyBridge?.let {
val rewritten = it.clientbound(frame)
if (it.active) {
if (frame.channel == "axiom:enable") logger.info("Translated legacy Axiom enable into API 10 server configuration")
return AxiomCustomPayloadFrameCodec.write(rewritten)
}
}
observe(AxiomPayloadDirection.CLIENTBOUND, bytes)
return rewriteClientbound(bytes)
}
/** Null means this fragment is buffered until the final fragment is written. */
fun send(bytes: ByteArray): ByteArray? {
if (!serverboundPlay) return bytes
val frame = readFrame(bytes, serverboundCustomPayloadPacketId) ?: return bytes
if (frame.channel == "minecraft:register") {
serverboundCustomPayloadPacketId = frame.packetId
return bytes
}
if (!AxiomProtocol.isAxiomChannel(frame.channel)) return bytes
serverboundCustomPayloadPacketId = frame.packetId
legacyBridge?.takeIf { it.active }?.let { bridge ->
val rewritten = bridge.serverbound(frame) ?: return null
if (frame.channel == "axiom:hello") logger.info("Translated Axiom client hello into API 9 using server registry IDs")
return AxiomCustomPayloadFrameCodec.write(rewritten)
}
observe(AxiomPayloadDirection.SERVERBOUND, bytes)
return rewriteServerbound(bytes)
}
private fun readFrame(bytes: ByteArray, packetId: Int?): AxiomCustomPayloadFrame? = runCatching {
if (packetId == null) AxiomCustomPayloadFrameCodec.read(bytes)
else AxiomCustomPayloadFrameCodec.readIfCustomPayload(bytes, packetId)
}.getOrNull()
/** The provider must account for any Axiom mappings already performed by the server. */
fun configureTranslation(
serverProtocolVersion: Int,
blockStateIdTranslator: BlockStateIdTranslator,
paletteWidths: BlockStatePaletteWidths,
) {
this.serverProtocolVersion = serverProtocolVersion
frameTranslationEngine = AxiomFrameTranslationEngine(AxiomTranslationEngine(blockStateIdTranslator, paletteWidths))
}
var serverboundCustomPayloadPacketId: Int? = null
private set
var clientboundCustomPayloadPacketId: Int? = null
private set
val hello: AxiomHello?
get() = handshake.hello
val enable: AxiomEnable?
get() = handshake.enable
val session: AxiomTranslationSession?
// The handshake does not carry the server's protocol, a provider has to supply it.
get() = handshake.session(serverProtocolVersion)
fun observe(direction: AxiomPayloadDirection, frameBytes: ByteArray): AxiomCustomPayloadFrame? {
val knownPacketId = when (direction) {
AxiomPayloadDirection.CLIENTBOUND -> clientboundCustomPayloadPacketId
AxiomPayloadDirection.SERVERBOUND -> serverboundCustomPayloadPacketId
}
val frame = if (knownPacketId == null) {
runCatching { AxiomCustomPayloadFrameCodec.read(frameBytes) }.getOrNull()
} else {
runCatching { AxiomCustomPayloadFrameCodec.readIfCustomPayload(frameBytes, knownPacketId) }.getOrNull()
} ?: return null
if (!AxiomProtocol.isAxiomChannel(frame.channel)) {
return null
}
when (direction) {
AxiomPayloadDirection.CLIENTBOUND -> clientboundCustomPayloadPacketId = frame.packetId
AxiomPayloadDirection.SERVERBOUND -> serverboundCustomPayloadPacketId = frame.packetId
}
runCatching { handshake.observe(direction, frame.channel, frame.payloadBytes) }
.onFailure { logger.warn("Cannot observe {} {}: {}", direction, frame.channel, it.message) }
if (direction == AxiomPayloadDirection.CLIENTBOUND && frame.channel == AxiomProtocol.channel("enable")) {
enable?.let {
logger.info("Axiom API {} enabled={}; client-side mappings configured={}", hello?.apiVersion, it.enabled, frameTranslationEngine != null)
}
}
if (direction == AxiomPayloadDirection.CLIENTBOUND && frame.channel == AxiomProtocol.channel("goodbye")) {
handshake.goodbyeReason?.let { logger.info("Axiom disabled: {}", it) }
}
return frame
}
fun rewriteServerbound(frameBytes: ByteArray): ByteArray {
val packetId = serverboundCustomPayloadPacketId ?: return frameBytes
val session = session ?: return frameBytes
val engine = frameTranslationEngine ?: return frameBytes
return runCatching {
engine.rewrite(
frameBytes = frameBytes,
customPayloadPacketId = packetId,
direction = AxiomPayloadDirection.SERVERBOUND,
session = session,
)
}.getOrElse {
logger.warn("Could not rewrite serverbound Axiom payload: {}", it.message)
frameBytes
}
}
fun rewriteClientbound(frameBytes: ByteArray): ByteArray {
val packetId = clientboundCustomPayloadPacketId ?: return frameBytes
val session = session ?: return frameBytes
val engine = frameTranslationEngine ?: return frameBytes
return runCatching {
engine.rewrite(
frameBytes = frameBytes,
customPayloadPacketId = packetId,
direction = AxiomPayloadDirection.CLIENTBOUND,
session = session,
)
}.getOrElse {
logger.warn("Could not rewrite clientbound Axiom payload: {}", it.message)
frameBytes
}
}
}
@@ -0,0 +1,52 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.channel.ChannelPipeline
import io.netty.util.AttributeKey
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
import org.slf4j.LoggerFactory
object AxiomNettyBridge {
private const val INBOUND_HANDLER_NAME = "viaaxiom:raw_axiom_inbound"
private const val OUTBOUND_HANDLER_NAME = "viaaxiom:raw_axiom_outbound"
private const val DECODER_HANDLER_NAME = "decoder"
private const val ENCODER_HANDLER_NAME = "encoder"
private val STATE = AttributeKey.valueOf<AxiomClientTranslationState>("viaaxiom:state")
private val logger = LoggerFactory.getLogger("ViaAxiom")
fun install(pipeline: ChannelPipeline) = install(pipeline) { AxiomClientTranslationState() }
fun install(pipeline: ChannelPipeline, stateFactory: () -> AxiomClientTranslationState) {
// Before login, Minecraft uses inbound_config/outbound_config instead of codecs.
// Position here so replacement with decoder/encoder retains the byte-level hook.
val inboundAnchor = if (pipeline.get(DECODER_HANDLER_NAME) != null) DECODER_HANDLER_NAME else "inbound_config"
val outboundAnchor = if (pipeline.get(ENCODER_HANDLER_NAME) != null) ENCODER_HANDLER_NAME else "outbound_config"
if (pipeline.get(inboundAnchor) == null || pipeline.get(outboundAnchor) == null) return
val state = pipeline.channel().attr(STATE).get() ?: stateFactory().also {
pipeline.channel().attr(STATE).set(it)
}
// Krypton adds decompression immediately before decoder, while ViaFabricPlus
// can move its own codec. Restore the native, uncompressed side of both codecs.
if (!immediatelyBefore(pipeline, INBOUND_HANDLER_NAME, inboundAnchor)) {
if (pipeline.get(INBOUND_HANDLER_NAME) != null) pipeline.remove(INBOUND_HANDLER_NAME)
pipeline.addBefore(inboundAnchor, INBOUND_HANDLER_NAME, RawAxiomInboundHandler(state))
}
if (!immediatelyBefore(pipeline, OUTBOUND_HANDLER_NAME, outboundAnchor)) {
if (pipeline.get(OUTBOUND_HANDLER_NAME) != null) pipeline.remove(OUTBOUND_HANDLER_NAME)
pipeline.addBefore(outboundAnchor, OUTBOUND_HANDLER_NAME, RawAxiomOutboundHandler(state))
}
}
fun protocolChanged(pipeline: ChannelPipeline, direction: AxiomPayloadDirection, play: Boolean) {
install(pipeline)
pipeline.channel().attr(STATE).get()?.protocolChanged(direction, play)
if (play) logger.info("Axiom {} play pipeline: {}", direction, pipeline.names().joinToString(" -> "))
}
private fun immediatelyBefore(pipeline: ChannelPipeline, handler: String, anchor: String): Boolean {
val names = pipeline.names()
val index = names.indexOf(handler)
return index >= 0 && index + 1 < names.size && names[index + 1] == anchor
}
}
@@ -0,0 +1,47 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import me.wargearsystems.viaaxiom.protocol.AxiomPayloadDirection
class RawAxiomInboundHandler(
private val state: AxiomClientTranslationState,
) : ChannelInboundHandlerAdapter() {
override fun userEventTriggered(context: ChannelHandlerContext, event: Any) {
super.userEventTriggered(context, event)
// Krypton fires a pipeline event after adding/removing its compression codecs.
if (event.javaClass.name == "me.steinborn.krypton.mod.shared.misc.KryptonPipelineEvent") {
context.executor().execute {
if (context.channel().isActive) AxiomNettyBridge.install(context.pipeline())
}
}
}
override fun channelRead(context: ChannelHandlerContext, message: Any) {
if (message is ByteBuf) {
val originalBytes = message.copyReadableBytes()
val rewrittenBytes = try {
state.receive(context, originalBytes)
} catch (failure: Exception) {
message.release()
context.fireExceptionCaught(failure)
return
}
if (!rewrittenBytes.contentEquals(originalBytes)) {
message.release()
super.channelRead(context, Unpooled.wrappedBuffer(rewrittenBytes))
return
}
}
super.channelRead(context, message)
}
private fun ByteBuf.copyReadableBytes(): ByteArray {
val bytes = ByteArray(readableBytes())
getBytes(readerIndex(), bytes)
return bytes
}
}
@@ -0,0 +1,76 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelPromise
import io.netty.channel.ChannelDuplexHandler
import java.nio.channels.ClosedChannelException
import me.wargearsystems.viaaxiom.protocol.AxiomCustomPayloadFrameCodec
class RawAxiomOutboundHandler(
private val state: AxiomClientTranslationState,
) : ChannelDuplexHandler() {
private val pendingFragments = mutableListOf<ChannelPromise>()
override fun write(context: ChannelHandlerContext, message: Any, promise: ChannelPromise) {
if (message is ByteBuf) {
val originalBytes = message.copyReadableBytes()
val rewrittenBytes = try {
state.send(originalBytes)
} catch (failure: Exception) {
message.release()
promise.tryFailure(failure)
failPending(failure)
context.fireExceptionCaught(failure)
return
}
if (rewrittenBytes == null) {
message.release()
pendingFragments += promise
return
}
// Only the final tunnel write owns the buffered fragment promises. Unrelated
// packets between fragments must not complete them prematurely.
val isTunnel = runCatching {
AxiomCustomPayloadFrameCodec.read(originalBytes).channel == "axiom:tunnel"
}.getOrDefault(false)
val outputPromise = if (isTunnel && pendingFragments.isNotEmpty()) {
val promises = pendingFragments.toList() + promise
pendingFragments.clear()
context.newPromise().also { combined ->
combined.addListener { future ->
promises.forEach { if (future.isSuccess) it.trySuccess() else it.tryFailure(future.cause()) }
}
}
} else promise
if (!rewrittenBytes.contentEquals(originalBytes)) {
message.release()
super.write(context, Unpooled.wrappedBuffer(rewrittenBytes), outputPromise)
return
}
}
super.write(context, message, promise)
}
override fun channelInactive(context: ChannelHandlerContext) {
failPending(ClosedChannelException())
super.channelInactive(context)
}
override fun handlerRemoved(context: ChannelHandlerContext) {
failPending(ClosedChannelException())
super.handlerRemoved(context)
}
private fun failPending(failure: Throwable) {
pendingFragments.forEach { it.tryFailure(failure) }
pendingFragments.clear()
}
private fun ByteBuf.copyReadableBytes(): ByteArray {
val bytes = ByteArray(readableBytes())
getBytes(readerIndex(), bytes)
return bytes
}
}
@@ -0,0 +1,62 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.channel.Channel
import me.wargearsystems.viaaxiom.protocol.AxiomLegacyBridge
import me.wargearsystems.viaaxiom.translation.*
import net.minecraft.SharedConstants
import net.minecraft.world.level.block.Block
import net.minecraft.world.level.block.Blocks
import org.slf4j.LoggerFactory
/** Optional integration through the public ViaFabricPlus/ViaVersion interfaces. */
object ViaFabricPlusMappingProvider {
private val logger = LoggerFactory.getLogger("ViaAxiom")
fun createLegacyBridge(channel: Channel): AxiomLegacyBridge {
val nativeVersion = SharedConstants.getProtocolVersion()
val api = Class.forName("com.viaversion.viafabricplus.ViaFabricPlus").getMethod("api").invoke(null)
val translation = call("com.viaversion.viafabricplus.api.ViaFabricPlusAPI", api, "protocolTranslation")!!
val target = Class.forName("com.viaversion.viafabricplus.api.protocoltranslator.ProtocolTranslation")
.getMethod("targetVersion", Channel::class.java).invoke(translation, channel)
val serverVersion = call("com.viaversion.viaversion.api.protocol.version.ProtocolVersion", target, "getVersion") as Int
require(serverVersion >= 770) { "Legacy bridge currently requires Minecraft 1.21.5 or newer" }
val clientSize = Block.BLOCK_STATE_REGISTRY.size()
val stone = Block.getId(Blocks.STONE.defaultBlockState())
val steps = mutableListOf<IntArray>()
if (nativeVersion != serverVersion) {
val manager = Class.forName("com.viaversion.viaversion.api.Via").getMethod("getManager").invoke(null)
val protocols = call("com.viaversion.viaversion.api.ViaManager", manager, "getProtocolManager")!!
val managerClass = Class.forName("com.viaversion.viaversion.api.protocol.ProtocolManager")
val path = managerClass.getMethod("getProtocolPath", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType)
.invoke(protocols, nativeVersion, serverVersion) as? List<*>
?: error("No ViaVersion mapping path from $nativeVersion to $serverVersion")
for (entry in path.asReversed()) {
val protocol = call("com.viaversion.viaversion.api.protocol.ProtocolPathEntry", entry!!, "protocol")!!
managerClass.getMethod("completeMappingDataLoading", Class::class.java).invoke(protocols, protocol.javaClass)
val data = call("com.viaversion.viaversion.api.protocol.Protocol", protocol, "getMappingData") ?: continue
val mappings = call("com.viaversion.viaversion.api.data.MappingData", data, "getBlockStateMappings") ?: continue
val size = call("com.viaversion.viaversion.api.data.Mappings", mappings, "size") as Int
require(size in 1..1_000_000) { "Invalid block registry mapping size" }
val getNewId = Class.forName("com.viaversion.viaversion.api.data.Mappings")
.getMethod("getNewId", Int::class.javaPrimitiveType)
steps += IntArray(size) { getNewId.invoke(mappings, it) as Int }
}
}
val (clientToServer, _) = BlockStateMappingChain.compose(steps, clientSize, stone)
val empty = Block.getId(Blocks.VOID_AIR.defaultBlockState())
require(clientToServer[empty] >= 0) { "Mapping chain cannot preserve Axiom's empty block state" }
var reportedMissing = false
val engine = BlockStateMappingChain.translationEngine(steps, clientSize, stone) { direction, id, fallback ->
if (!reportedMissing) {
reportedMissing = true
logger.warn("Axiom {} block state {} has no mapping; using stone placeholder {}", direction, id, fallback)
}
}
logger.info("Legacy Axiom bridge mappings ready: protocol {} -> {}, block registries {} -> {}",
nativeVersion, serverVersion, clientSize, steps.firstOrNull()?.size ?: clientSize)
return AxiomLegacyBridge(serverVersion, engine)
}
private fun call(type: String, receiver: Any, method: String): Any? =
Class.forName(type).getMethod(method).invoke(receiver)
}
@@ -0,0 +1,15 @@
{
"required": true,
"minVersion": "0.8",
"package": "me.wargearsystems.viaaxiom.mixin.client",
"compatibilityLevel": "JAVA_25",
"client": [
"ClientConnectionMixin"
],
"injectors": {
"defaultRequire": 1
},
"overwrites": {
"requireAnnotations": true
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"schemaVersion": 1,
"id": "viaaxiom",
"version": "${version}",
"name": "ViaAxiom",
"description": "Translates Axiom traffic between client and server versions",
"authors": ["Jakob Schulz"],
"license": "MIT",
"environment": "client",
"mixins": [
"viaaxiom.client.mixins.json"
],
"depends": {
"fabricloader": ">=${loader_version}",
"fabric-language-kotlin": ">=${kotlin_loader_version}",
"fabric-api": "*",
"minecraft": "${minecraft_version}",
"java": ">=25"
}
}
@@ -0,0 +1,154 @@
package me.wargearsystems.viaaxiom.client.network
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelOutboundHandlerAdapter
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.embedded.EmbeddedChannel
import me.wargearsystems.viaaxiom.binary.AxiomByteWriter
import me.wargearsystems.viaaxiom.protocol.*
import me.wargearsystems.viaaxiom.translation.*
import java.util.concurrent.TimeUnit
import kotlin.test.*
class AxiomNettyBridgeTest {
@Test fun `compression insertion and ViaFabricPlus reorder retain uncompressed native payload hook`() {
val channel = EmbeddedChannel()
channel.pipeline().addLast("decoder", ChannelInboundHandlerAdapter())
channel.pipeline().addLast("encoder", ChannelOutboundHandlerAdapter())
val (temporaryChannel, state) = channel()
temporaryChannel.finishAndReleaseAll()
AxiomNettyBridge.install(channel.pipeline()) { state }
// Model Krypton's insertion after ViaAxiom was installed at channelActive.
channel.pipeline().addBefore("decoder", "decompress", object : ChannelInboundHandlerAdapter() {
override fun channelRead(context: ChannelHandlerContext, message: Any) {
val input = message as ByteBuf
assertEquals(77, input.readUnsignedByte().toInt())
context.fireChannelRead(input)
}
})
channel.pipeline().addBefore("decoder", "via-decoder", ChannelInboundHandlerAdapter())
channel.pipeline().addBefore("encoder", "compress", ChannelOutboundHandlerAdapter())
channel.pipeline().addBefore("encoder", "via-encoder", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.protocolChanged(channel.pipeline(), AxiomPayloadDirection.CLIENTBOUND, true)
AxiomNettyBridge.protocolChanged(channel.pipeline(), AxiomPayloadDirection.SERVERBOUND, true)
val names = channel.pipeline().names()
assertTrue(names.indexOf("decompress") < names.indexOf("viaaxiom:raw_axiom_inbound"))
assertTrue(names.indexOf("via-decoder") < names.indexOf("viaaxiom:raw_axiom_inbound"))
assertEquals(names.indexOf("encoder") - 1, names.indexOf("viaaxiom:raw_axiom_outbound"))
val compressed = Unpooled.buffer().writeByte(77).writeBytes(AxiomCustomPayloadFrameCodec.write(registration()))
channel.writeInbound(compressed)
assertEquals("minecraft:register", frame(channel.readInbound()).channel)
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
assertEquals("axiom:hello", frame(assertNotNull(channel.readInbound<ByteBuf>())).channel)
channel.finishAndReleaseAll()
}
@Test fun `hooks are installed before initial configuration handlers and survive replacement`() {
val channel = EmbeddedChannel()
channel.pipeline().addLast("inbound_config", ChannelInboundHandlerAdapter())
channel.pipeline().addLast("outbound_config", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.install(channel.pipeline())
val names = channel.pipeline().names()
assertTrue(names.indexOf("viaaxiom:raw_axiom_inbound") < names.indexOf("inbound_config"))
assertTrue(names.indexOf("viaaxiom:raw_axiom_outbound") < names.indexOf("outbound_config"))
channel.pipeline().replace("inbound_config", "decoder", ChannelInboundHandlerAdapter())
channel.pipeline().replace("outbound_config", "encoder", ChannelOutboundHandlerAdapter())
AxiomNettyBridge.install(channel.pipeline())
assertEquals(1, channel.pipeline().names().count { it == "viaaxiom:raw_axiom_inbound" })
channel.finishAndReleaseAll()
}
@Test fun `legacy registration produces challenge and rewrites real outbound hello`() {
val (channel, _) = channel()
register(channel)
val challenge = frame(assertNotNull(channel.readInbound<ByteBuf>()))
assertEquals("axiom:hello", challenge.channel)
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, 42)))))
val outgoing = frame(assertNotNull(channel.readOutbound<ByteBuf>()))
assertEquals(AxiomHello(9, 5000, 771), AxiomHelloCodec.read(outgoing.payloadBytes))
channel.finishAndReleaseAll()
}
@Test fun `fragment promises wait for combined write and unrelated writes do not complete them`() {
val (channel, _) = channel()
negotiate(channel)
val body = ByteArray(1000)
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_buffer", body), splitSize = 128)
val promises = fragments.dropLast(1).map { fragment ->
channel.newPromise().also { channel.pipeline().write(buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragment)), it) }
}
assertTrue(promises.none { it.isDone })
channel.writeOutbound(Unpooled.wrappedBuffer(byteArrayOf(0)))
assertTrue(promises.none { it.isDone })
assertContentEquals(byteArrayOf(0), bytes(channel.readOutbound()))
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragments.last())))
assertTrue(promises.all { it.isSuccess })
val output = frame(channel.readOutbound())
assertEquals("axiom:set_buffer", output.channel)
assertContentEquals(body, output.payloadBytes)
channel.finishAndReleaseAll()
}
@Test fun `disconnect fails pending writes and releases buffered ByteBufs`() {
val (channel, _) = channel()
negotiate(channel)
val fragments = AxiomTunnelCodec.encode(AxiomTunnelPacket("axiom:set_buffer", ByteArray(500)), splitSize = 128)
val input = buffer(AxiomCustomPayloadFrame(20, "axiom:tunnel", fragments.first()))
val promise = channel.newPromise()
channel.pipeline().write(input, promise)
assertEquals(0, input.refCnt())
assertFalse(promise.isDone)
channel.close()
assertTrue(promise.isDone)
assertFalse(promise.isSuccess)
channel.finishAndReleaseAll()
}
@Test fun `configuration phase registrations cannot start play handshake and stale callbacks are cancelled`() {
val (channel, state) = channel()
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, false)
register(channel)
assertNull(channel.readInbound<ByteBuf>())
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, true)
channel.writeInbound(buffer(registration()))
bytes(channel.readInbound())
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, false)
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
assertNull(channel.readInbound<ByteBuf>())
channel.finishAndReleaseAll()
}
private fun channel(): Pair<EmbeddedChannel, AxiomClientTranslationState> {
val state = AxiomClientTranslationState {
AxiomLegacyBridge(771, object : AxiomPayloadTranslator {
override fun rewrite(payload: AxiomPayload, session: AxiomTranslationSession) = payload.bytes
}) { 42 }
}
state.protocolChanged(AxiomPayloadDirection.CLIENTBOUND, true)
state.protocolChanged(AxiomPayloadDirection.SERVERBOUND, true)
return EmbeddedChannel(RawAxiomInboundHandler(state), RawAxiomOutboundHandler(state)) to state
}
private fun registration() = AxiomCustomPayloadFrame(24, "minecraft:register", "axiom:hello\u0000axiom:set_buffer".toByteArray())
private fun register(channel: EmbeddedChannel) {
channel.writeInbound(buffer(registration()))
bytes(channel.readInbound())
channel.advanceTimeBy(600, TimeUnit.MILLISECONDS)
channel.runScheduledPendingTasks()
}
private fun negotiate(channel: EmbeddedChannel) {
register(channel)
bytes(channel.readInbound())
channel.writeOutbound(buffer(AxiomCustomPayloadFrame(20, "axiom:hello", AxiomHelloCodec.write(AxiomHello(10, 5000, 776, 42)))))
bytes(channel.readOutbound())
channel.writeInbound(buffer(AxiomCustomPayloadFrame(24, "axiom:enable", AxiomEnableCodec.write(AxiomEnable(true, 1_048_576, 2, 0, 0)))))
bytes(channel.readInbound())
}
private fun buffer(frame: AxiomCustomPayloadFrame) = Unpooled.wrappedBuffer(AxiomCustomPayloadFrameCodec.write(frame))
private fun frame(buffer: ByteBuf) = AxiomCustomPayloadFrameCodec.read(bytes(buffer))
private fun bytes(buffer: ByteBuf): ByteArray = ByteArray(buffer.readableBytes()).also { buffer.readBytes(it); buffer.release() }
}