Jump to content

Recommended Posts

Posted

Upon upgrading my dynamic link panels mod to 1.7.2, it appears my packets are being truncated by netty.

 

I am using slightly modified versions of the simpleimpl packet handlers, only modified gain access to playerentity.

 

This is the code I'm using in my packet:

 

   public void toBytes(ByteBuf buffer, ChannelHandlerContext ctx)
    {
    	if (this.compressedChunkData == null)
        {
            deflateGate.acquireUninterruptibly();
            if (this.compressedChunkData == null)
            {
                deflate();
            }
            deflateGate.release();
        }
    	buffer.writeInt(dimension);
        buffer.writeInt(this.xPos);
        buffer.writeInt(this.zPos);
        buffer.writeBoolean(this.includeInitialize);
        buffer.writeShort((short)(this.yPos & 65535));
        buffer.writeShort((short)(this.yMSBPos & 65535));
        buffer.writeInt(this.compressedChunkData.length);
        int i = buffer.writableBytes();
        buffer.ensureWritable(this.compressedChunkData.length);
        buffer.writeBytes(this.compressedChunkData);
    }

@Override
public void fromBytes(ByteBuf in, ChannelHandlerContext ctx) {
	this.dimension = in.readInt();
	this.xPos = in.readInt();
        this.zPos = in.readInt();
        this.includeInitialize = in.readBoolean();
        this.yPos = in.readShort();
        this.yMSBPos = in.readShort();
        int len = in.readInt();

        if (field_149286_i.length < len)
        {
            field_149286_i = new byte[len];
        }
        
        in.readBytes(field_149286_i, 0, len);
        int i = 0;
        int j;
        int msb = 0; //BugFix: MC does not read the MSB array from the packet properly, causing issues for servers that use blocks > 256

        for (j = 0; j < 16; ++j)
        {
            i += this.yPos >> j & 1;
            msb += this.yPos >> j & 1;
        }

        j = 12288 * i;
        j += 2048 * msb;

        if (this.includeInitialize)
        {
            j += 256;
        }

        this.chunkData = new byte[j];
        Inflater inflater = new Inflater();
        inflater.setInput(field_149286_i, 0, len);

        try
        {
            inflater.inflate(this.chunkData);
        }
        catch (DataFormatException dataformatexception)
        {
            error = true;
        }
        finally
        {
            inflater.end();
        }
}

 

And this is the crash I'm getting on the client side:

 

Caused by: java.lang.IndexOutOfBoundsException: readerIndex(21) + length(2879) exceeds writerIndex(36): SlicedByteBuf(ridx: 21, widx: 36, cap: 36/36, unwrapped: UnpooledHeapByteBuf(ridx: 1, widx: 37, cap: 37/37))
at io.netty.buffer.AbstractByteBuf.checkReadableBytes(AbstractByteBuf.java:1160) ~[AbstractByteBuf.class:?]
at io.netty.buffer.AbstractByteBuf.readBytes(AbstractByteBuf.java:668) ~[AbstractByteBuf.class:?]
at com.shadowking97.mystcraftplugin.dynamicLinkPanels.network.packets.ChunkInfoPacket.fromBytes(ChunkInfoPacket.java:131) ~[ChunkInfoPacket.class:?]
at com.shadowking97.mystcraftplugin.dynamicLinkPanels.network.impl.DLPIndexedCodec.decodeInto(DLPIndexedCodec.java:17) ~[DLPIndexedCodec.class:?]
at com.shadowking97.mystcraftplugin.dynamicLinkPanels.network.impl.DLPIndexedCodec.decodeInto(DLPIndexedCodec.java:1) ~[DLPIndexedCodec.class:?]
at cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec.decode(FMLIndexedMessageToMessageCodec.java:77) ~[FMLIndexedMessageToMessageCodec.class:?]
at cpw.mods.fml.common.network.FMLIndexedMessageToMessageCodec.decode(FMLIndexedMessageToMessageCodec.java:17) ~[FMLIndexedMessageToMessageCodec.class:?]
at io.netty.handler.codec.MessageToMessageCodec$2.decode(MessageToMessageCodec.java:81) ~[MessageToMessageCodec$2.class:?]
at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:89) ~[MessageToMessageDecoder.class:?]
... 18 more

 

The server isn't reporting any errors, so it *appears* buffer.ensureWritable is passing, allowing the packet to send the full chunkData... but the client isn't receiving the 2879 bytes that it's supposed to.

 

If I can just be pointed in the right direction to ensure my packets are being sent and received completely, that would be lovely. Thank you!

Posted

Well, it is probably just a programming mistake.  Honestly you're probably making the payload processing a little more complicated than necessary, although your general approach seems workable.  Generally you shouldn't need to access the bytes in the buffer directly, but use ByteBuf and ByteBufUtils to access it.

Check out my tutorials here: http://jabelarminecraft.blogspot.com/

Posted

They're not odd computations, they're how vanilla minecraft compresses the chunk data that I'm sending to my second dimension renderer. This is a converted vanilla minecraft packet so I can redirected to my instance of theWorld instead of the normal one.

 

Here's my problem:

 

I'm writing to the packet, both the length of the data and the data itself:

 

        buffer.writeInt(this.compressedChunkData.length);
        int i = buffer.writableBytes();
        buffer.ensureWritable(this.compressedChunkData.length);
        buffer.writeBytes(this.compressedChunkData);

 

And then I'm attempting to read it:

 

int len = in.readInt();

        if (field_149286_i.length < len)
        {
            field_149286_i = new byte[len];
        }
        
        in.readBytes(field_149286_i, 0, len);

 

But when I try to read it:

 

Caused by: java.lang.IndexOutOfBoundsException: readerIndex(21) + length(2879) exceeds writerIndex(36): SlicedByteBuf(ridx: 21, widx: 36, cap: 36/36, unwrapped: UnpooledHeapByteBuf(ridx: 1, widx: 37, cap: 37/37))

 

So it SHOULD be sending a packet with the size of 21+2879, but it's only receiving a packet with the size of 36. The server isn't giving me any warnings or errors about the packet being too big when I try to send it (using simpleimpl), but the client isn't receiving it.

 

 

In other notes: I have just switched my packet pipeline to one of the tutorial ones that doesn't use simpleimpl, editing it so I didn't have to mess with my packets (other than switching which classes everything extends), and it started working fine. Other than the fact that the tutorial I used was marked as having horrible memory leaks. But at least now I know it's not anything wrong with my code, but some error or limitation within simpleimpl. At least in 1083.

Posted

They're not odd computations, they're how vanilla minecraft compresses the chunk data that I'm sending to my second dimension renderer.

 

On the contrary; they are odd in the sense that they are useless and out of place where they are. The uncompressed size is readily available to the sender (and when encoded as an integer) to the receiver as well. Computing it is a futile effort that just wastes cycles. See?

Posted

Mrph, thanks. I hadn't tried running optimizations on code I got from vanilla yet.... renamed variables only, basically.

 

But anyway, now I have to track down what's causing the memory leak in my new packet pipeline and fix it. Then I should be good...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Version 1.19 - Forge 41.0.63 I want to create a wolf entity that I can ride, so far it seems to be working, but the problem is that when I get on the wolf, I can’t control it. I then discovered that the issue is that the server doesn’t detect that I’m riding the wolf, so I’m struggling with synchronization. However, it seems to not be working properly. As I understand it, the server receives the packet but doesn’t register it correctly. I’m a bit new to Java, and I’ll try to provide all the relevant code and prints *The comments and prints are translated by chatgpt since they were originally in Spanish* Thank you very much in advance No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. No player is mounted, or the passenger is not a player. MountableWolfEntity package com.vals.valscraft.entity; import com.vals.valscraft.network.MountSyncPacket; import com.vals.valscraft.network.NetworkHandler; import net.minecraft.client.Minecraft; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.animal.Wolf; import net.minecraft.world.entity.player.Player; import net.minecraft.world.entity.Entity; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.phys.Vec3; import net.minecraftforge.event.TickEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.network.PacketDistributor; public class MountableWolfEntity extends Wolf { private boolean hasSaddle; private static final EntityDataAccessor<Byte> DATA_ID_FLAGS = SynchedEntityData.defineId(MountableWolfEntity.class, EntityDataSerializers.BYTE); public MountableWolfEntity(EntityType<? extends Wolf> type, Level level) { super(type, level); this.hasSaddle = false; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_FLAGS, (byte)0); } public static AttributeSupplier.Builder createAttributes() { return Wolf.createAttributes() .add(Attributes.MAX_HEALTH, 20.0) .add(Attributes.MOVEMENT_SPEED, 0.3); } @Override public InteractionResult mobInteract(Player player, InteractionHand hand) { ItemStack itemstack = player.getItemInHand(hand); if (itemstack.getItem() == Items.SADDLE && !this.hasSaddle()) { if (!player.isCreative()) { itemstack.shrink(1); } this.setSaddle(true); return InteractionResult.SUCCESS; } else if (!level.isClientSide && this.hasSaddle()) { player.startRiding(this); MountSyncPacket packet = new MountSyncPacket(true); // 'true' means the player is mounted NetworkHandler.CHANNEL.sendToServer(packet); // Ensure the server handles the packet return InteractionResult.SUCCESS; } return InteractionResult.PASS; } @Override public void travel(Vec3 travelVector) { if (this.isVehicle() && this.getControllingPassenger() instanceof Player) { System.out.println("The wolf has a passenger."); System.out.println("The passenger is a player."); Player player = (Player) this.getControllingPassenger(); // Ensure the player is the controller this.setYRot(player.getYRot()); this.yRotO = this.getYRot(); this.setXRot(player.getXRot() * 0.5F); this.setRot(this.getYRot(), this.getXRot()); this.yBodyRot = this.getYRot(); this.yHeadRot = this.yBodyRot; float forward = player.zza; float strafe = player.xxa; if (forward <= 0.0F) { forward *= 0.25F; } this.flyingSpeed = this.getSpeed() * 0.1F; this.setSpeed((float) this.getAttributeValue(Attributes.MOVEMENT_SPEED) * 1.5F); this.setDeltaMovement(new Vec3(strafe, travelVector.y, forward).scale(this.getSpeed())); this.calculateEntityAnimation(this, false); } else { // The wolf does not have a passenger or the passenger is not a player System.out.println("No player is mounted, or the passenger is not a player."); super.travel(travelVector); } } public boolean hasSaddle() { return this.hasSaddle; } public void setSaddle(boolean hasSaddle) { this.hasSaddle = hasSaddle; } @Override protected void dropEquipment() { super.dropEquipment(); if (this.hasSaddle()) { this.spawnAtLocation(Items.SADDLE); this.setSaddle(false); } } @SubscribeEvent public static void onServerTick(TickEvent.ServerTickEvent event) { if (event.phase == TickEvent.Phase.START) { MinecraftServer server = net.minecraftforge.server.ServerLifecycleHooks.getCurrentServer(); if (server != null) { for (ServerPlayer player : server.getPlayerList().getPlayers()) { if (player.isPassenger() && player.getVehicle() instanceof MountableWolfEntity) { MountableWolfEntity wolf = (MountableWolfEntity) player.getVehicle(); System.out.println("Tick: " + player.getName().getString() + " is correctly mounted on " + wolf); } } } } } private boolean lastMountedState = false; @Override public void tick() { super.tick(); if (!this.level.isClientSide) { // Only on the server boolean isMounted = this.isVehicle() && this.getControllingPassenger() instanceof Player; // Only print if the state changed if (isMounted != lastMountedState) { if (isMounted) { Player player = (Player) this.getControllingPassenger(); // Verify the passenger is a player System.out.println("Server: Player " + player.getName().getString() + " is now mounted."); } else { System.out.println("Server: The wolf no longer has a passenger."); } lastMountedState = isMounted; } } } @Override public void addPassenger(Entity passenger) { super.addPassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(true)); } } } @Override public void removePassenger(Entity passenger) { super.removePassenger(passenger); if (passenger instanceof Player) { Player player = (Player) passenger; if (!this.level.isClientSide && player instanceof ServerPlayer) { // Send the packet to the server to indicate the player is no longer mounted NetworkHandler.CHANNEL.send(PacketDistributor.PLAYER.with(() -> (ServerPlayer) player), new MountSyncPacket(false)); } } } @Override public boolean isControlledByLocalInstance() { Entity entity = this.getControllingPassenger(); return entity instanceof Player; } @Override public void positionRider(Entity passenger) { if (this.hasPassenger(passenger)) { double xOffset = Math.cos(Math.toRadians(this.getYRot() + 90)) * 0.4; double zOffset = Math.sin(Math.toRadians(this.getYRot() + 90)) * 0.4; passenger.setPos(this.getX() + xOffset, this.getY() + this.getPassengersRidingOffset() + passenger.getMyRidingOffset(), this.getZ() + zOffset); } } } MountSyncPacket package com.vals.valscraft.network; import com.vals.valscraft.entity.MountableWolfEntity; import net.minecraft.network.FriendlyByteBuf; import net.minecraft.server.level.ServerLevel; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class MountSyncPacket { private final boolean isMounted; public MountSyncPacket(boolean isMounted) { this.isMounted = isMounted; } public void encode(FriendlyByteBuf buffer) { buffer.writeBoolean(isMounted); } public static MountSyncPacket decode(FriendlyByteBuf buffer) { return new MountSyncPacket(buffer.readBoolean()); } public void handle(NetworkEvent.Context context) { context.enqueueWork(() -> { ServerPlayer player = context.getSender(); // Get the player from the context if (player != null) { // Verifies if the player has dismounted if (!isMounted) { Entity vehicle = player.getVehicle(); if (vehicle instanceof MountableWolfEntity wolf) { // Logic to remove the player as a passenger wolf.removePassenger(player); System.out.println("Server: Player " + player.getName().getString() + " is no longer mounted."); } } } }); context.setPacketHandled(true); // Marks the packet as handled } } networkHandler package com.vals.valscraft.network; import com.vals.valscraft.valscraft; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.network.NetworkRegistry; import net.minecraftforge.network.simple.SimpleChannel; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class NetworkHandler { private static final String PROTOCOL_VERSION = "1"; public static final SimpleChannel CHANNEL = NetworkRegistry.newSimpleChannel( new ResourceLocation(valscraft.MODID, "main"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals ); public static void init() { int packetId = 0; // Register the mount synchronization packet CHANNEL.registerMessage( packetId++, MountSyncPacket.class, MountSyncPacket::encode, MountSyncPacket::decode, (msg, context) -> msg.handle(context.get()) // Get the context with context.get() ); } }  
    • Do you use features of inventory profiles next (ipnext) or is there a change without it?
    • Remove rubidium - you are already using embeddium, which is a fork of rubidium
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.