cleanup code, avoid some deprecated methods, fix dedicated server packet sending and class not found

This commit is contained in:
creeper123123321 2019-03-16 17:16:13 -03:00
parent 407d66b313
commit e25b39e3f3
No known key found for this signature in database
GPG Key ID: 0AC57D54786721D1
26 changed files with 567 additions and 672 deletions

View File

@ -42,11 +42,13 @@ dependencies {
shade("de.gerrygames:viarewind-core:1.4.0") { transitive = false } shade("de.gerrygames:viarewind-core:1.4.0") { transitive = false }
shade("nl.matsv:viabackwards-core:3.0.0-19w11b") { transitive = false } shade("nl.matsv:viabackwards-core:3.0.0-19w11b") { transitive = false }
compileOnly 'com.google.code.findbugs:jsr305:3.0.2'
minecraft "com.mojang:minecraft:19w11b" minecraft "com.mojang:minecraft:19w11b"
mappings "net.fabricmc:yarn:19w11b.2" mappings "net.fabricmc:yarn:19w11b.4"
modCompile "net.fabricmc:fabric-loader:0.3.7.109" modCompile "net.fabricmc:fabric-loader:0.3.7.109"
modCompile "net.fabricmc:fabric:0.2.3.110" modCompile "net.fabricmc:fabric:0.2.3.111"
} }
jar { jar {

View File

@ -39,7 +39,7 @@ import io.netty.channel.EventLoop;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.registry.CommandRegistry; import net.fabricmc.fabric.api.registry.CommandRegistry;
import net.fabricmc.loader.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.command.CommandSource; import net.minecraft.server.command.CommandSource;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import us.myles.ViaVersion.ViaManager; import us.myles.ViaVersion.ViaManager;
@ -66,10 +66,21 @@ public class ViaFabric implements ModInitializer {
} }
public static String getVersion() { public static String getVersion() {
return FabricLoader.INSTANCE.getModContainer("viafabric") return FabricLoader.getInstance().getModContainer("viafabric")
.get().getMetadata().getVersion().getFriendlyString(); .get().getMetadata().getVersion().getFriendlyString();
} }
private static <S extends CommandSource> LiteralArgumentBuilder<S> command(String commandName) {
return LiteralArgumentBuilder.<S>literal(commandName)
.then(
RequiredArgumentBuilder
.<S, String>argument("args", StringArgumentType.greedyString())
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute)
.suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion)
)
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute);
}
@Override @Override
public void onInitialize() { public void onInitialize() {
Via.init(ViaManager.builder() Via.init(ViaManager.builder()
@ -83,7 +94,7 @@ public class ViaFabric implements ModInitializer {
new VRRewindPlatform().init(); new VRRewindPlatform().init();
new VRBackwardsPlatform().init(); new VRBackwardsPlatform().init();
if (FabricLoader.INSTANCE.getEnvironmentType() == EnvType.CLIENT) { if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
try { try {
Class.forName("io.github.cottonmc.clientcommands.ClientCommands") Class.forName("io.github.cottonmc.clientcommands.ClientCommands")
.getMethod("registerCommand", Consumer.class) .getMethod("registerCommand", Consumer.class)
@ -105,15 +116,4 @@ public class ViaFabric implements ModInitializer {
Via.getPlatform().getLogger().warning("Fabric API isn't installed"); Via.getPlatform().getLogger().warning("Fabric API isn't installed");
} }
} }
private static <S extends CommandSource> LiteralArgumentBuilder<S> command(String commandName) {
return LiteralArgumentBuilder.<S>literal(commandName)
.then(
RequiredArgumentBuilder
.<S, String>argument("args", StringArgumentType.greedyString())
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute)
.suggests(((VRCommandHandler) Via.getManager().getCommandHandler())::suggestion)
)
.executes(((VRCommandHandler) Via.getManager().getCommandHandler())::execute);
}
} }

View File

@ -25,7 +25,8 @@
package com.github.creeper123123321.viafabric.commands; package com.github.creeper123123321.viafabric.commands;
import net.fabricmc.api.EnvType; import net.fabricmc.api.EnvType;
import net.fabricmc.loader.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientCommandSource; import net.minecraft.client.network.ClientCommandSource;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.server.command.CommandSource; import net.minecraft.server.command.CommandSource;
@ -53,8 +54,8 @@ public class NMSCommandSender implements ViaCommandSender {
public void sendMessage(String s) { public void sendMessage(String s) {
if (source instanceof ServerCommandSource) { if (source instanceof ServerCommandSource) {
((ServerCommandSource) source).sendFeedback(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s)), false); ((ServerCommandSource) source).sendFeedback(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s)), false);
} else if (FabricLoader.INSTANCE.getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) { } else if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) {
FabricLoader.INSTANCE.getEnvironmentHandler().getClientPlayer() MinecraftClient.getInstance().player
.appendCommandFeedback(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s))); .appendCommandFeedback(TextComponent.Serializer.fromJsonString(ChatRewriter.legacyTextToJson(s)));
} }
} }
@ -64,8 +65,8 @@ public class NMSCommandSender implements ViaCommandSender {
if (source instanceof ServerCommandSource) { if (source instanceof ServerCommandSource) {
Entity entity = ((ServerCommandSource) source).getEntity(); Entity entity = ((ServerCommandSource) source).getEntity();
if (entity != null) return entity.getUuid(); if (entity != null) return entity.getUuid();
} else if (FabricLoader.INSTANCE.getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) { } else if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) {
return FabricLoader.INSTANCE.getEnvironmentHandler().getClientPlayer().getUuid(); return MinecraftClient.getInstance().player.getUuid();
} }
return UUID.fromString(getName()); return UUID.fromString(getName());
} }
@ -74,8 +75,8 @@ public class NMSCommandSender implements ViaCommandSender {
public String getName() { public String getName() {
if (source instanceof ServerCommandSource) { if (source instanceof ServerCommandSource) {
return ((ServerCommandSource) source).getName(); return ((ServerCommandSource) source).getName();
} else if (FabricLoader.INSTANCE.getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) { } else if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT && source instanceof ClientCommandSource) {
return FabricLoader.INSTANCE.getEnvironmentHandler().getClientPlayer().getEntityName(); return MinecraftClient.getInstance().player.getEntityName();
} }
return "?"; return "?";
} }

View File

@ -30,7 +30,6 @@ import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.suggestion.Suggestions; import com.mojang.brigadier.suggestion.Suggestions;
import com.mojang.brigadier.suggestion.SuggestionsBuilder; import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import net.minecraft.server.command.CommandSource; import net.minecraft.server.command.CommandSource;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.commands.ViaCommandHandler; import us.myles.ViaVersion.commands.ViaCommandHandler;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -50,12 +49,10 @@ public class VRCommandHandler extends ViaCommandHandler {
args = StringArgumentType.getString(ctx, "args").split(" "); args = StringArgumentType.getString(ctx, "args").split(" ");
} catch (IllegalArgumentException ignored) { } catch (IllegalArgumentException ignored) {
} }
Via.getManager() onCommand(
.getCommandHandler() new NMSCommandSender(ctx.getSource()),
.onCommand( args
new NMSCommandSender(ctx.getSource()), );
args
);
return 1; return 1;
} }

View File

@ -51,7 +51,7 @@ public class LeakDetectSubCommand extends ViaSubCommand {
ResourceLeakDetector.setLevel(level); ResourceLeakDetector.setLevel(level);
viaCommandSender.sendMessage("Set leak detector level to " + level); viaCommandSender.sendMessage("Set leak detector level to " + level);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
viaCommandSender.sendMessage("Invalid level (" + Arrays.toString(ResourceLeakDetector.Level.values()) +")"); viaCommandSender.sendMessage("Invalid level (" + Arrays.toString(ResourceLeakDetector.Level.values()) + ")");
} }
} else { } else {
viaCommandSender.sendMessage("Current leak detection level is " + ResourceLeakDetector.getLevel()); viaCommandSender.sendMessage("Current leak detection level is " + ResourceLeakDetector.getLevel());

View File

@ -37,7 +37,6 @@ import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.util.PipelineUtil; import us.myles.ViaVersion.util.PipelineUtil;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class VRDecodeHandler extends ByteToMessageDecoder { public class VRDecodeHandler extends ByteToMessageDecoder {
@ -100,13 +99,11 @@ public class VRDecodeHandler extends ByteToMessageDecoder {
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//try (AutoCloseable ignored = user.createTaskListAndRunOnClose()) { super.channelRead(ctx, msg);
super.channelRead(ctx, msg);
//}
} }
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) {
ProtocolInfo info = user.get(ProtocolInfo.class); ProtocolInfo info = user.get(ProtocolInfo.class);
if (info.getUuid() != null) { if (info.getUuid() != null) {
Via.getManager().removePortedClient(info.getUuid()); Via.getManager().removePortedClient(info.getUuid());

View File

@ -37,7 +37,6 @@ import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.util.PipelineUtil; import us.myles.ViaVersion.util.PipelineUtil;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class VREncodeHandler extends MessageToByteEncoder { public class VREncodeHandler extends MessageToByteEncoder {
private UserConnection user; private UserConnection user;
@ -110,8 +109,6 @@ public class VREncodeHandler extends MessageToByteEncoder {
@Override @Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
//try (AutoCloseable ignored = user.createTaskListAndRunOnClose()) { super.write(ctx, msg, promise);
super.write(ctx, msg, promise);
//}
} }
} }

View File

@ -113,7 +113,7 @@ public class FabricDecodeHandler extends ByteToMessageDecoder {
} }
@Override @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { public void channelInactive(ChannelHandlerContext ctx) {
ProtocolInfo pi = info.get(ProtocolInfo.class); ProtocolInfo pi = info.get(ProtocolInfo.class);
if (pi.getUuid() != null) { if (pi.getUuid() != null) {
Via.getManager().removePortedClient(pi.getUuid()); Via.getManager().removePortedClient(pi.getUuid());

View File

@ -28,7 +28,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; import io.netty.handler.codec.MessageToByteEncoder;
import us.myles.ViaVersion.api.PacketWrapper; import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.Via;
import us.myles.ViaVersion.api.data.UserConnection; import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.api.type.Type; import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.exception.CancelException; import us.myles.ViaVersion.exception.CancelException;

View File

@ -29,7 +29,6 @@ import com.github.creeper123123321.viafabric.util.VersionFormatFilter;
import net.minecraft.client.gui.Screen; import net.minecraft.client.gui.Screen;
import net.minecraft.client.gui.menu.MultiplayerScreen; import net.minecraft.client.gui.menu.MultiplayerScreen;
import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.resource.language.I18n;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Inject;

View File

@ -45,11 +45,11 @@ public class VRInjector implements ViaInjector {
@Override @Override
public String getEncoderName() { public String getEncoderName() {
throw new UnsupportedOperationException(); return "encoder";
} }
@Override @Override
public String getDecoderName() { public String getDecoderName() {
throw new UnsupportedOperationException(); return "decoder";
} }
} }

View File

@ -29,8 +29,11 @@ import com.github.creeper123123321.viafabric.commands.NMSCommandSender;
import com.github.creeper123123321.viafabric.commands.UserCommandSender; import com.github.creeper123123321.viafabric.commands.UserCommandSender;
import com.github.creeper123123321.viafabric.protocol.ClientSideReference; import com.github.creeper123123321.viafabric.protocol.ClientSideReference;
import com.github.creeper123123321.viafabric.util.FutureTaskId; import com.github.creeper123123321.viafabric.util.FutureTaskId;
import net.fabricmc.loader.FabricLoader; import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.loader.ModContainer; import net.fabricmc.loader.ModContainer;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.entity.Entity; import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.server.network.ServerPlayerEntity;
@ -53,6 +56,7 @@ import us.myles.ViaVersion.sponge.VersionInfo;
import us.myles.ViaVersion.util.GsonUtil; import us.myles.ViaVersion.util.GsonUtil;
import us.myles.viaversion.libs.gson.JsonObject; import us.myles.viaversion.libs.gson.JsonObject;
import javax.annotation.Nullable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -63,7 +67,21 @@ import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class VRPlatform implements ViaPlatform { public class VRPlatform implements ViaPlatform {
private VRViaConfig config = new VRViaConfig(FabricLoader.INSTANCE.getConfigDirectory().toPath().resolve("ViaFabric").resolve("viaversion.yml").toFile()); private VRViaConfig config = new VRViaConfig(FabricLoader.getInstance().getConfigDirectory().toPath().resolve("ViaFabric").resolve("viaversion.yml").toFile());
@Nullable
public static MinecraftServer getServer() {
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT) {
return getIntegratedServer();
}
return (MinecraftServer) FabricLoader.getInstance().getGameInstance();
}
@Environment(EnvType.CLIENT)
@Nullable
private static MinecraftServer getIntegratedServer() {
return MinecraftClient.getInstance().getServer();
}
@Override @Override
public Logger getLogger() { public Logger getLogger() {
@ -106,7 +124,7 @@ public class VRPlatform implements ViaPlatform {
// Kick task needs to be on main thread // Kick task needs to be on main thread
Executor executor = ViaFabric.EVENT_LOOP; Executor executor = ViaFabric.EVENT_LOOP;
boolean alreadyLogged; boolean alreadyLogged;
MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); MinecraftServer server = getServer();
if (server != null) { if (server != null) {
alreadyLogged = true; alreadyLogged = true;
executor = server; executor = server;
@ -161,7 +179,7 @@ public class VRPlatform implements ViaPlatform {
@Override @Override
public ViaCommandSender[] getOnlinePlayers() { public ViaCommandSender[] getOnlinePlayers() {
MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); MinecraftServer server = getServer();
if (server != null && server.method_18854()) { if (server != null && server.method_18854()) {
// Not thread safe // Not thread safe
return server.getPlayerManager().getPlayerList().stream() return server.getPlayerManager().getPlayerList().stream()
@ -190,7 +208,7 @@ public class VRPlatform implements ViaPlatform {
} }
} else { } else {
runSync(() -> { runSync(() -> {
MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); MinecraftServer server = getServer();
if (server == null) return; if (server == null) return;
ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid);
if (player == null) return; if (player == null) return;
@ -212,7 +230,7 @@ public class VRPlatform implements ViaPlatform {
e.printStackTrace(); e.printStackTrace();
} }
} else { } else {
MinecraftServer server = FabricLoader.INSTANCE.getEnvironmentHandler().getServerInstance(); MinecraftServer server = getServer();
if (server != null && server.method_18854()) { if (server != null && server.method_18854()) {
ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid); ServerPlayerEntity player = server.getPlayerManager().getPlayer(uuid);
if (player == null) return false; if (player == null) return false;
@ -251,7 +269,7 @@ public class VRPlatform implements ViaPlatform {
public JsonObject getDump() { public JsonObject getDump() {
JsonObject platformSpecific = new JsonObject(); JsonObject platformSpecific = new JsonObject();
List<PluginInfo> mods = new ArrayList<>(); List<PluginInfo> mods = new ArrayList<>();
for (ModContainer mod : FabricLoader.INSTANCE.getModContainers()) { for (ModContainer mod : net.fabricmc.loader.FabricLoader.INSTANCE.getModContainers()) {
mods.add(new PluginInfo(true, mods.add(new PluginInfo(true,
mod.getMetadata().getName(), mod.getMetadata().getName(),
mod.getMetadata().getVersion().getFriendlyString(), mod.getMetadata().getVersion().getFriendlyString(),
@ -270,5 +288,4 @@ public class VRPlatform implements ViaPlatform {
public boolean isOldClientsAllowed() { public boolean isOldClientsAllowed() {
return true; return true;
} }
} }

View File

@ -28,12 +28,12 @@ import com.github.creeper123123321.viafabric.ViaFabric;
import de.gerrygames.viarewind.api.ViaRewindConfig; import de.gerrygames.viarewind.api.ViaRewindConfig;
import de.gerrygames.viarewind.api.ViaRewindConfigImpl; import de.gerrygames.viarewind.api.ViaRewindConfigImpl;
import de.gerrygames.viarewind.api.ViaRewindPlatform; import de.gerrygames.viarewind.api.ViaRewindPlatform;
import net.fabricmc.loader.FabricLoader; import net.fabricmc.loader.api.FabricLoader;
import java.util.logging.Logger; import java.util.logging.Logger;
public class VRRewindPlatform implements ViaRewindPlatform { public class VRRewindPlatform implements ViaRewindPlatform {
private static ViaRewindConfig config = new ViaRewindConfigImpl(FabricLoader.INSTANCE.getConfigDirectory().toPath().resolve("ViaFabric").resolve("viarewind.yml").toFile()); private static ViaRewindConfig config = new ViaRewindConfigImpl(FabricLoader.getInstance().getConfigDirectory().toPath().resolve("ViaFabric").resolve("viarewind.yml").toFile());
public void init() { public void init() {
init(config); init(config);

View File

@ -46,14 +46,15 @@ public class VRViaAPI implements ViaAPI<Void> {
@Override @Override
public int getPlayerVersion(UUID uuid) { public int getPlayerVersion(UUID uuid) {
if (!isPorted(uuid)) { UserConnection con = Via.getManager().getPortedPlayers().get(uuid);
try { if (con != null) {
return Via.getManager().getInjector().getServerProtocolVersion(); return con.get(ProtocolInfo.class).getProtocolVersion();
} catch (Exception e) { }
e.printStackTrace(); try {
} return Via.getManager().getInjector().getServerProtocolVersion();
} catch (Exception e) {
throw new AssertionError(e);
} }
return Via.getManager().getPortedPlayers().get(uuid).get(ProtocolInfo.class).getProtocolVersion();
} }
@Override @Override

View File

@ -35,46 +35,46 @@ import us.myles.ViaVersion.packets.State;
// Based on https://github.com/Gerrygames/ClientViaVersion // Based on https://github.com/Gerrygames/ClientViaVersion
public class Protocol1_7_6_10to1_7_1_5 extends Protocol { public class Protocol1_7_6_10to1_7_1_5 extends Protocol {
public static final ValueTransformer<String, String> INSERT_DASHES = new ValueTransformer<String, String>(Type.STRING) { public static final ValueTransformer<String, String> INSERT_DASHES = new ValueTransformer<String, String>(Type.STRING) {
@Override @Override
public String transform(PacketWrapper packetWrapper, String s) { public String transform(PacketWrapper packetWrapper, String s) {
StringBuilder builder = new StringBuilder(s); StringBuilder builder = new StringBuilder(s);
builder.insert(20, "-"); builder.insert(20, "-");
builder.insert(16, "-"); builder.insert(16, "-");
builder.insert(12, "-"); builder.insert(12, "-");
builder.insert(8, "-"); builder.insert(8, "-");
return builder.toString(); return builder.toString();
} }
}; };
@Override @Override
protected void registerPackets() { protected void registerPackets() {
//Login Success //Login Success
this.registerOutgoing(State.LOGIN, 0x02, 0x02, new PacketRemapper() { this.registerOutgoing(State.LOGIN, 0x02, 0x02, new PacketRemapper() {
@Override @Override
public void registerMap() { public void registerMap() {
map(Type.STRING, INSERT_DASHES); map(Type.STRING, INSERT_DASHES);
} }
}); });
//Spawn Player //Spawn Player
this.registerOutgoing(State.PLAY, 0x0C, 0x0C, new PacketRemapper() { this.registerOutgoing(State.PLAY, 0x0C, 0x0C, new PacketRemapper() {
@Override @Override
public void registerMap() { public void registerMap() {
map(Type.VAR_INT); map(Type.VAR_INT);
map(Type.STRING, INSERT_DASHES); map(Type.STRING, INSERT_DASHES);
map(Type.STRING); map(Type.STRING);
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.VAR_INT, 0); packetWrapper.write(Type.VAR_INT, 0);
} }
}); });
} }
}); });
} }
@Override @Override
public void init(UserConnection userConnection) { public void init(UserConnection userConnection) {
} }
} }

View File

@ -57,12 +57,48 @@ import java.util.UUID;
// Based on https://github.com/Gerrygames/ClientViaVersion // Based on https://github.com/Gerrygames/ClientViaVersion
public class Protocol1_8TO1_7_6_10 extends Protocol { public class Protocol1_8TO1_7_6_10 extends Protocol {
private static ValueReader xyzToPosition = (ValueReader<Position>) packetWrapper -> { private static ValueReader<Position> xyzToPosition = packetWrapper -> {
long x = packetWrapper.read(Type.INT); long x = packetWrapper.read(Type.INT);
long y = packetWrapper.read(Type.INT); long y = packetWrapper.read(Type.INT);
long z = packetWrapper.read(Type.INT); long z = packetWrapper.read(Type.INT);
return new Position(x, y, z); return new Position(x, y, z);
}; };
private static ArrayList<Integer> placeable = new ArrayList<>();
static {
placeable.add(6);
placeable.add(27);
placeable.add(28);
placeable.add(30);
placeable.add(31);
placeable.add(32);
placeable.add(37);
placeable.add(38);
placeable.add(39);
placeable.add(40);
placeable.add(50);
placeable.add(65);
placeable.add(66);
placeable.add(69);
placeable.add(70);
placeable.add(72);
placeable.add(76);
placeable.add(77);
placeable.add(96);
placeable.add(106);
placeable.add(111);
placeable.add(131);
placeable.add(143);
placeable.add(147);
placeable.add(148);
placeable.add(157);
placeable.add(167);
placeable.add(175);
for (int i = 256; i <= 378; i++) placeable.add(i);
for (int i = 381; i <= 396; i++) placeable.add(i);
for (int i = 398; i <= 452; i++) placeable.add(i);
for (int i = 2256; i <= 2267; i++) placeable.add(i);
}
@Override @Override
protected void registerPackets() { protected void registerPackets() {
@ -86,7 +122,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.STRING); //Level Type map(Type.STRING); //Level Type
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, false); //Reduced Debug Info packetWrapper.write(Type.BOOLEAN, false); //Reduced Debug Info
} }
}); });
@ -100,7 +136,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.STRING); //Chat Message map(Type.STRING); //Chat Message
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BYTE, (byte) 0); //Position (chat box) packetWrapper.write(Type.BYTE, (byte) 0); //Position (chat box)
} }
}); });
@ -519,7 +555,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.BYTE); //z map(Type.BYTE); //z
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, true); //OnGround packetWrapper.write(Type.BOOLEAN, true); //OnGround
} }
}); });
@ -535,7 +571,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.BYTE); //pitch map(Type.BYTE); //pitch
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, true); //OnGround packetWrapper.write(Type.BOOLEAN, true); //OnGround
} }
}); });
@ -554,7 +590,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.BYTE); //pitch map(Type.BYTE); //pitch
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, true); //OnGround packetWrapper.write(Type.BOOLEAN, true); //OnGround
} }
}); });
@ -573,7 +609,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.BYTE); //pitch map(Type.BYTE); //pitch
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, true); //OnGround packetWrapper.write(Type.BOOLEAN, true); //OnGround
} }
}); });
@ -622,7 +658,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.SHORT, Type.VAR_INT); //Duration map(Type.SHORT, Type.VAR_INT); //Duration
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BOOLEAN, false); packetWrapper.write(Type.BOOLEAN, false);
} }
}); //Hide Particles }); //Hide Particles
@ -911,7 +947,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
items = new Item[old.length + 1]; items = new Item[old.length + 1];
items[0] = old[0]; items[0] = old[0];
System.arraycopy(old, 1, items, 2, old.length - 1); System.arraycopy(old, 1, items, 2, old.length - 1);
items[1] = new Item((short) 351, (byte) 3, (short) 4, null); items[1] = new Item(351, (byte) 3, (short) 4, null);
} }
packetWrapper.write(Type.ITEM_ARRAY, items); //Items packetWrapper.write(Type.ITEM_ARRAY, items); //Items
} }
@ -1309,7 +1345,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
Item item = packetWrapper.read(Type.ITEM); Item item = packetWrapper.read(Type.ITEM);
packetWrapper.write(Types1_7_6_10.COMPRESSED_NBT_ITEM, item); packetWrapper.write(Types1_7_6_10.COMPRESSED_NBT_ITEM, item);
if (isPlayerInsideBlock(x, y, z, direction) && !isPlaceable(item.getId())) if (isPlayerInsideBlock(x, y, z, direction) && !isPlaceable(item.getIdentifier()))
packetWrapper.cancel(); packetWrapper.cancel();
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
@ -1331,7 +1367,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
public void registerMap() { public void registerMap() {
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.INT, 0); //Entity Id, hopefully 0 is ok packetWrapper.write(Type.INT, 0); //Entity Id, hopefully 0 is ok
packetWrapper.write(Type.BYTE, (byte) 1); //Animation packetWrapper.write(Type.BYTE, (byte) 1); //Animation
} }
@ -1452,7 +1488,7 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
map(Type.BOOLEAN); map(Type.BOOLEAN);
create(new ValueCreator() { create(new ValueCreator() {
@Override @Override
public void write(PacketWrapper packetWrapper) throws Exception { public void write(PacketWrapper packetWrapper) {
packetWrapper.write(Type.BYTE, (byte) 0); packetWrapper.write(Type.BYTE, (byte) 0);
} }
}); });
@ -1564,43 +1600,6 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
return false; return false;
} }
private static ArrayList<Integer> placeable = new ArrayList<>();
static {
placeable.add(6);
placeable.add(27);
placeable.add(28);
placeable.add(30);
placeable.add(31);
placeable.add(32);
placeable.add(37);
placeable.add(38);
placeable.add(39);
placeable.add(40);
placeable.add(50);
placeable.add(65);
placeable.add(66);
placeable.add(69);
placeable.add(70);
placeable.add(72);
placeable.add(76);
placeable.add(77);
placeable.add(96);
placeable.add(106);
placeable.add(111);
placeable.add(131);
placeable.add(143);
placeable.add(147);
placeable.add(148);
placeable.add(157);
placeable.add(167);
placeable.add(175);
for (int i = 256; i <= 378; i++) placeable.add(i);
for (int i = 381; i <= 396; i++) placeable.add(i);
for (int i = 398; i <= 452; i++) placeable.add(i);
for (int i = 2256; i <= 2267; i++) placeable.add(i);
}
private boolean isPlaceable(int id) { private boolean isPlaceable(int id) {
return placeable.contains(id); return placeable.contains(id);
} }
@ -1680,9 +1679,20 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
ITEM_TAKE("take"), ITEM_TAKE("take"),
MOB_APPEARANCE("mobappearance"); MOB_APPEARANCE("mobappearance");
private static final HashMap<String, Particle> particleMap = new HashMap<>();
static {
Particle[] particles = values();
int var1 = particles.length;
for (Particle particle : particles) {
particleMap.put(particle.name, particle);
}
}
public final String name; public final String name;
public final int extra; public final int extra;
private static final HashMap<String, Particle> particleMap = new HashMap<>();
Particle(String name) { Particle(String name) {
this(name, 0); this(name, 0);
@ -1696,15 +1706,5 @@ public class Protocol1_8TO1_7_6_10 extends Protocol {
public static Particle find(String part) { public static Particle find(String part) {
return particleMap.get(part); return particleMap.get(part);
} }
static {
Particle[] particles = values();
int var1 = particles.length;
for (Particle particle : particles) {
particleMap.put(particle.name, particle);
}
}
} }
} }

View File

@ -37,156 +37,156 @@ import java.util.zip.DataFormatException;
import java.util.zip.Inflater; import java.util.zip.Inflater;
public class ChunkPacketTransformer { public class ChunkPacketTransformer {
public static void transformChunk(PacketWrapper packetWrapper) throws Exception { public static void transformChunk(PacketWrapper packetWrapper) throws Exception {
int chunkX = packetWrapper.read(Type.INT); int chunkX = packetWrapper.read(Type.INT);
int chunkZ = packetWrapper.read(Type.INT); int chunkZ = packetWrapper.read(Type.INT);
boolean groundUp = packetWrapper.read(Type.BOOLEAN); boolean groundUp = packetWrapper.read(Type.BOOLEAN);
int primaryBitMask = packetWrapper.read(Type.SHORT); int primaryBitMask = packetWrapper.read(Type.SHORT);
int addBitMask = packetWrapper.read(Type.SHORT); int addBitMask = packetWrapper.read(Type.SHORT);
int compressedSize = packetWrapper.read(Type.INT); int compressedSize = packetWrapper.read(Type.INT);
CustomByteType customByteType = new CustomByteType(compressedSize); CustomByteType customByteType = new CustomByteType(compressedSize);
byte[] data = packetWrapper.read(customByteType); byte[] data = packetWrapper.read(customByteType);
int k = 0; int k = 0;
int l = 0; int l = 0;
for(int j = 0; j < 16; ++j) { for (int j = 0; j < 16; ++j) {
k += primaryBitMask >> j & 1; k += primaryBitMask >> j & 1;
l += addBitMask >> j & 1; l += addBitMask >> j & 1;
} }
int uncompressedSize = 12288 * k; int uncompressedSize = 12288 * k;
uncompressedSize += 2048 * l; uncompressedSize += 2048 * l;
if (groundUp) { if (groundUp) {
uncompressedSize += 256; uncompressedSize += 256;
} }
byte[] uncompressedData = new byte[uncompressedSize]; byte[] uncompressedData = new byte[uncompressedSize];
Inflater inflater = new Inflater(); Inflater inflater = new Inflater();
inflater.setInput(data, 0, compressedSize); inflater.setInput(data, 0, compressedSize);
try { try {
inflater.inflate(uncompressedData); inflater.inflate(uncompressedData);
} catch (DataFormatException ex) { } catch (DataFormatException ex) {
throw new IOException("Bad compressed data format"); throw new IOException("Bad compressed data format");
} finally { } finally {
inflater.end(); inflater.end();
} }
Chunk1_8to1_7_6_10 chunk = new Chunk1_8to1_7_6_10(uncompressedData, primaryBitMask, addBitMask, true, groundUp); Chunk1_8to1_7_6_10 chunk = new Chunk1_8to1_7_6_10(uncompressedData, primaryBitMask, addBitMask, true, groundUp);
Field field = PacketWrapper.class.getDeclaredField("packetValues"); Field field = PacketWrapper.class.getDeclaredField("packetValues");
field.setAccessible(true); field.setAccessible(true);
((List)field.get(packetWrapper)).clear(); ((List) field.get(packetWrapper)).clear();
field = PacketWrapper.class.getDeclaredField("readableObjects"); field = PacketWrapper.class.getDeclaredField("readableObjects");
field.setAccessible(true); field.setAccessible(true);
((LinkedList)field.get(packetWrapper)).clear(); ((LinkedList) field.get(packetWrapper)).clear();
field = PacketWrapper.class.getDeclaredField("inputBuffer"); field = PacketWrapper.class.getDeclaredField("inputBuffer");
field.setAccessible(true); field.setAccessible(true);
ByteBuf buffer = (ByteBuf) field.get(packetWrapper); ByteBuf buffer = (ByteBuf) field.get(packetWrapper);
buffer.clear(); buffer.clear();
buffer.writeInt(chunkX); buffer.writeInt(chunkX);
buffer.writeInt(chunkZ); buffer.writeInt(chunkZ);
buffer.writeBoolean(groundUp); buffer.writeBoolean(groundUp);
buffer.writeShort(primaryBitMask); buffer.writeShort(primaryBitMask);
byte[] finaldata = chunk.get1_8Data(); byte[] finaldata = chunk.get1_8Data();
Type.VAR_INT.write(buffer, finaldata.length); Type.VAR_INT.write(buffer, finaldata.length);
buffer.writeBytes(finaldata); buffer.writeBytes(finaldata);
} }
public static void transformChunkBulk(PacketWrapper packetWrapper) throws Exception { public static void transformChunkBulk(PacketWrapper packetWrapper) throws Exception {
short columnCount = packetWrapper.read(Type.SHORT); //short1 short columnCount = packetWrapper.read(Type.SHORT); //short1
int size = packetWrapper.read(Type.INT); //size int size = packetWrapper.read(Type.INT); //size
boolean skyLightSent = packetWrapper.read(Type.BOOLEAN); //h boolean skyLightSent = packetWrapper.read(Type.BOOLEAN); //h
int[] chunkX = new int[columnCount]; //a int[] chunkX = new int[columnCount]; //a
int[] chunkZ = new int[columnCount]; //b int[] chunkZ = new int[columnCount]; //b
int[] primaryBitMask = new int[columnCount]; //c int[] primaryBitMask = new int[columnCount]; //c
int[] addBitMask = new int[columnCount]; //d int[] addBitMask = new int[columnCount]; //d
byte[][] inflatedBuffers = new byte[columnCount][]; //inflatedBuffers byte[][] inflatedBuffers = new byte[columnCount][]; //inflatedBuffers
CustomByteType customByteType = new CustomByteType(size); CustomByteType customByteType = new CustomByteType(size);
byte[] buildBuffer = packetWrapper.read(customByteType); //buildBuffer byte[] buildBuffer = packetWrapper.read(customByteType); //buildBuffer
byte[] data = new byte[196864 * columnCount]; //abyte byte[] data = new byte[196864 * columnCount]; //abyte
Inflater inflater = new Inflater(); Inflater inflater = new Inflater();
inflater.setInput(buildBuffer, 0, size); inflater.setInput(buildBuffer, 0, size);
try { try {
inflater.inflate(data); inflater.inflate(data);
} catch (DataFormatException ex) { } catch (DataFormatException ex) {
throw new IOException("Bad compressed data format"); throw new IOException("Bad compressed data format");
} finally { } finally {
inflater.end(); inflater.end();
} }
int i = 0; int i = 0;
for(int j = 0; j < columnCount; ++j) { for (int j = 0; j < columnCount; ++j) {
chunkX[j] = packetWrapper.read(Type.INT); chunkX[j] = packetWrapper.read(Type.INT);
chunkZ[j] = packetWrapper.read(Type.INT); chunkZ[j] = packetWrapper.read(Type.INT);
primaryBitMask[j] = packetWrapper.read(Type.SHORT); primaryBitMask[j] = packetWrapper.read(Type.SHORT);
addBitMask[j] = packetWrapper.read(Type.SHORT); addBitMask[j] = packetWrapper.read(Type.SHORT);
int k = 0; int k = 0;
int l = 0; int l = 0;
int i1; int i1;
for(i1 = 0; i1 < 16; ++i1) { for (i1 = 0; i1 < 16; ++i1) {
k += primaryBitMask[j] >> i1 & 1; k += primaryBitMask[j] >> i1 & 1;
l += addBitMask[j] >> i1 & 1; l += addBitMask[j] >> i1 & 1;
} }
i1 = 8192 * k + 256; i1 = 8192 * k + 256;
i1 += 2048 * l; i1 += 2048 * l;
if (skyLightSent) { if (skyLightSent) {
i1 += 2048 * k; i1 += 2048 * k;
} }
inflatedBuffers[j] = new byte[i1]; inflatedBuffers[j] = new byte[i1];
System.arraycopy(data, i, inflatedBuffers[j], 0, i1); System.arraycopy(data, i, inflatedBuffers[j], 0, i1);
i += i1; i += i1;
} }
Chunk1_8to1_7_6_10[] chunks = new Chunk1_8to1_7_6_10[columnCount]; Chunk1_8to1_7_6_10[] chunks = new Chunk1_8to1_7_6_10[columnCount];
for (i = 0; i<columnCount; i++) { for (i = 0; i < columnCount; i++) {
chunks[i] = new Chunk1_8to1_7_6_10(inflatedBuffers[i], primaryBitMask[i], addBitMask[i], skyLightSent, true); chunks[i] = new Chunk1_8to1_7_6_10(inflatedBuffers[i], primaryBitMask[i], addBitMask[i], skyLightSent, true);
} }
packetWrapper.write(Type.BOOLEAN, skyLightSent); packetWrapper.write(Type.BOOLEAN, skyLightSent);
packetWrapper.write(Type.VAR_INT, (int)columnCount); packetWrapper.write(Type.VAR_INT, (int) columnCount);
for(i = 0; i < columnCount; ++i) { for (i = 0; i < columnCount; ++i) {
packetWrapper.write(Type.INT, chunkX[i]); packetWrapper.write(Type.INT, chunkX[i]);
packetWrapper.write(Type.INT, chunkZ[i]); packetWrapper.write(Type.INT, chunkZ[i]);
packetWrapper.write(Type.UNSIGNED_SHORT, primaryBitMask[i]); packetWrapper.write(Type.UNSIGNED_SHORT, primaryBitMask[i]);
} }
for(i = 0; i < columnCount; ++i) { for (i = 0; i < columnCount; ++i) {
data = chunks[i].get1_8Data(); data = chunks[i].get1_8Data();
customByteType = new CustomByteType(data.length); customByteType = new CustomByteType(data.length);
packetWrapper.write(customByteType, data); packetWrapper.write(customByteType, data);
} }
} }
public static void transformMultiBlockChange(PacketWrapper packetWrapper) throws Exception { public static void transformMultiBlockChange(PacketWrapper packetWrapper) throws Exception {
int chunkX = packetWrapper.read(Type.INT); int chunkX = packetWrapper.read(Type.INT);
int chunkZ = packetWrapper.read(Type.INT); int chunkZ = packetWrapper.read(Type.INT);
int size = packetWrapper.read(Type.SHORT); int size = packetWrapper.read(Type.SHORT);
packetWrapper.read(Type.INT); packetWrapper.read(Type.INT);
short[] blocks = new short[size]; short[] blocks = new short[size];
short[] positions = new short[size]; short[] positions = new short[size];
for (int i = 0; i<size; i++) { for (int i = 0; i < size; i++) {
positions[i] = packetWrapper.read(Type.SHORT); positions[i] = packetWrapper.read(Type.SHORT);
blocks[i] = packetWrapper.read(Type.SHORT); blocks[i] = packetWrapper.read(Type.SHORT);
} }
packetWrapper.write(Type.INT, chunkX); packetWrapper.write(Type.INT, chunkX);
packetWrapper.write(Type.INT, chunkZ); packetWrapper.write(Type.INT, chunkZ);
packetWrapper.write(Type.VAR_INT, size); packetWrapper.write(Type.VAR_INT, size);
for (int i = 0; i<size; i++) { for (int i = 0; i < size; i++) {
packetWrapper.write(Type.SHORT, positions[i]); packetWrapper.write(Type.SHORT, positions[i]);
packetWrapper.write(Type.VAR_INT, (int)blocks[i]); packetWrapper.write(Type.VAR_INT, (int) blocks[i]);
} }
} }
} }

View File

@ -27,101 +27,101 @@ package com.github.creeper123123321.viafabric.protocol.protocol1_8to1_7_6_10.chu
import us.myles.ViaVersion.api.minecraft.chunks.NibbleArray; import us.myles.ViaVersion.api.minecraft.chunks.NibbleArray;
public class ExtendedBlockStorage { public class ExtendedBlockStorage {
private int yBase; private int yBase;
private byte[] blockLSBArray; private byte[] blockLSBArray;
private NibbleArray blockMSBArray; private NibbleArray blockMSBArray;
private NibbleArray blockMetadataArray; private NibbleArray blockMetadataArray;
private NibbleArray blocklightArray; private NibbleArray blocklightArray;
private NibbleArray skylightArray; private NibbleArray skylightArray;
public ExtendedBlockStorage(int paramInt, boolean paramBoolean) { public ExtendedBlockStorage(int paramInt, boolean paramBoolean) {
this.yBase = paramInt; this.yBase = paramInt;
this.blockLSBArray = new byte[4096]; this.blockLSBArray = new byte[4096];
this.blockMetadataArray = new NibbleArray(this.blockLSBArray.length); this.blockMetadataArray = new NibbleArray(this.blockLSBArray.length);
this.blocklightArray = new NibbleArray(this.blockLSBArray.length); this.blocklightArray = new NibbleArray(this.blockLSBArray.length);
if (paramBoolean) { if (paramBoolean) {
this.skylightArray = new NibbleArray(this.blockLSBArray.length); this.skylightArray = new NibbleArray(this.blockLSBArray.length);
} }
} }
public int getExtBlockMetadata(int paramInt1, int paramInt2, int paramInt3) { public int getExtBlockMetadata(int paramInt1, int paramInt2, int paramInt3) {
return this.blockMetadataArray.get(paramInt1, paramInt2, paramInt3); return this.blockMetadataArray.get(paramInt1, paramInt2, paramInt3);
} }
public void setExtBlockMetadata(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { public void setExtBlockMetadata(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
this.blockMetadataArray.set(paramInt1, paramInt2, paramInt3, paramInt4); this.blockMetadataArray.set(paramInt1, paramInt2, paramInt3, paramInt4);
} }
public int getYLocation() { public int getYLocation() {
return this.yBase; return this.yBase;
} }
public void setExtSkylightValue(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { public void setExtSkylightValue(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
this.skylightArray.set(paramInt1, paramInt2, paramInt3, paramInt4); this.skylightArray.set(paramInt1, paramInt2, paramInt3, paramInt4);
} }
public int getExtSkylightValue(int paramInt1, int paramInt2, int paramInt3) { public int getExtSkylightValue(int paramInt1, int paramInt2, int paramInt3) {
return this.skylightArray.get(paramInt1, paramInt2, paramInt3); return this.skylightArray.get(paramInt1, paramInt2, paramInt3);
} }
public void setExtBlocklightValue(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { public void setExtBlocklightValue(int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
this.blocklightArray.set(paramInt1, paramInt2, paramInt3, paramInt4); this.blocklightArray.set(paramInt1, paramInt2, paramInt3, paramInt4);
} }
public int getExtBlocklightValue(int paramInt1, int paramInt2, int paramInt3) { public int getExtBlocklightValue(int paramInt1, int paramInt2, int paramInt3) {
return this.blocklightArray.get(paramInt1, paramInt2, paramInt3); return this.blocklightArray.get(paramInt1, paramInt2, paramInt3);
} }
public byte[] getBlockLSBArray() { public byte[] getBlockLSBArray() {
return this.blockLSBArray; return this.blockLSBArray;
} }
public boolean isEmpty() { public void setBlockLSBArray(byte[] paramArrayOfByte) {
return this.blockMSBArray==null; this.blockLSBArray = paramArrayOfByte;
} }
public void clearMSBArray() { public boolean isEmpty() {
this.blockMSBArray = null; return this.blockMSBArray == null;
} }
public NibbleArray getBlockMSBArray() { public void clearMSBArray() {
return this.blockMSBArray; this.blockMSBArray = null;
} }
public NibbleArray getMetadataArray() { public NibbleArray getBlockMSBArray() {
return this.blockMetadataArray; return this.blockMSBArray;
} }
public NibbleArray getBlocklightArray() { public void setBlockMSBArray(NibbleArray paramNibbleArray) {
return this.blocklightArray; this.blockMSBArray = paramNibbleArray;
} }
public NibbleArray getSkylightArray() { public NibbleArray getMetadataArray() {
return this.skylightArray; return this.blockMetadataArray;
} }
public void setBlockLSBArray(byte[] paramArrayOfByte) { public NibbleArray getBlocklightArray() {
this.blockLSBArray = paramArrayOfByte; return this.blocklightArray;
} }
public void setBlockMSBArray(NibbleArray paramNibbleArray) { public void setBlocklightArray(NibbleArray paramNibbleArray) {
this.blockMSBArray = paramNibbleArray; this.blocklightArray = paramNibbleArray;
} }
public void setBlockMetadataArray(NibbleArray paramNibbleArray) { public NibbleArray getSkylightArray() {
this.blockMetadataArray = paramNibbleArray; return this.skylightArray;
} }
public void setBlocklightArray(NibbleArray paramNibbleArray) { public void setSkylightArray(NibbleArray paramNibbleArray) {
this.blocklightArray = paramNibbleArray; this.skylightArray = paramNibbleArray;
} }
public void setSkylightArray(NibbleArray paramNibbleArray) { public void setBlockMetadataArray(NibbleArray paramNibbleArray) {
this.skylightArray = paramNibbleArray; this.blockMetadataArray = paramNibbleArray;
} }
public NibbleArray createBlockMSBArray() { public NibbleArray createBlockMSBArray() {
this.blockMSBArray = new NibbleArray(this.blockLSBArray.length); this.blockMSBArray = new NibbleArray(this.blockLSBArray.length);
return this.blockMSBArray; return this.blockMSBArray;
} }
} }

View File

@ -36,74 +36,74 @@ import java.util.List;
public class MetadataRewriter { public class MetadataRewriter {
public static void transform(Entity1_10Types.EntityType type, List<Metadata> list) { public static void transform(Entity1_10Types.EntityType type, List<Metadata> list) {
for (Metadata entry : new ArrayList<>(list)) { for (Metadata entry : new ArrayList<>(list)) {
MetaIndex1_8to1_7_6_10 metaIndex = MetaIndex1_8to1_7_6_10.searchIndex(type, entry.getId()); MetaIndex1_8to1_7_6_10 metaIndex = MetaIndex1_8to1_7_6_10.searchIndex(type, entry.getId());
try { try {
if (metaIndex == null) throw new Exception("Could not find valid metadata"); if (metaIndex == null) throw new Exception("Could not find valid metadata");
if (metaIndex.getNewType() == MetaType1_8.NonExistent) { if (metaIndex.getNewType() == MetaType1_8.NonExistent) {
list.remove(entry); list.remove(entry);
return; return;
} }
Object value = entry.getValue(); Object value = entry.getValue();
if (!value.getClass().isAssignableFrom(metaIndex.getOldType().getType().getOutputClass())) { if (!value.getClass().isAssignableFrom(metaIndex.getOldType().getType().getOutputClass())) {
list.remove(entry); list.remove(entry);
return; return;
} }
entry.setMetaType(metaIndex.getNewType()); entry.setMetaType(metaIndex.getNewType());
entry.setId(metaIndex.getNewIndex()); entry.setId(metaIndex.getNewIndex());
switch (metaIndex.getNewType()) { switch (metaIndex.getNewType()) {
case Int: case Int:
if (metaIndex.getOldType() == MetaType1_7_6_10.Byte) { if (metaIndex.getOldType() == MetaType1_7_6_10.Byte) {
entry.setValue(((Byte) value).intValue()); entry.setValue(((Byte) value).intValue());
} }
if (metaIndex.getOldType() == MetaType1_7_6_10.Short) { if (metaIndex.getOldType() == MetaType1_7_6_10.Short) {
entry.setValue(((Short) value).intValue()); entry.setValue(((Short) value).intValue());
} }
if (metaIndex.getOldType() == MetaType1_7_6_10.Int) { if (metaIndex.getOldType() == MetaType1_7_6_10.Int) {
entry.setValue(value); entry.setValue(value);
} }
break; break;
case Byte: case Byte:
if (metaIndex.getOldType() == MetaType1_7_6_10.Int) { if (metaIndex.getOldType() == MetaType1_7_6_10.Int) {
entry.setValue(((Integer) value).byteValue()); entry.setValue(((Integer) value).byteValue());
} }
if (metaIndex.getOldType() == MetaType1_7_6_10.Byte) { if (metaIndex.getOldType() == MetaType1_7_6_10.Byte) {
entry.setValue(value); entry.setValue(value);
} }
if (metaIndex==MetaIndex1_8to1_7_6_10.HUMAN_SKIN_FLAGS) { if (metaIndex == MetaIndex1_8to1_7_6_10.HUMAN_SKIN_FLAGS) {
byte flags = (byte) value; byte flags = (byte) value;
boolean cape = flags==2; boolean cape = flags == 2;
flags = (byte) (cape ? 127 : 125); flags = (byte) (cape ? 127 : 125);
entry.setValue(flags); entry.setValue(flags);
} }
break; break;
case Slot: case Slot:
entry.setValue(value); entry.setValue(value);
break; break;
case Float: case Float:
entry.setValue(value); entry.setValue(value);
break; break;
case Short: case Short:
entry.setValue(value); entry.setValue(value);
break; break;
case String: case String:
entry.setValue(value); entry.setValue(value);
break; break;
case Position: case Position:
entry.setValue(value); entry.setValue(value);
break; break;
case Rotation: case Rotation:
entry.setValue(value); entry.setValue(value);
break; break;
default: default:
Via.getPlatform().getLogger().warning("[Out] Unhandled MetaDataType: " + metaIndex.getNewType()); Via.getPlatform().getLogger().warning("[Out] Unhandled MetaDataType: " + metaIndex.getNewType());
list.remove(entry); list.remove(entry);
break; break;
} }
} catch (Exception e) { } catch (Exception e) {
list.remove(entry); list.remove(entry);
} }
} }
} }
} }

View File

@ -39,48 +39,48 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class EntityTracker extends StoredObject { public class EntityTracker extends StoredObject {
private final Map<Integer, Entity1_10Types.EntityType> clientEntityTypes = new ConcurrentHashMap<>(); private final Map<Integer, Entity1_10Types.EntityType> clientEntityTypes = new ConcurrentHashMap<>();
private final Map<Integer, List<Metadata>> metadataBuffer = new ConcurrentHashMap<>(); private final Map<Integer, List<Metadata>> metadataBuffer = new ConcurrentHashMap<>();
public EntityTracker(UserConnection user) { public EntityTracker(UserConnection user) {
super(user); super(user);
} }
public void removeEntity(int entityId) { public void removeEntity(int entityId) {
clientEntityTypes.remove(entityId); clientEntityTypes.remove(entityId);
} }
public Map<Integer, Entity1_10Types.EntityType> getClientEntityTypes() { public Map<Integer, Entity1_10Types.EntityType> getClientEntityTypes() {
return this.clientEntityTypes; return this.clientEntityTypes;
} }
public void addMetadataToBuffer(int entityID, List<Metadata> metadataList) { public void addMetadataToBuffer(int entityID, List<Metadata> metadataList) {
if (this.metadataBuffer.containsKey(entityID)) { if (this.metadataBuffer.containsKey(entityID)) {
this.metadataBuffer.get(entityID).addAll(metadataList); this.metadataBuffer.get(entityID).addAll(metadataList);
} else if (!metadataList.isEmpty()) { } else if (!metadataList.isEmpty()) {
this.metadataBuffer.put(entityID, metadataList); this.metadataBuffer.put(entityID, metadataList);
} }
} }
public List<Metadata> getBufferedMetadata(int entityId) { public List<Metadata> getBufferedMetadata(int entityId) {
return metadataBuffer.get(entityId); return metadataBuffer.get(entityId);
} }
public void sendMetadataBuffer(int entityId) { public void sendMetadataBuffer(int entityId) {
if (!this.metadataBuffer.containsKey(entityId)) return; if (!this.metadataBuffer.containsKey(entityId)) return;
PacketWrapper wrapper = new PacketWrapper(0x1C, null, this.getUser()); PacketWrapper wrapper = new PacketWrapper(0x1C, null, this.getUser());
wrapper.write(Type.VAR_INT, entityId); wrapper.write(Type.VAR_INT, entityId);
wrapper.write(Types1_8.METADATA_LIST, this.metadataBuffer.get(entityId)); wrapper.write(Types1_8.METADATA_LIST, this.metadataBuffer.get(entityId));
MetadataRewriter.transform(this.getClientEntityTypes().get(entityId), this.metadataBuffer.get(entityId)); MetadataRewriter.transform(this.getClientEntityTypes().get(entityId), this.metadataBuffer.get(entityId));
if (!this.metadataBuffer.get(entityId).isEmpty()) { if (!this.metadataBuffer.get(entityId).isEmpty()) {
try { try {
wrapper.send(Protocol1_8TO1_7_6_10.class); wrapper.send(Protocol1_8TO1_7_6_10.class);
} catch (Exception ex) { } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
} }
} }
this.metadataBuffer.remove(entityId); this.metadataBuffer.remove(entityId);
} }
} }

View File

@ -31,36 +31,36 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class MapStorage extends StoredObject { public class MapStorage extends StoredObject {
private Map<Integer, MapData> maps = new HashMap<>(); private Map<Integer, MapData> maps = new HashMap<>();
public MapStorage(UserConnection user) { public MapStorage(UserConnection user) {
super(user); super(user);
} }
public MapData getMapData(int id) { public MapData getMapData(int id) {
return maps.get(id); return maps.get(id);
} }
public void putMapData(int id, MapData mapData) { public void putMapData(int id, MapData mapData) {
maps.put(id, mapData); maps.put(id, mapData);
} }
public static class MapData { public static class MapData {
public byte scale = 0; public byte scale = 0;
public MapIcon[] mapIcons = {}; public MapIcon[] mapIcons = {};
} }
public static class MapIcon { public static class MapIcon {
public byte direction; public byte direction;
public byte type; public byte type;
public byte x; public byte x;
public byte z; public byte z;
public MapIcon(byte direction, byte type, byte x, byte z) { public MapIcon(byte direction, byte type, byte x, byte z) {
this.direction = direction; this.direction = direction;
this.type = type; this.type = type;
this.x = x; this.x = x;
this.z = z; this.z = z;
} }
} }
} }

View File

@ -31,17 +31,17 @@ import java.util.HashMap;
public class Scoreboard extends StoredObject { public class Scoreboard extends StoredObject {
private HashMap<String, String> objectives = new HashMap<>(); private HashMap<String, String> objectives = new HashMap<>();
public Scoreboard(UserConnection user) { public Scoreboard(UserConnection user) {
super(user); super(user);
} }
public void put(String name, String objective) { public void put(String name, String objective) {
objectives.put(name, objective); objectives.put(name, objective);
} }
public String get(String name) { public String get(String name) {
return objectives.getOrDefault(name, "null"); return objectives.getOrDefault(name, "null");
} }
} }

View File

@ -33,56 +33,56 @@ import java.util.UUID;
public class Tablist extends StoredObject { public class Tablist extends StoredObject {
private ArrayList<TabListEntry> tablist = new ArrayList<>(); private ArrayList<TabListEntry> tablist = new ArrayList<>();
public Tablist(UserConnection user) { public Tablist(UserConnection user) {
super(user); super(user);
} }
public TabListEntry getTabListEntry(String name) { public static boolean shouldUpdateDisplayName(String oldName, String newName) {
for (TabListEntry entry : tablist) if (name.equals(entry.name)) return entry; return oldName == null && newName != null || oldName != null && newName == null || oldName != null && !oldName.equals(newName);
return null; }
}
public TabListEntry getTabListEntry(UUID uuid) { public TabListEntry getTabListEntry(String name) {
for (TabListEntry entry : tablist) if (uuid.equals(entry.uuid)) return entry; for (TabListEntry entry : tablist) if (name.equals(entry.name)) return entry;
return null; return null;
} }
public void remove(TabListEntry entry) { public TabListEntry getTabListEntry(UUID uuid) {
tablist.remove(entry); for (TabListEntry entry : tablist) if (uuid.equals(entry.uuid)) return entry;
} return null;
}
public void add(TabListEntry entry) { public void remove(TabListEntry entry) {
tablist.add(entry); tablist.remove(entry);
} }
public static boolean shouldUpdateDisplayName(String oldName, String newName) { public void add(TabListEntry entry) {
return oldName == null && newName != null || oldName != null && newName == null || oldName != null && !oldName.equals(newName); tablist.add(entry);
} }
public static class TabListEntry { public static class TabListEntry {
public String name; public String name;
public String displayName; public String displayName;
public UUID uuid; public UUID uuid;
public int ping; public int ping;
public List<Property> properties = new ArrayList<>(); public List<Property> properties = new ArrayList<>();
public TabListEntry(String name, UUID uuid) { public TabListEntry(String name, UUID uuid) {
this.name = name; this.name = name;
this.uuid = uuid; this.uuid = uuid;
} }
} }
public static class Property { public static class Property {
public String name; public String name;
public String value; public String value;
public String signature; public String signature;
public Property(String name, String value, String signature) { public Property(String name, String value, String signature) {
this.name = name; this.name = name;
this.value = value; this.value = value;
this.signature = signature; this.signature = signature;
} }
} }
} }

View File

@ -31,13 +31,13 @@ import java.util.HashMap;
public class Windows extends StoredObject { public class Windows extends StoredObject {
public HashMap<Short, Short> types = new HashMap<>(); public HashMap<Short, Short> types = new HashMap<>();
public Windows(UserConnection user) { public Windows(UserConnection user) {
super(user); super(user);
} }
public short get(short windowId) { public short get(short windowId) {
return types.getOrDefault(windowId, (short)-1); return types.getOrDefault(windowId, (short) -1);
} }
} }

View File

@ -1,115 +0,0 @@
/*
* MIT License
*
* Copyright (c) 2018 creeper123123321 and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.creeper123123321.viafabric.util;
import com.google.common.base.Joiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Based on ViaVersion's Version
public class Version implements Comparable<Version> {
private static final Pattern semVer = Pattern.compile("(?<a>0|[1-9]\\d*)\\.(?<b>0|[1-9]\\d*)(?:\\.(?<c>0|[1-9]\\d*))?(?:-(?<tag>[A-z0-9.-]*))?");
private final int[] parts = new int[3];
private String tag;
public Version(String value) {
if (value == null) {
throw new IllegalArgumentException("Version can not be null");
} else {
Matcher matcher = semVer.matcher(value);
if (!matcher.matches()) {
throw new IllegalArgumentException("Invalid version format");
} else {
this.parts[0] = Integer.parseInt(matcher.group("a"));
this.parts[1] = Integer.parseInt(matcher.group("b"));
this.parts[2] = matcher.group("c") == null ? 0 : Integer.parseInt(matcher.group("c"));
this.tag = matcher.group("tag") == null ? "" : matcher.group("tag");
}
}
}
public static int compare(Version verA, Version verB) {
if (verA == verB) {
return 0;
} else if (verA == null) {
return -1;
} else if (verB == null) {
return 1;
} else {
int max = Math.max(verA.parts.length, verB.parts.length);
for(int i = 0; i < max; ++i) {
int partA = i < verA.parts.length ? verA.parts[i] : 0;
int partB = i < verB.parts.length ? verB.parts[i] : 0;
if (partA < partB) {
return -1;
}
if (partA > partB) {
return 1;
}
}
// ViaFabric
if (verA.tag.isEmpty() && verB.tag.isEmpty()) {
return 0;
}
if (verA.tag.isEmpty()) {
return 1;
}
if (verB.tag.isEmpty()) {
return -1;
}
return verA.tag.compareTo(verB.tag);
}
}
public static boolean equals(Version verA, Version verB) {
return verA == verB || verA != null && verB != null && compare(verA, verB) == 0;
}
public String toString() {
String[] split = new String[this.parts.length];
for(int i = 0; i < this.parts.length; ++i) {
split[i] = String.valueOf(this.parts[i]);
}
return Joiner.on(".").join(split) + (this.tag.length() != 0 ? "-" + this.tag : "");
}
public int compareTo(Version that) {
return compare(this, that);
}
public boolean equals(Object that) {
return that instanceof Version && equals(this, (Version)that);
}
public String getTag() {
return this.tag;
}
}

View File

@ -46,7 +46,7 @@ public class VersionFormatFilter implements Predicate<String> {
.flatMap(str -> Stream.concat( .flatMap(str -> Stream.concat(
Arrays.stream(str.split("-")), Arrays.stream(str.split("-")),
Arrays.stream(new String[]{str}) Arrays.stream(new String[]{str})
)) ))
.anyMatch(ver -> ver.startsWith(s)); .anyMatch(ver -> ver.startsWith(s));
} }
} }