net.minecraft.network.PacketBuffer Java Examples

The following examples show how to use net.minecraft.network.PacketBuffer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SetSerializerProvider.java    From OpenModsLib with MIT License 6 votes vote down vote up
protected IStreamSerializer<?> createSetSerializer(final TypeToken<?> componentType) {
	final IStreamSerializer<Object[]> arraySerializer = NullableCollectionSerializer.createObjectArraySerializer(componentType);
	return new IStreamSerializer<Set<?>>() {

		@Override
		public Set<?> readFromStream(PacketBuffer input) throws IOException {
			Object[] values = arraySerializer.readFromStream(input);
			return Sets.newHashSet(values);
		}

		@Override
		public void writeToStream(Set<?> o, PacketBuffer output) throws IOException {
			final Object[] tmp = new Object[o.size()];
			arraySerializer.writeToStream(o.toArray(tmp), output);
		}
	};
}
 
Example #2
Source File: PhysicsObject.java    From Valkyrien-Skies with Apache License 2.0 6 votes vote down vote up
public void writeSpawnData(ByteBuf buffer) {
    PacketBuffer modifiedBuffer = new PacketBuffer(buffer);

    modifiedBuffer.writeInt(getOwnedChunks().getCenterX());
    modifiedBuffer.writeInt(getOwnedChunks().getCenterZ());
    modifiedBuffer.writeInt(getOwnedChunks().getRadius());

    modifiedBuffer.writeDouble(getWrapperEntity().posX);
    modifiedBuffer.writeDouble(getWrapperEntity().posY);
    modifiedBuffer.writeDouble(getWrapperEntity().posZ);

    modifiedBuffer.writeDouble(getWrapperEntity().getPitch());
    modifiedBuffer.writeDouble(getWrapperEntity().getYaw());
    modifiedBuffer.writeDouble(getWrapperEntity().getRoll());

    getCenterCoord().writeToByteBuf(modifiedBuffer);

    // Make a local copy to avoid potential data races
    BlockPos physicsInfuserPosLocal = getPhysicsInfuserPos();
    modifiedBuffer.writeBoolean(physicsInfuserPosLocal != null);
    if (physicsInfuserPosLocal != null) {
        modifiedBuffer.writeBlockPos(physicsInfuserPosLocal);
    }
}
 
Example #3
Source File: PacketAsteroidInfo.java    From AdvancedRocketry with MIT License 6 votes vote down vote up
@Override
public void write(ByteBuf out) {
	PacketBuffer packetBuffer = new PacketBuffer(out);
	NBTTagCompound nbt = new NBTTagCompound();
	
	packetBuffer.writeString(asteroid.ID);
	packetBuffer.writeInt(asteroid.distance);
	packetBuffer.writeInt(asteroid.mass);
	packetBuffer.writeInt(asteroid.minLevel);
	packetBuffer.writeFloat(asteroid.massVariability);
	packetBuffer.writeFloat(asteroid.richness);					//factor of the ratio of ore to stone
	packetBuffer.writeFloat(asteroid.richnessVariability);		//variability of richness
	packetBuffer.writeFloat(asteroid.probability);				//probability of the asteroid spawning
	packetBuffer.writeFloat(asteroid.timeMultiplier);
	
	packetBuffer.writeInt(asteroid.stackProbabilites.size());
	for(int i = 0; i < asteroid.stackProbabilites.size(); i++)
	{
		packetBuffer.writeItemStack(asteroid.itemStacks.get(i));
		packetBuffer.writeFloat(asteroid.stackProbabilites.get(i));
	}
}
 
Example #4
Source File: MetaTileEntity.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void receiveInitialSyncData(PacketBuffer buf) {
    this.frontFacing = EnumFacing.VALUES[buf.readByte()];
    this.paintingColor = buf.readInt();
    int amountOfTraits = buf.readShort();
    for (int i = 0; i < amountOfTraits; i++) {
        int traitNetworkId = buf.readVarInt();
        MTETrait trait = mteTraits.stream().filter(otherTrait -> otherTrait.getNetworkID() == traitNetworkId).findAny().get();
        trait.receiveInitialData(buf);
    }
    for (EnumFacing coverSide : EnumFacing.VALUES) {
        int coverId = buf.readVarInt();
        if (coverId != -1) {
            CoverDefinition coverDefinition = CoverDefinition.getCoverByNetworkId(coverId);
            CoverBehavior coverBehavior = coverDefinition.createCoverBehavior(this, coverSide);
            coverBehavior.readInitialSyncData(buf);
            this.coverBehaviors[coverSide.getIndex()] = coverBehavior;
        }
    }
    this.isFragile = buf.readBoolean();
}
 
Example #5
Source File: NetworkEventCodec.java    From OpenModsLib with MIT License 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, NetworkEvent msg, List<Object> out) throws IOException {
	final Channel channel = ctx.channel();
	final Side side = channel.attr(NetworkRegistry.CHANNEL_SOURCE).get();

	final NetworkEventEntry entry = CommonRegistryCallbacks.getObjectToEntryMap(registry).get(msg.getClass());
	Preconditions.checkState(entry != null, "Can't find registration for class %s", msg.getClass());
	final int id = CommonRegistryCallbacks.getEntryIdMap(registry).get(entry);

	final EventDirection validator = entry.getDirection();
	Preconditions.checkState(validator != null && validator.validateSend(side),
			"Invalid direction: sending packet %s on side %s", msg.getClass(), side);

	final PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
	buf.writeVarInt(id);
	msg.writeToStream(buf);

	final FMLProxyPacket packet = new FMLProxyPacket(buf, NetworkEventDispatcher.CHANNEL_NAME);
	packet.setDispatcher(msg.dispatcher);
	out.add(packet);
}
 
Example #6
Source File: LitematicaBlockStateContainerFull.java    From litematica with GNU Lesser General Public License v3.0 6 votes vote down vote up
public byte[] getBackingArrayAsByteArray()
{
    final int entrySize = PacketBuffer.getVarIntSize(this.palette.getPaletteSize() - 1);
    final long volume = this.storage.size();
    final long length = (long) entrySize * volume;

    if (length > Integer.MAX_VALUE)
    {
        throw new IndexOutOfBoundsException("Block data backing byte array length " + length + " exceeds the maximum value of " + Integer.MAX_VALUE);
    }

    byte[] arr = new byte[(int) length];
    PacketBuffer buf = new PacketBuffer(Unpooled.wrappedBuffer(arr));
    buf.writerIndex(0);

    for (int i = 0; i < volume; ++i)
    {
        buf.writeVarInt(this.storage.getAt(i));
    }

    return arr;
}
 
Example #7
Source File: MessageStopPiloting.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@Override
public void fromBytes(ByteBuf buf) {
    PacketBuffer packetBuf = new PacketBuffer(buf);
    posToStopPiloting = new BlockPos(
        packetBuf.readInt(),
        packetBuf.readInt(),
        packetBuf.readInt()
    );
}
 
Example #8
Source File: ForgePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void dispatchCUIEvent(CUIEvent event) {
    String[] params = event.getParameters();
    String send = event.getTypeId();
    if (params.length > 0) {
        send = send + "|" + StringUtil.joinString(params, "|");
    }
    PacketBuffer buffer = new PacketBuffer(Unpooled.copiedBuffer(send.getBytes(WECUIPacketHandler.UTF_8_CHARSET)));
    SPacketCustomPayload packet = new SPacketCustomPayload(ForgeWorldEdit.CUI_PLUGIN_CHANNEL, buffer);
    this.player.connection.sendPacket(packet);
}
 
Example #9
Source File: TextFieldWidget.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void readUpdateInfo(int id, PacketBuffer buffer) {
    super.readUpdateInfo(id, buffer);
    if (id == 1) {
        this.currentString = buffer.readString(Short.MAX_VALUE);
        this.textField.setText(currentString);
    }
}
 
Example #10
Source File: MessageBookCodeData.java    From Minecoprocessors with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void fromBytes(final ByteBuf buf) {
  final PacketBuffer buffer = new PacketBuffer(buf);
  try {
    nbt = buffer.readCompoundTag();
  } catch (final IOException e) {
    Minecoprocessors.proxy.logger.warn("Invalid packet received.", e);
  }
}
 
Example #11
Source File: LaserParticleData.java    From MiningGadgets with MIT License 5 votes vote down vote up
@Override
public void write(PacketBuffer buf) {
    buf.writeVarInt(Block.BLOCK_STATE_IDS.get(state));
    buf.writeFloat(size);
    buf.writeFloat(r);
    buf.writeFloat(g);
    buf.writeFloat(b);
    buf.writeFloat(maxAgeMul);
    buf.writeBoolean(depthTest);
}
 
Example #12
Source File: GPActor.java    From GriefPrevention with MIT License 5 votes vote down vote up
@Override
public void dispatchCUIEvent(CUIEvent event) {
    String[] params = event.getParameters();
    String send = event.getTypeId();
    if (params.length > 0) {
        send = send + "|" + StringUtil.joinString(params, "|");
    }

    PacketBuffer buffer = new PacketBuffer(Unpooled.copiedBuffer(send.getBytes(UTF_8_CHARSET)));
    SPacketCustomPayload packet = new SPacketCustomPayload(CUI_PLUGIN_CHANNEL, buffer);
    this.player.connection.sendPacket(packet);
}
 
Example #13
Source File: ItemArtifact.java    From Artifacts with MIT License 5 votes vote down vote up
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
   {
	NBTTagCompound data = itemStack.getTagCompound();
	int effectID = 0;
	if(data != null && world.isRemote) {
		effectID = data.getInteger("onItemRightClick");
		if(effectID != 0) {
			//System.out.println("Activating...");
			int d = data.getInteger("onItemRightClickDelay");
			//System.out.println("R-click: " + d);
			if(d <= 0) {
				IArtifactComponent c = ArtifactsAPI.artifacts.getComponent(effectID);
				if(c != null)
					itemStack = c.onItemRightClick(itemStack, world, player);
				d = itemStack.stackTagCompound.getInteger("onItemRightClickDelay");
				
				PacketBuffer out = new PacketBuffer(Unpooled.buffer());
				out.writeInt(4096);
				out.writeInt(d);
				out.writeInt(player.inventory.currentItem);
				CToSMessage packet = new CToSMessage(out);
				DragonArtifacts.artifactNetworkWrapper.sendToServer(packet);
			}
		}
	}
       return itemStack;
   }
 
Example #14
Source File: MetaTileEntity.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void writeTraitData(MTETrait trait, int internalId, Consumer<PacketBuffer> dataWriter) {
    writeCustomData(-4, buffer -> {
        buffer.writeVarInt(trait.getNetworkID());
        buffer.writeVarInt(internalId);
        dataWriter.accept(buffer);
    });
}
 
Example #15
Source File: AbstractWidgetGroup.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeClientAction(Widget widget, int updateId, Consumer<PacketBuffer> dataWriter) {
    AbstractWidgetGroup.this.writeClientAction(1, buffer -> {
        buffer.writeVarInt(widgets.indexOf(widget));
        buffer.writeVarInt(updateId);
        dataWriter.accept(buffer);
    });
}
 
Example #16
Source File: MessageStopPiloting.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf) {
    PacketBuffer packetBuf = new PacketBuffer(buf);
    packetBuf.writeInt(posToStopPiloting.getX());
    packetBuf.writeInt(posToStopPiloting.getY());
    packetBuf.writeInt(posToStopPiloting.getZ());
    //use absolute coordinates instead of writeBlockPos in case we ever add compatibility with cubic chunks
}
 
Example #17
Source File: MetaTileEntityMultiblockPart.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeInitialSyncData(PacketBuffer buf) {
    super.writeInitialSyncData(buf);
    MultiblockControllerBase controller = getController();
    buf.writeBoolean(controller != null);
    if (controller != null) {
        buf.writeBlockPos(controller.getPos());
    }
}
 
Example #18
Source File: ForgePlayer.java    From FastAsyncWorldedit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void dispatchCUIEvent(CUIEvent event) {
    String[] params = event.getParameters();
    String send = event.getTypeId();
    if (params.length > 0) {
        send = send + "|" + StringUtil.joinString(params, "|");
    }
    PacketBuffer buffer = new PacketBuffer(Unpooled.copiedBuffer(send.getBytes(WECUIPacketHandler.UTF_8_CHARSET)));
    SPacketCustomPayload packet = new SPacketCustomPayload(ForgeWorldEdit.CUI_PLUGIN_CHANNEL, buffer);
    this.player.connection.sendPacket(packet);
}
 
Example #19
Source File: TileEntityPipeBase.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeCoverCustomData(int id, Consumer<PacketBuffer> writer) {
    writeCustomData(-3, buffer -> {
        buffer.writeVarInt(id);
        writer.accept(buffer);
    });
}
 
Example #20
Source File: StructuredDataMaster.java    From OpenModsLib with MIT License 5 votes vote down vote up
private PacketBuffer createElementPayload(Collection<Integer> ids) {
	try {
		PacketBuffer output = new PacketBuffer(Unpooled.buffer());
		for (Integer id : ids) {
			E element = elements.get(id);
			element.writeToStream(output);
		}

		return output;
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example #21
Source File: MetaTileEntityPrimitiveBlastFurnace.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void receiveCustomData(int dataId, PacketBuffer buf) {
    super.receiveCustomData(dataId, buf);
    if (dataId == 100) {
        this.isActive = buf.readBoolean();
        getWorld().checkLight(getPos());
        getHolder().scheduleChunkForRenderUpdate();
    }
}
 
Example #22
Source File: SyncableByteArray.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public void writeToStream(PacketBuffer stream) {
	if (value == null) {
		stream.writeInt(0);
	} else {
		stream.writeByteArray(value);
	}
}
 
Example #23
Source File: DryingRecipe.java    From Survivalist with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void write(PacketBuffer buffer, DryingRecipe recipe)
{
    buffer.writeString(recipe.group);
    recipe.input.write(buffer);
    buffer.writeItemStack(recipe.output);
    buffer.writeVarInt(recipe.time);
}
 
Example #24
Source File: PacketSatellite.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@Override
public void write(ByteBuf outline) {
	PacketBuffer packetBuffer = new PacketBuffer(outline);
	NBTTagCompound nbt = new NBTTagCompound();
	machine.writeToNBT(nbt);
	
	packetBuffer.writeCompoundTag(nbt);
}
 
Example #25
Source File: SyncableUUID.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public void writeToStream(PacketBuffer stream) {
	if (uuid != null) {
		stream.writeBoolean(true);
		stream.writeUniqueId(uuid);
	} else {
		stream.writeBoolean(false);
	}
}
 
Example #26
Source File: MetaTileEntityTank.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void writeInitialSyncData(PacketBuffer buf) {
    super.writeInitialSyncData(buf);
    if (isTankController()) {
        buf.writeBoolean(true);
        ByteBufUtils.writeRelativeBlockList(buf, getPos(), connectedTanks);
        buf.writeBlockPos(new BlockPos(multiblockSize));
        FluidStack fluidStack = multiblockFluidTank.getFluid();
        ByteBufUtils.writeFluidStack(buf, fluidStack);
    } else {
        buf.writeBoolean(false);
        buf.writeBlockPos(controllerPos);
    }
}
 
Example #27
Source File: NetworkHandler.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Packet proxy2packet(FMLProxyPacket packet) {
    PacketBuffer payload = (PacketBuffer) packet.payload();
    Class<Packet> packetClass = (Class<Packet>) packetMap.get(payload.readVarInt());
    PacketCodec<Packet> codec = (PacketCodec<Packet>) codecMap.get(packetClass);
    return codec.decoder.decode(payload);
}
 
Example #28
Source File: SimpleTextWidget.java    From GregTech with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void readUpdateInfo(int id, PacketBuffer buffer) {
    if (id == 1) {
        this.lastText = buffer.readString(Short.MAX_VALUE);
        updateSize();
    }
}
 
Example #29
Source File: CreateRecipe.java    From EnderStorage with MIT License 5 votes vote down vote up
@Override
public void write(PacketBuffer buffer, CreateRecipe recipe) {
    buffer.writeString(recipe.group);

    for (Ingredient ingredient : recipe.input) {
        ingredient.write(buffer);
    }

    buffer.writeItemStack(recipe.output);
}
 
Example #30
Source File: SyncableTank.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public void writeToStream(PacketBuffer stream) {
	if (fluid != null) {
		stream.writeBoolean(true);
		final String id = FluidRegistry.getFluidName(fluid.getFluid());
		stream.writeString(id);
		stream.writeInt(fluid.amount);
		stream.writeCompoundTag(fluid.tag);
	} else {
		stream.writeBoolean(false);
	}
}