us.myles.ViaVersion.api.Pair Java Examples

The following examples show how to use us.myles.ViaVersion.api.Pair. 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: Cooldown.java    From ViaRewind with MIT License 6 votes vote down vote up
public void setAttackSpeed(double base, ArrayList<Pair<Byte, Double>> modifiers) {
	attackSpeed = base;
	for (int j = 0; j<modifiers.size(); j++) {
		if (modifiers.get(j).getKey()==0) {
			attackSpeed += modifiers.get(j).getValue();
			modifiers.remove(j--);
		}
	}
	for (int j = 0; j<modifiers.size(); j++) {
		if (modifiers.get(j).getKey()==1) {
			attackSpeed += base * modifiers.get(j).getValue();
			modifiers.remove(j--);
		}
	}
	for (int j = 0; j<modifiers.size(); j++) {
		if (modifiers.get(j).getKey()==2) {
			attackSpeed *= (1.0 + modifiers.get(j).getValue());
			modifiers.remove(j--);
		}
	}
}
 
Example #2
Source File: BungeeServerHandler.java    From ViaVersion with MIT License 6 votes vote down vote up
@EventHandler(priority = 120)
public void onServerConnect(ServerConnectEvent e) {
    if (e.isCancelled()) {
        return;
    }

    UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
    if (user == null) return;
    if (!user.has(BungeeStorage.class)) {
        user.put(new BungeeStorage(user, e.getPlayer()));
    }

    int protocolId = ProtocolDetectorService.getProtocolId(e.getTarget().getName());
    List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

    // Check if ViaVersion can support that version
    try {
        //Object pendingConnection = getPendingConnection.invoke(e.getPlayer());
        Object handshake = getHandshake.invoke(e.getPlayer().getPendingConnection());
        setProtocol.invoke(handshake, protocols == null ? user.getProtocolInfo().getProtocolVersion() : protocolId);
    } catch (InvocationTargetException | IllegalAccessException e1) {
        e1.printStackTrace();
    }
}
 
Example #3
Source File: VelocityServerHandler.java    From ViaVersion with MIT License 6 votes vote down vote up
@Subscribe
public void preServerConnect(ServerPreConnectEvent e) {
    try {
        UserConnection user = Via.getManager().getConnection(e.getPlayer().getUniqueId());
        if (user == null) return;
        if (!user.has(VelocityStorage.class)) {
            user.put(new VelocityStorage(user, e.getPlayer()));
        }

        int protocolId = ProtocolDetectorService.getProtocolId(e.getOriginalServer().getServerInfo().getName());
        List<Pair<Integer, Protocol>> protocols = ProtocolRegistry.getProtocolPath(user.getProtocolInfo().getProtocolVersion(), protocolId);

        // Check if ViaVersion can support that version
        Object connection = getMinecraftConnection.invoke(e.getPlayer());
        setNextProtocolVersion.invoke(connection, ProtocolVersion.getProtocolVersion(protocols == null
                ? user.getProtocolInfo().getProtocolVersion()
                : protocolId));

    } catch (IllegalAccessException | InvocationTargetException e1) {
        e1.printStackTrace();
    }
}
 
Example #4
Source File: BlockConnectionStorage.java    From ViaVersion with MIT License 6 votes vote down vote up
public void remove(int x, int y, int z) {
    long pair = getChunkSectionIndex(x, y, z);
    Pair<byte[], NibbleArray> map = blockStorage.get(pair);
    if (map == null) return;
    int blockIndex = encodeBlockPos(x, y, z);
    NibbleArray nibbleArray = map.getValue();
    if (nibbleArray != null) {
        nibbleArray.set(blockIndex, 0);
        boolean allZero = true;
        for (int i = 0; i < 4096; i++) {
            if (nibbleArray.get(i) != 0) {
                allZero = false;
                break;
            }
        }
        if (allZero) map.setValue(null);
    }
    map.getKey()[blockIndex] = 0;
    for (short entry : map.getKey()) {
        if (entry != 0) return;
    }
    blockStorage.remove(pair);
}
 
Example #5
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 6 votes vote down vote up
/**
 * Calculate a path from a client version to server version.
 *
 * @param clientVersion The input client version
 * @param serverVersion The desired output server version
 * @return The path it generated, null if it failed.
 */
@Nullable
public static List<Pair<Integer, Protocol>> getProtocolPath(int clientVersion, int serverVersion) {
    Pair<Integer, Integer> protocolKey = new Pair<>(clientVersion, serverVersion);
    // Check cache
    List<Pair<Integer, Protocol>> protocolList = pathCache.get(protocolKey);
    if (protocolList != null) {
        return protocolList;
    }
    // Generate path
    List<Pair<Integer, Protocol>> outputPath = getProtocolPath(new ArrayList<>(), clientVersion, serverVersion);
    // If it found a path, cache it.
    if (outputPath != null) {
        pathCache.put(protocolKey, outputPath);
    }
    return outputPath;
}
 
Example #6
Source File: SnowyGrassConnectionHandler.java    From ViaVersion with MIT License 6 votes vote down vote up
static ConnectionData.ConnectorInitAction init() {
    final Set<String> snowyGrassBlocks = new HashSet<>();
    snowyGrassBlocks.add("minecraft:grass_block");
    snowyGrassBlocks.add("minecraft:podzol");
    snowyGrassBlocks.add("minecraft:mycelium");

    final SnowyGrassConnectionHandler handler = new SnowyGrassConnectionHandler();
    return blockData -> {
        if (snowyGrassBlocks.contains(blockData.getMinecraftKey())) {
            ConnectionData.connectionHandlerMap.put(blockData.getSavedBlockStateId(), handler);
            blockData.set("snowy", "true");
            grassBlocks.put(new Pair<>(blockData.getSavedBlockStateId(), true), blockData.getBlockStateId());
            blockData.set("snowy", "false");
            grassBlocks.put(new Pair<>(blockData.getSavedBlockStateId(), false), blockData.getBlockStateId());
        }
        if (blockData.getMinecraftKey().equals("minecraft:snow") || blockData.getMinecraftKey().equals("minecraft:snow_block")) {
            ConnectionData.connectionHandlerMap.put(blockData.getSavedBlockStateId(), handler);
            snows.add(blockData.getSavedBlockStateId());
        }
    };
}
 
Example #7
Source File: CommandBlockStorage.java    From ViaVersion with MIT License 6 votes vote down vote up
public Optional<CompoundTag> getCommandBlock(Position position) {
    Pair<Integer, Integer> chunkCoords = getChunkCoords(position);

    Map<Position, CompoundTag> blocks = storedCommandBlocks.get(chunkCoords);
    if (blocks == null)
        return Optional.empty();

    CompoundTag tag = blocks.get(position);
    if (tag == null)
        return Optional.empty();

    tag = tag.clone();
    tag.put(new ByteTag("powered", (byte) 0));
    tag.put(new ByteTag("auto", (byte) 0));
    tag.put(new ByteTag("conditionMet", (byte) 0));
    return Optional.of(tag);
}
 
Example #8
Source File: MetaIndex1_8to1_9.java    From ViaRewind with MIT License 5 votes vote down vote up
private static Optional<MetaIndex> getIndex(Entity1_10Types.EntityType type, int index) {
	Pair pair = new Pair<>(type, index);
	if (metadataRewrites.containsKey(pair)) {
		return Optional.of(metadataRewrites.get(pair));
	}

	return Optional.empty();
}
 
Example #9
Source File: FlowerPotHandler.java    From ViaBackwards with MIT License 5 votes vote down vote up
@Override
public CompoundTag transform(UserConnection user, int blockId, CompoundTag tag) {
    Pair<String, Byte> item = getOrDefault(blockId);

    tag.put(new StringTag("Item", item.getKey()));
    tag.put(new IntTag("Data", item.getValue()));

    return tag;
}
 
Example #10
Source File: BlockConnectionStorage.java    From ViaVersion with MIT License 5 votes vote down vote up
private Pair<byte[], NibbleArray> getChunkSection(long index, boolean requireNibbleArray) {
    Pair<byte[], NibbleArray> map = blockStorage.get(index);
    if (map == null) {
        map = new Pair<>(new byte[4096], null);
        blockStorage.put(index, map);
    }
    if (map.getValue() == null && requireNibbleArray) {
        map.setValue(new NibbleArray(4096));
    }
    return map;
}
 
Example #11
Source File: BlockConnectionStorage.java    From ViaVersion with MIT License 5 votes vote down vote up
public int get(int x, int y, int z) {
    long pair = getChunkSectionIndex(x, y, z);
    Pair<byte[], NibbleArray> map = blockStorage.get(pair);
    if (map == null) return 0;
    short blockPosition = encodeBlockPos(x, y, z);
    NibbleArray nibbleArray = map.getValue();
    return WorldPackets.toNewId(
            ((map.getKey()[blockPosition] & 0xFF) << 4)
                    | (nibbleArray == null ? 0 : nibbleArray.get(blockPosition))
    );
}
 
Example #12
Source File: BlockConnectionStorage.java    From ViaVersion with MIT License 5 votes vote down vote up
public void store(int x, int y, int z, int blockState) {
    short mapping = REVERSE_BLOCK_MAPPINGS[blockState];
    if (mapping == -1) return;

    blockState = mapping;
    long pair = getChunkSectionIndex(x, y, z);
    Pair<byte[], NibbleArray> map = getChunkSection(pair, (blockState & 0xF) != 0);
    int blockIndex = encodeBlockPos(x, y, z);
    map.getKey()[blockIndex] = (byte) (blockState >> 4);
    NibbleArray nibbleArray = map.getValue();
    if (nibbleArray != null) {
        nibbleArray.set(blockIndex, blockState);
    }
}
 
Example #13
Source File: SnowyGrassConnectionHandler.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public int connect(UserConnection user, Position position, int blockState) {
    int blockUpId = getBlockData(user, position.getRelative(BlockFace.TOP));
    Integer newId = grassBlocks.get(new Pair<>(blockState, snows.contains(blockUpId)));
    if (newId != null) {
        return newId;
    }
    return blockState;
}
 
Example #14
Source File: FlowerPotHandler.java    From ViaVersion with MIT License 5 votes vote down vote up
@Override
public int transform(UserConnection user, CompoundTag tag) {
    Object item = tag.contains("Item") ? tag.get("Item").getValue() : null;
    Object data = tag.contains("Data") ? tag.get("Data").getValue() : null;

    // Convert item to String without namespace or to Byte
    if (item instanceof String) {
        item = ((String) item).replace("minecraft:", "");
    } else if (item instanceof Number) {
        item = ((Number) item).byteValue();
    } else {
        item = (byte) 0;
    }

    // Convert data to Byte
    if (data instanceof Number) {
        data = ((Number) data).byteValue();
    } else {
        data = (byte) 0;
    }

    Integer flower = flowers.get(new Pair<>(item, (byte) data));
    if (flower != null) return flower;
    flower = flowers.get(new Pair<>(item, (byte) 0));
    if (flower != null) return flower;

    return 5265; // Fallback to empty pot
}
 
Example #15
Source File: CommandBlockStorage.java    From ViaVersion with MIT License 5 votes vote down vote up
public void addOrUpdateBlock(Position position, CompoundTag tag) {
    Pair<Integer, Integer> chunkPos = getChunkCoords(position);

    if (!storedCommandBlocks.containsKey(chunkPos))
        storedCommandBlocks.put(chunkPos, new ConcurrentHashMap<>());

    Map<Position, CompoundTag> blocks = storedCommandBlocks.get(chunkPos);

    if (blocks.containsKey(position))
        if (blocks.get(position).equals(tag))
            return;

    blocks.put(position, tag);
}
 
Example #16
Source File: PacketRemapper.java    From ViaVersion with MIT License 5 votes vote down vote up
/**
 * Remap a packet wrapper
 *
 * @param packetWrapper The wrapper to remap
 * @throws Exception Throws if it fails to write / read to the packet.
 */
public void remap(PacketWrapper packetWrapper) throws Exception {
    try {
        // Read all the current values
        for (Pair<ValueReader, ValueWriter> valueRemapper : valueRemappers) {
            Object object = valueRemapper.getKey().read(packetWrapper);
            // Convert object to write type :O!!!
            valueRemapper.getValue().write(packetWrapper, object);
        }
        // If we had handlers we'd put them here
    } catch (InformativeException e) {
        e.addSource(this.getClass());
        throw e;
    }
}
 
Example #17
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 5 votes vote down vote up
public static boolean isBaseProtocol(Protocol protocol) {
    for (Pair<Range<Integer>, Protocol> p : baseProtocols) {
        if (p.getValue() == protocol) {
            return true;
        }
    }
    return false;
}
 
Example #18
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 5 votes vote down vote up
public static Protocol getBaseProtocol(int serverVersion) {
    for (Pair<Range<Integer>, Protocol> rangeProtocol : Lists.reverse(baseProtocols)) {
        if (rangeProtocol.getKey().contains(serverVersion)) {
            return rangeProtocol.getValue();
        }
    }
    throw new IllegalStateException("No Base Protocol for " + serverVersion);
}
 
Example #19
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 5 votes vote down vote up
public static void refreshVersions() {
    supportedVersions.clear();

    supportedVersions.add(ProtocolRegistry.SERVER_PROTOCOL);
    for (ProtocolVersion versions : ProtocolVersion.getProtocols()) {
        List<Pair<Integer, Protocol>> paths = getProtocolPath(versions.getId(), ProtocolRegistry.SERVER_PROTOCOL);
        if (paths == null) continue;
        supportedVersions.add(versions.getId());
        for (Pair<Integer, Protocol> path : paths) {
            supportedVersions.add(path.getKey());
        }
    }
}
 
Example #20
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 5 votes vote down vote up
/**
 * Registers a base protocol.
 * Base Protocols registered later have higher priority
 * Only one base protocol will be added to pipeline
 *
 * @param baseProtocol       Base Protocol to register
 * @param supportedProtocols Versions that baseProtocol supports
 */
public static void registerBaseProtocol(Protocol baseProtocol, Range<Integer> supportedProtocols) {
    baseProtocols.add(new Pair<>(supportedProtocols, baseProtocol));
    if (Via.getPlatform().isPluginEnabled()) {
        baseProtocol.register(Via.getManager().getProviders());
        refreshVersions();
    } else {
        registerList.add(baseProtocol);
    }
}
 
Example #21
Source File: MetaIndex1_7_6_10to1_8.java    From ViaRewind with MIT License 5 votes vote down vote up
private static Optional<MetaIndex1_8to1_7_6_10> getIndex(Entity1_10Types.EntityType type, int index) {
	Pair pair = new Pair<>(type, index);
	if (metadataRewrites.containsKey(pair)) {
		return Optional.of(metadataRewrites.get(pair));
	}

	return Optional.empty();
}
 
Example #22
Source File: CommandBlockStorage.java    From ViaVersion with MIT License 4 votes vote down vote up
public void unloadChunk(int x, int z) {
    Pair<Integer, Integer> chunkPos = new Pair<>(x, z);
    storedCommandBlocks.remove(chunkPos);
}
 
Example #23
Source File: CommandBlockStorage.java    From ViaVersion with MIT License 4 votes vote down vote up
private Pair<Integer, Integer> getChunkCoords(Position position) {
    int chunkX = Math.floorDiv(position.getX(), 16);
    int chunkZ = Math.floorDiv(position.getZ(), 16);

    return new Pair<>(chunkX, chunkZ);
}
 
Example #24
Source File: BaseProtocol.java    From ViaVersion with MIT License 4 votes vote down vote up
@Override
protected void registerPackets() {
    /* Incoming Packets */

    // Handshake Packet
    registerIncoming(State.HANDSHAKE, 0x00, 0x00, new PacketRemapper() {
        @Override
        public void registerMap() {
            // select right protocol
            map(Type.VAR_INT); // 0 - Client Protocol Version
            map(Type.STRING); // 1 - Server Address
            map(Type.UNSIGNED_SHORT); // 2 - Server Port
            map(Type.VAR_INT); // 3 - Next State
            handler(new PacketHandler() {
                @Override
                public void handle(PacketWrapper wrapper) throws Exception {
                    int protVer = wrapper.get(Type.VAR_INT, 0);
                    int state = wrapper.get(Type.VAR_INT, 1);

                    ProtocolInfo info = wrapper.user().getProtocolInfo();
                    info.setProtocolVersion(protVer);
                    // Ensure the server has a version provider
                    if (Via.getManager().getProviders().get(VersionProvider.class) == null) {
                        wrapper.user().setActive(false);
                        return;
                    }
                    // Choose the pipe
                    int protocol = Via.getManager().getProviders().get(VersionProvider.class).getServerProtocol(wrapper.user());
                    info.setServerProtocolVersion(protocol);
                    List<Pair<Integer, Protocol>> protocols = null;

                    // Only allow newer clients or (1.9.2 on 1.9.4 server if the server supports it)
                    if (info.getProtocolVersion() >= protocol || Via.getPlatform().isOldClientsAllowed()) {
                        protocols = ProtocolRegistry.getProtocolPath(info.getProtocolVersion(), protocol);
                    }

                    ProtocolPipeline pipeline = wrapper.user().getProtocolInfo().getPipeline();
                    if (protocols != null) {
                        for (Pair<Integer, Protocol> prot : protocols) {
                            pipeline.add(prot.getValue());
                            // Ensure mapping data has already been loaded
                            ProtocolRegistry.completeMappingDataLoading(prot.getValue().getClass());
                        }
                        wrapper.set(Type.VAR_INT, 0, protocol);
                    }

                    // Add Base Protocol
                    pipeline.add(ProtocolRegistry.getBaseProtocol(protocol));

                    // Change state
                    if (state == 1) {
                        info.setState(State.STATUS);
                    }
                    if (state == 2) {
                        info.setState(State.LOGIN);
                    }
                }
            });
        }
    });
}
 
Example #25
Source File: FlowerPotHandler.java    From ViaVersion with MIT License 4 votes vote down vote up
public static void register(String identifier, byte numbericBlockId, byte blockData, int newId) {
    flowers.put(new Pair<>(identifier, blockData), newId);
    flowers.put(new Pair<>(numbericBlockId, blockData), newId);
}
 
Example #26
Source File: ProtocolRegistry.java    From ViaVersion with MIT License 4 votes vote down vote up
/**
 * Calculate a path to get from an input protocol to the servers protocol.
 *
 * @param current       The current items in the path
 * @param clientVersion The current input version
 * @param serverVersion The desired output version
 * @return The path which has been generated, null if failed.
 */
@Nullable
private static List<Pair<Integer, Protocol>> getProtocolPath(List<Pair<Integer, Protocol>> current, int clientVersion, int serverVersion) {
    if (clientVersion == serverVersion) return null; // We're already there
    if (current.size() > 50) return null; // Fail safe, protocol too complicated.

    // First check if there is any protocols for this
    Int2ObjectMap<Protocol> inputMap = registryMap.get(clientVersion);
    if (inputMap == null) {
        return null; // Not supported
    }

    // Next check there isn't an obvious path
    Protocol protocol = inputMap.get(serverVersion);
    if (protocol != null) {
        current.add(new Pair<>(serverVersion, protocol));
        return current; // Easy solution
    }

    // There might be a more advanced solution... So we'll see if any of the others can get us there
    List<Pair<Integer, Protocol>> shortest = null;
    for (Int2ObjectMap.Entry<Protocol> entry : inputMap.int2ObjectEntrySet()) {
        // Ensure it wasn't caught by the other loop
        if (entry.getIntKey() == (serverVersion)) continue;

        Pair<Integer, Protocol> pair = new Pair<>(entry.getIntKey(), entry.getValue());
        // Ensure no recursion
        if (current.contains(pair)) continue;

        // Create a copy
        List<Pair<Integer, Protocol>> newCurrent = new ArrayList<>(current);
        newCurrent.add(pair);
        // Calculate the rest of the protocol using the current
        newCurrent = getProtocolPath(newCurrent, entry.getKey(), serverVersion);
        if (newCurrent != null) {
            // If it's shorter then choose it
            if (shortest == null || shortest.size() > newCurrent.size()) {
                shortest = newCurrent;
            }
        }
    }

    return shortest; // null if none found
}
 
Example #27
Source File: FlowerPotHandler.java    From ViaBackwards with MIT License 4 votes vote down vote up
private static void register(int id, String identifier, byte data) {
    FLOWERS.put(id, new Pair<>(identifier, data));
}
 
Example #28
Source File: FlowerPotHandler.java    From ViaBackwards with MIT License 4 votes vote down vote up
public Pair<String, Byte> getOrDefault(int blockId) {
    Pair<String, Byte> pair = FLOWERS.get(blockId);
    return pair != null ? pair : AIR;
}
 
Example #29
Source File: PacketRemapper.java    From ViaVersion with MIT License 2 votes vote down vote up
/**
 * Map a type using a basic ValueReader to a ValueWriter
 *
 * @param inputReader  The reader to read with.
 * @param outputWriter The writer to write with
 * @param <T>          The return type
 */
public <T> void map(ValueReader<T> inputReader, ValueWriter<T> outputWriter) {
    valueRemappers.add(new Pair<>(inputReader, outputWriter));
}