diff --git a/src/main/java/dev/dfonline/codeclient/CodeClient.java b/src/main/java/dev/dfonline/codeclient/CodeClient.java index b6e2f6b0..87b55101 100644 --- a/src/main/java/dev/dfonline/codeclient/CodeClient.java +++ b/src/main/java/dev/dfonline/codeclient/CodeClient.java @@ -24,7 +24,6 @@ import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientLifecycleEvents; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; -import net.fabricmc.fabric.api.event.client.ClientTickCallback; import net.minecraft.block.Blocks; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.ChatScreen; @@ -36,11 +35,9 @@ import net.minecraft.client.util.math.MatrixStack; import net.minecraft.network.listener.PacketListener; import net.minecraft.network.packet.Packet; -import net.minecraft.network.packet.c2s.play.CommandExecutionC2SPacket; import net.minecraft.network.packet.s2c.play.CloseScreenS2CPacket; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; -import net.minecraft.util.math.Vec3d; import org.jetbrains.annotations.NotNull; import org.lwjgl.glfw.GLFW; import org.slf4j.Logger; @@ -51,9 +48,8 @@ public class CodeClient implements ModInitializer { public static final String MOD_NAME = "CodeClient"; public static final String MOD_ID = "codeclient"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_NAME); - - public static MinecraftClient MC = MinecraftClient.getInstance(); public static final Gson gson = new Gson(); + public static MinecraftClient MC = MinecraftClient.getInstance(); /** * Starts the "Code Palette" screen if pressed. */ @@ -75,23 +71,21 @@ public class CodeClient implements ModInitializer { /** * For all receiving packet events and debugging. - * @return If the packet should be cancelled and not acted on. True to ignore. + * * @param Server2Client + * @return If the packet should be cancelled and not acted on. True to ignore. */ public static boolean handlePacket(Packet packet) { - if(currentAction.onReceivePacket(packet)) return true; - if(Debug.handlePacket(packet)) return true; - if(BuildPhaser.handlePacket(packet)) return true; - if(ChestPeeker.handlePacket(packet)) return true; + if (currentAction.onReceivePacket(packet)) return true; + if (Debug.handlePacket(packet)) return true; + if (BuildPhaser.handlePacket(packet)) return true; + if (ChestPeeker.handlePacket(packet)) return true; Event.handlePacket(packet); LastPos.handlePacket(packet); - String name = packet.getClass().getName().replace("net.minecraft.network.packet.s2c.play.",""); -// if(!List.of("PlayerListS2CPacket","WorldTimeUpdateS2CPacket","GameMessageS2CPacket","KeepAliveS2CPacket", "ChunkDataS2CPacket", "UnloadChunkS2CPacket","TeamS2CPacket", "ChunkRenderDistanceCenterS2CPacket", "MessageHeaderS2CPacket", "LightUpdateS2CPacket", "OverlayMessageS2CPacket").contains(name)) LOGGER.info(name); - if((MC.currentScreen instanceof GameMenuScreen || MC.currentScreen instanceof ChatScreen || MC.currentScreen instanceof StateSwitcher) && packet instanceof CloseScreenS2CPacket) { - return true; - } - return false; + String name = packet.getClass().getName().replace("net.minecraft.network.packet.s2c.play.", ""); +// if(!java.util.List.of("PlayerListS2CPacket","WorldTimeUpdateS2CPacket","GameMessageS2CPacket","KeepAliveS2CPacket", "ChunkDataS2CPacket", "UnloadChunkS2CPacket","TeamS2CPacket", "ChunkRenderDistanceCenterS2CPacket", "MessageHeaderS2CPacket", "LightUpdateS2CPacket", "OverlayMessageS2CPacket").contains(name)) LOGGER.info(name); + return (MC.currentScreen instanceof GameMenuScreen || MC.currentScreen instanceof ChatScreen || MC.currentScreen instanceof StateSwitcher) && packet instanceof CloseScreenS2CPacket; } /** @@ -100,24 +94,25 @@ public static boolean handlePacket(Packet packet) * Useful for fallback checks and preventing noclip packet spam screwing you over. */ public static boolean noClipOn() { - if(MC.player == null) return false; - if(!Config.getConfig().NoClipEnabled) return false; - if(!(location instanceof Dev)) return false; - if(!(currentAction instanceof None)) return false; - if(!MC.player.getAbilities().creativeMode) return false; + if (MC.player == null) return false; + if (!Config.getConfig().NoClipEnabled) return false; + if (!(location instanceof Dev)) return false; + if (!(currentAction instanceof None)) return false; + if (!MC.player.getAbilities().creativeMode) return false; return true; } /** * All outgoing packet events and debugging. - * @return If the packet shouldn't be sent. True to not send. + * * @param ClientToServer + * @return If the packet shouldn't be sent. True to not send. */ public static boolean onSendPacket(Packet packet) { - if(CodeClient.currentAction.onSendPacket(packet)) return true; - if(BuildPhaser.onPacket(packet)) return true; + if (CodeClient.currentAction.onSendPacket(packet)) return true; + if (BuildPhaser.onPacket(packet)) return true; Event.onSendPacket(packet); - String name = packet.getClass().getName().replace("net.minecraft.network.packet.c2s.play.",""); + String name = packet.getClass().getName().replace("net.minecraft.network.packet.c2s.play.", ""); // LOGGER.info(name); return false; } @@ -133,35 +128,39 @@ public static void onTick() { ChestPeeker.tick(); RecentChestInsert.tick(); - if(location instanceof Dev dev) { - if(MC.player == null) return; + if (location instanceof Dev dev) { + if (MC.player == null) return; MC.player.getAbilities().allowFlying = true; - if(NoClip.isIgnoringWalls()) MC.player.noClip = true; - if(editBind.wasPressed()) { + if (NoClip.isIgnoringWalls()) MC.player.noClip = true; + if (editBind.wasPressed()) { MC.setScreen(new DevInventoryScreen(MC.player)); } - var pos = new BlockPos(dev.getX() - 1,49,dev.getZ()); - if(dev.getSize() == null) { + var pos = new BlockPos(dev.getX() - 1, 49, dev.getZ()); + if (dev.getSize() == null) { // TODO wait for plugin messages, or make a fix now. - if(!CodeClient.MC.world.getBlockState(pos.south(50)).isOf(CodeClient.MC.world.getBlockState(pos.south(51)).getBlock())) dev.setSize(Plot.Size.BASIC); - else if(!CodeClient.MC.world.getBlockState(pos.south(100)).isOf(CodeClient.MC.world.getBlockState(pos.south(101)).getBlock())) dev.setSize(Plot.Size.LARGE); - else if(!CodeClient.MC.world.getBlockState(pos.south(300)).isOf(CodeClient.MC.world.getBlockState(pos.south(301)).getBlock())) dev.setSize(Plot.Size.MASSIVE); + if (!CodeClient.MC.world.getBlockState(pos.south(50)).isOf(CodeClient.MC.world.getBlockState(pos.south(51)).getBlock())) + dev.setSize(Plot.Size.BASIC); + else if (!CodeClient.MC.world.getBlockState(pos.south(100)).isOf(CodeClient.MC.world.getBlockState(pos.south(101)).getBlock())) + dev.setSize(Plot.Size.LARGE); + else if (!CodeClient.MC.world.getBlockState(pos.south(300)).isOf(CodeClient.MC.world.getBlockState(pos.south(301)).getBlock())) + dev.setSize(Plot.Size.MASSIVE); } dev.setHasUnderground(!CodeClient.MC.world.getBlockState(pos).isOf(Blocks.STONE)); } - if(CodeClient.location instanceof Spawn spawn && spawn.consumeHasJustJoined()) { - if(autoJoin == AutoJoin.PLOT) { + if (CodeClient.location instanceof Spawn spawn && spawn.consumeHasJustJoined()) { + if (autoJoin == AutoJoin.PLOT) { MC.getNetworkHandler().sendCommand("join " + Config.getConfig().AutoJoinPlotId); autoJoin = AutoJoin.NONE; - } else if(Config.getConfig().AutoFly) { + } else if (Config.getConfig().AutoFly) { MC.getNetworkHandler().sendCommand("fly"); } } } + public static void onRender(MatrixStack matrices, VertexConsumerProvider.Immediate vertexConsumers, double cameraX, double cameraY, double cameraZ) { Debug.render(matrices, vertexConsumers); RecentChestInsert.render(matrices, vertexConsumers, cameraX, cameraY, cameraZ); - if(shouldReload) { + if (shouldReload) { MC.worldRenderer.reload(); shouldReload = false; } @@ -198,7 +197,7 @@ public static void reset() { @Override public void onInitialize() { ClientTickEvents.START_CLIENT_TICK.register(client -> { - if(MC.player == null || MC.world == null) clean(); + if (MC.player == null || MC.world == null) clean(); }); MC = MinecraftClient.getInstance(); @@ -206,16 +205,16 @@ public void onInitialize() { BlockRenderLayerMap.INSTANCE.putBlock(Blocks.STRUCTURE_VOID, RenderLayer.getTranslucent()); BlockRenderLayerMap.INSTANCE.putBlock(Blocks.LIGHT, RenderLayer.getTranslucent()); - ClientLifecycleEvents.CLIENT_STOPPING.register(new Identifier(MOD_ID,"close"), client -> SocketHandler.stop()); + ClientLifecycleEvents.CLIENT_STOPPING.register(new Identifier(MOD_ID, "close"), client -> SocketHandler.stop()); - if(Config.getConfig().CodeClientAPI) { + if (Config.getConfig().CodeClientAPI) { try { SocketHandler.start(); } catch (Exception e) { LOGGER.error(e.getMessage()); } } - if(Config.getConfig().AutoJoin) { + if (Config.getConfig().AutoJoin) { autoJoin = AutoJoin.GAME; } diff --git a/src/main/java/dev/dfonline/codeclient/Commands.java b/src/main/java/dev/dfonline/codeclient/Commands.java index 14555d46..37affb6a 100644 --- a/src/main/java/dev/dfonline/codeclient/Commands.java +++ b/src/main/java/dev/dfonline/codeclient/Commands.java @@ -35,8 +35,9 @@ import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal; public class Commands { - public static Action confirm = null; private static final Text DONE = Text.translatable("gui.done"); + public static Action confirm = null; + private static void actionCallback() { CodeClient.currentAction = new None(); Utility.sendMessage(DONE, ChatType.SUCCESS); @@ -46,9 +47,9 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("auth").executes(context -> { SocketHandler.setAuthorised(true); Utility.sendMessage(Text.translatable("codeclient.api.authorised") - .append(Text.literal("\n")).append(Text.translatable("codeclient.api.warning").formatted(Formatting.BOLD)) - .append(Text.literal("\n")).append(Text.translatable("codeclient.api.remove")) - , ChatType.SUCCESS); + .append(Text.literal("\n")).append(Text.translatable("codeclient.api.warning").formatted(Formatting.BOLD)) + .append(Text.literal("\n")).append(Text.translatable("codeclient.api.remove")) + , ChatType.SUCCESS); return 0; }).then(literal("remove").executes(context -> { SocketHandler.setAuthorised(false); @@ -61,16 +62,16 @@ public static void register(CommandDispatcher dispatc dispatcher.register(literal("worldplot").executes(context -> { - if(CodeClient.location instanceof Plot plot) plot.setSize(null); + if (CodeClient.location instanceof Plot plot) plot.setSize(null); return 0; }).then(literal("basic").executes(context -> { - if(CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.BASIC); + if (CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.BASIC); return 0; })).then(literal("large").executes(context -> { - if(CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.LARGE); + if (CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.LARGE); return 0; })).then(literal("massive").executes(context -> { - if(CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.MASSIVE); + if (CodeClient.location instanceof Plot plot) plot.setSize(Plot.Size.MASSIVE); return 0; }))); @@ -112,11 +113,10 @@ public static void register(CommandDispatcher dispatc } String dataFinal = data.toString(); try { - Path path = FileManager.writeFile("widthdump.txt",dataFinal); - Utility.sendMessage(Text.translatable("codeclient.files.saved",path).setStyle(Text.empty().getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, path.toString())))); - } - catch (Exception ignored) { - Utility.sendMessage(Text.translatable("codeclient.files.error.cant_save"),ChatType.FAIL); + Path path = FileManager.writeFile("widthdump.txt", dataFinal); + Utility.sendMessage(Text.translatable("codeclient.files.saved", path).setStyle(Text.empty().getStyle().withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, path.toString())))); + } catch (Exception ignored) { + Utility.sendMessage(Text.translatable("codeclient.files.error.cant_save"), ChatType.FAIL); CodeClient.LOGGER.info(dataFinal); } return 0; @@ -145,13 +145,13 @@ public static void register(CommandDispatcher dispatc // })); dispatcher.register(literal("getspawn").executes(context -> { - if(!(CodeClient.location instanceof Dev)) return 1; + if (!(CodeClient.location instanceof Dev)) return 1; CodeClient.currentAction = new MoveToSpawn(Commands::actionCallback); CodeClient.currentAction.init(); return 0; })); dispatcher.register(literal("getsize").executes(context -> { - if(!(CodeClient.location instanceof Dev)) return 1; + if (!(CodeClient.location instanceof Dev)) return 1; CodeClient.currentAction = new GetPlotSize(Commands::actionCallback); CodeClient.currentAction.init(); return 0; @@ -195,94 +195,90 @@ public static void register(CommandDispatcher dispatc // return 1; // } // }) - .then(argument("folder",StringArgumentType.greedyString()).suggests(Commands::suggestDirectories).executes(context -> { - if(CodeClient.location instanceof Dev) { - String arg = context.getArgument("folder",String.class); - String[] path = arg.split("/"); - - Path currentPath = FileManager.templatesPath(); - for (String dir: path) { - currentPath = currentPath.resolve(dir); - if(Files.notExists(currentPath)) { - try { - Files.createDirectory(currentPath); - } - catch (Exception ignored) { - Utility.sendMessage(Text.translatable("codeclient.files.error.write_folder",currentPath)); - } - } - else if(!Files.isDirectory(currentPath)) { - Utility.sendMessage(Text.translatable("codeclient.files.error.not_dir",currentPath), ChatType.FAIL); - return -1; - } - } + .then(argument("folder", StringArgumentType.greedyString()).suggests(Commands::suggestDirectories).executes(context -> { + if (CodeClient.location instanceof Dev) { + String arg = context.getArgument("folder", String.class); + String[] path = arg.split("/"); - boolean invalid = false; - try { - var list = Files.list(currentPath); - for (var file : list.toList()) { - invalid = true; - if(file.getFileName().toString().equals(".git")) { - Utility.sendMessage( - Text.empty() - .append(Text.translatable("codeclient.files.git")) - .append(Text.literal("\n")) - .append(Text.translatable("codeclient.files.open_native").fillStyle( - Style.EMPTY - .withColor(Formatting.AQUA) - .withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE,currentPath.toAbsolutePath().toString())) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,Text.literal(currentPath.toAbsolutePath().toString()))))) - ,ChatType.INFO); - invalid = false; break; - } - } - list.close(); - } - catch (Exception ignored) { - Utility.sendMessage(Text.translatable("codeclient.files.error.read_folder"),ChatType.FAIL); - } - if(invalid) { - Utility.sendMessage(Text.translatable("codeclient.files.empty_dir")); - return -1; - } + Path currentPath = FileManager.templatesPath(); + for (String dir : path) { + currentPath = currentPath.resolve(dir); + if (Files.notExists(currentPath)) { + try { + Files.createDirectory(currentPath); + } catch (Exception ignored) { + Utility.sendMessage(Text.translatable("codeclient.files.error.write_folder", currentPath)); + } + } else if (!Files.isDirectory(currentPath)) { + Utility.sendMessage(Text.translatable("codeclient.files.error.not_dir", currentPath), ChatType.FAIL); + return -1; + } + } - Utility.sendMessage(Text.translatable("codeclient.action.scanning").append(" ").append(Text.translatable("codeclient.action.abort")),ChatType.INFO); - var scan = new ArrayList(); - Path finalCurrentPath = currentPath; - CodeClient.currentAction = new ScanPlot(() -> { - actionCallback(); - for (ItemStack item : scan) { - String data = Utility.templateDataItem(item); - var template = Template.parse64(data); - if(template == null) continue; - var first = template.blocks.get(0); - String name = Objects.requireNonNullElse(first.action != null ? first.action : first.data,"unknown"); - var filePath = finalCurrentPath.resolve(name + ".dft"); - try { - Files.write(filePath,Base64.getDecoder().decode(data)); - } - catch (Exception ignored) { - Utility.sendMessage(Text.translatable("codeclient.files.error.write_file",filePath),ChatType.FAIL); - } - } + boolean invalid = false; + try { + var list = Files.list(currentPath); + for (var file : list.toList()) { + invalid = true; + if (file.getFileName().toString().equals(".git")) { + Utility.sendMessage( + Text.empty() + .append(Text.translatable("codeclient.files.git")) + .append(Text.literal("\n")) + .append(Text.translatable("codeclient.files.open_native").fillStyle( + Style.EMPTY + .withColor(Formatting.AQUA) + .withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, currentPath.toAbsolutePath().toString())) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(currentPath.toAbsolutePath().toString()))))) + , ChatType.INFO); + invalid = false; + break; + } + } + list.close(); + } catch (Exception ignored) { + Utility.sendMessage(Text.translatable("codeclient.files.error.read_folder"), ChatType.FAIL); + } + if (invalid) { + Utility.sendMessage(Text.translatable("codeclient.files.empty_dir")); + return -1; + } - },scan); - CodeClient.currentAction.init(); - return 0; - } - else { - Utility.sendMessage(Text.translatable("codeclient.warning.dev_mode"), ChatType.FAIL); - return 1; - } - })) + Utility.sendMessage(Text.translatable("codeclient.action.scanning").append(" ").append(Text.translatable("codeclient.action.abort")), ChatType.INFO); + var scan = new ArrayList(); + Path finalCurrentPath = currentPath; + CodeClient.currentAction = new ScanPlot(() -> { + actionCallback(); + for (ItemStack item : scan) { + String data = Utility.templateDataItem(item); + var template = Template.parse64(data); + if (template == null) continue; + var first = template.blocks.get(0); + String name = Objects.requireNonNullElse(first.action != null ? first.action : first.data, "unknown"); + var filePath = finalCurrentPath.resolve(name + ".dft"); + try { + Files.write(filePath, Base64.getDecoder().decode(data)); + } catch (Exception ignored) { + Utility.sendMessage(Text.translatable("codeclient.files.error.write_file", filePath), ChatType.FAIL); + } + } + + }, scan); + CodeClient.currentAction.init(); + return 0; + } else { + Utility.sendMessage(Text.translatable("codeclient.warning.dev_mode"), ChatType.FAIL); + return 1; + } + })) ); dispatcher.register(literal("scanfor").then(argument("name", StringArgumentType.greedyString()).executes(context -> { - if(CodeClient.location instanceof Dev dev) { + if (CodeClient.location instanceof Dev dev) { Pattern pattern = Pattern.compile(context.getArgument("name", String.class), Pattern.CASE_INSENSITIVE); var scan = dev.scanForSigns(pattern); Utility.sendMessage(Text.translatable("codeclient.action.scanfor.scan_result")); - for (var res: scan.entrySet()) { - Utility.sendMessage("- " + res.getKey() + ": " + res.getValue().getMessage(1,false).getString()); + for (var res : scan.entrySet()) { + Utility.sendMessage("- " + res.getKey() + ": " + res.getValue().getMessage(1, false).getString()); } return 0; } @@ -303,16 +299,16 @@ else if(!Files.isDirectory(currentPath)) { // return -1; // })); dispatcher.register(literal("templateplacer").executes(context -> { - if(CodeClient.location instanceof Dev) { + if (CodeClient.location instanceof Dev) { var action = Utility.createPlacer(Utility.templatesInInventory(), Commands::actionCallback); - if(action == null) return -1; + if (action == null) return -1; CodeClient.currentAction = action; CodeClient.currentAction.init(); return 0; } - Utility.sendMessage(Text.translatable("codeclient.warning.dev_mode"),ChatType.FAIL); + Utility.sendMessage(Text.translatable("codeclient.warning.dev_mode"), ChatType.FAIL); return -1; - }).then(argument("path",StringArgumentType.greedyString()).suggests(Commands::suggestTemplates).executes(context -> { + }).then(argument("path", StringArgumentType.greedyString()).suggests(Commands::suggestTemplates).executes(context -> { try { if (CodeClient.location instanceof Dev dev) { var map = new HashMap(); @@ -326,35 +322,32 @@ else if(!Files.isDirectory(currentPath)) { } Utility.sendMessage(Text.translatable("codeclient.warning.dev_mode"), ChatType.FAIL); return -1; - } - catch (Exception e) { - Utility.sendMessage(Text.translatable("codeclient.files.template_fail"),ChatType.FAIL); + } catch (Exception e) { + Utility.sendMessage(Text.translatable("codeclient.files.template_fail"), ChatType.FAIL); return -2; } }))); dispatcher.register(literal("save").then(argument("path", StringArgumentType.greedyString()).suggests(Commands::suggestDirectories).executes(context -> { String data = Utility.templateDataItem(CodeClient.MC.player.getMainHandStack()); - if(data == null) { - Utility.sendMessage(Text.translatable("codeclient.files.hold_template"),ChatType.FAIL); + if (data == null) { + Utility.sendMessage(Text.translatable("codeclient.files.hold_template"), ChatType.FAIL); return 0; } - String arg = context.getArgument("path",String.class); + String arg = context.getArgument("path", String.class); String[] path = arg.split("/"); Path currentPath = FileManager.templatesPath(); // Create folders - for (String dir: Arrays.stream(path).toList().subList(0,path.length - 1)) { + for (String dir : Arrays.stream(path).toList().subList(0, path.length - 1)) { currentPath = currentPath.resolve(dir); - if(Files.notExists(currentPath)) { + if (Files.notExists(currentPath)) { try { Files.createDirectory(currentPath); + } catch (Exception ignored) { + Utility.sendMessage(Text.translatable("codeclient.files.error.write_folder", currentPath)); } - catch (Exception ignored) { - Utility.sendMessage(Text.translatable("codeclient.files.error.write_folder",currentPath)); - } - } - else if(!Files.isDirectory(currentPath)) { - Utility.sendMessage(Text.translatable("codeclient.files.error.not_dir",currentPath), ChatType.FAIL); + } else if (!Files.isDirectory(currentPath)) { + Utility.sendMessage(Text.translatable("codeclient.files.error.not_dir", currentPath), ChatType.FAIL); return -1; } } @@ -362,19 +355,18 @@ else if(!Files.isDirectory(currentPath)) { // Write file try { Files.write(currentPath.resolve(currentPath), Base64.getDecoder().decode(data)); - Utility.sendMessage(Text.translatable("codeclient.files.saved",currentPath),ChatType.SUCCESS); - } - catch (Exception e) { - Utility.sendMessage(Text.translatable("codeclient.files.error.write_file",currentPath), ChatType.FAIL); + Utility.sendMessage(Text.translatable("codeclient.files.saved", currentPath), ChatType.SUCCESS); + } catch (Exception e) { + Utility.sendMessage(Text.translatable("codeclient.files.error.write_file", currentPath), ChatType.FAIL); CodeClient.LOGGER.error(e.getMessage()); } return 0; }))); dispatcher.register(literal("load").then(argument("path", StringArgumentType.greedyString()).suggests(Commands::suggestTemplates).executes(context -> { - if(CodeClient.MC.player.isCreative()) { - String arg = context.getArgument("path",String.class); + if (CodeClient.MC.player.isCreative()) { + String arg = context.getArgument("path", String.class); Path path = FileManager.templatesPath().resolve(arg + ".dft"); - if(Files.notExists(path)) { + if (Files.notExists(path)) { Utility.sendMessage(Text.translatable("codeclient.files.error.cant_read"), ChatType.FAIL); return -1; } @@ -384,56 +376,54 @@ else if(!Files.isDirectory(currentPath)) { template.setCustomName(Text.empty().formatted(Formatting.RED).append("Saved Template").append(Text.literal(" » ").formatted(Formatting.DARK_RED, Formatting.BOLD)).append(String.valueOf(FileManager.templatesPath().relativize(path)))); CodeClient.MC.player.giveItemStack(template); Utility.sendInventory(); - } - catch (Exception e) { - Utility.sendMessage(Text.translatable("codeclient.files.error.read_file",path), ChatType.FAIL); + } catch (Exception e) { + Utility.sendMessage(Text.translatable("codeclient.files.error.read_file", path), ChatType.FAIL); return -2; } return 0; } - Utility.sendMessage(Text.translatable("codeclient.warning.creative_mode"),ChatType.FAIL); + Utility.sendMessage(Text.translatable("codeclient.warning.creative_mode"), ChatType.FAIL); return -1; - }))); + }))); dispatcher.register(literal("swap").then(argument("path", StringArgumentType.greedyString()).suggests(Commands::suggestTemplates).executes(context -> { Path path = FileManager.templatesPath().resolve(context.getArgument("path", String.class)); try { - ArrayList map = new ArrayList<>(); - for (var template: Objects.requireNonNull(getAllTemplates(path))) { + ArrayList map = new ArrayList<>(); + for (var template : Objects.requireNonNull(getAllTemplates(path))) { map.add(Utility.makeTemplate(template)); } confirm = Utility.createSwapper(map, Commands::actionCallback).swap(); - Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.use"),ChatType.INFO); + Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.use"), ChatType.INFO); } catch (IOException e) { - Utility.sendMessage(Text.translatable("codeclient.files.error.read_file",path),ChatType.FAIL); + Utility.sendMessage(Text.translatable("codeclient.files.error.read_file", path), ChatType.FAIL); } return 0; }))); dispatcher.register(literal("delete").then(argument("path", StringArgumentType.greedyString()).suggests(Commands::suggestTemplates).executes(context -> { - Path path = FileManager.templatesPath().resolve(context.getArgument("path",String.class)); + Path path = FileManager.templatesPath().resolve(context.getArgument("path", String.class)); Path dft = path.getParent().resolve(path.getFileName() + ".dft"); - if(Files.notExists(path) && Files.exists(dft)) path = dft; - if(!path.toAbsolutePath().startsWith(FileManager.templatesPath().toAbsolutePath())) { - Utility.sendMessage(Text.translatable("codeclient.files.not_in_templates"),ChatType.INFO); + if (Files.notExists(path) && Files.exists(dft)) path = dft; + if (!path.toAbsolutePath().startsWith(FileManager.templatesPath().toAbsolutePath())) { + Utility.sendMessage(Text.translatable("codeclient.files.not_in_templates"), ChatType.INFO); return -2; } - if(Files.notExists(path)) { - Utility.sendMessage(Text.translatable("codeclient.files.error.not_found"),ChatType.FAIL); + if (Files.notExists(path)) { + Utility.sendMessage(Text.translatable("codeclient.files.error.not_found"), ChatType.FAIL); return -1; } try { FileUtils.forceDelete(path.toFile()); - Utility.sendMessage(Text.translatable("codeclient.files.deleted",path),ChatType.SUCCESS); - } - catch (Exception e) { - Utility.sendMessage(Text.translatable("codeclient.files.error.cant_delete"),ChatType.FAIL); + Utility.sendMessage(Text.translatable("codeclient.files.deleted", path), ChatType.SUCCESS); + } catch (Exception e) { + Utility.sendMessage(Text.translatable("codeclient.files.error.cant_delete"), ChatType.FAIL); } return 0; }))); dispatcher.register(literal("jumptofreespot").executes(context -> { - if(CodeClient.location instanceof Dev dev) { - CodeClient.currentAction = new GoTo(dev.findFreePlacePos(CodeClient.MC.player.getBlockPos()).toCenterPos().add(0,-0.5,0), Commands::actionCallback); + if (CodeClient.location instanceof Dev dev) { + CodeClient.currentAction = new GoTo(dev.findFreePlacePos(CodeClient.MC.player.getBlockPos()).toCenterPos().add(0, -0.5, 0), Commands::actionCallback); CodeClient.currentAction.init(); return 0; } @@ -442,15 +432,15 @@ else if(!Files.isDirectory(currentPath)) { dispatcher.register(literal("confirmcc").executes(context -> { - if(confirm == null) { - Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.nothing"),ChatType.INFO); + if (confirm == null) { + Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.nothing"), ChatType.INFO); return 0; } - if(!(CodeClient.currentAction instanceof None)) { - Utility.sendMessage(Text.translatable("codeclient.action.busy").append(" ").append(Text.translatable("codeclient.action.abort")),ChatType.FAIL); + if (!(CodeClient.currentAction instanceof None)) { + Utility.sendMessage(Text.translatable("codeclient.action.busy").append(" ").append(Text.translatable("codeclient.action.abort")), ChatType.FAIL); return -1; } - Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.confirm"),ChatType.SUCCESS); + Utility.sendMessage(Text.translatable("codeclient.action.confirmcc.confirm"), ChatType.SUCCESS); CodeClient.currentAction = confirm; CodeClient.currentAction.init(); confirm = null; @@ -459,49 +449,52 @@ else if(!Files.isDirectory(currentPath)) { } private static CompletableFuture suggestDirectories(CommandContext context, SuggestionsBuilder builder) { - return suggestTemplates(context,builder,false); + return suggestTemplates(context, builder, false); } + private static CompletableFuture suggestTemplates(CommandContext context, SuggestionsBuilder builder) { - return suggestTemplates(context,builder,true); + return suggestTemplates(context, builder, true); } + private static CompletableFuture suggestTemplates(CommandContext ignored, SuggestionsBuilder builder, boolean suggestFiles) { try { var possibilities = new ArrayList(); - String[] path = builder.getRemaining().split("/",-1); - String currentPath = String.join("/", (Arrays.stream(path).toList().subList(0,path.length - 1))); + String[] path = builder.getRemaining().split("/", -1); + String currentPath = String.join("/", (Arrays.stream(path).toList().subList(0, path.length - 1))); var list = Files.list(FileManager.templatesPath().resolve(currentPath)); - for (var file: list.toList()) { - if(file.getFileName().toString().equals(".git")) continue; + for (var file : list.toList()) { + if (file.getFileName().toString().equals(".git")) continue; String s = currentPath.isEmpty() ? "" : currentPath + "/"; - if(Files.isDirectory(file)) possibilities.add(s + file.getFileName().toString() + "/"); - else if(file.getFileName().toString().endsWith(".dft")) { + if (Files.isDirectory(file)) possibilities.add(s + file.getFileName().toString() + "/"); + else if (file.getFileName().toString().endsWith(".dft")) { String name = file.getFileName().toString(); - if(suggestFiles) possibilities.add(s + name.substring(0, name.length() - 4)); + if (suggestFiles) possibilities.add(s + name.substring(0, name.length() - 4)); } } list.close(); - for (String possibility: possibilities) { - if(possibility.toLowerCase().contains(builder.getRemainingLowerCase())) builder.suggest(possibility,Text.literal("Folder")); + for (String possibility : possibilities) { + if (possibility.toLowerCase().contains(builder.getRemainingLowerCase())) + builder.suggest(possibility, Text.literal("Folder")); } - } catch (IOException ignored1) {} + } catch (IOException ignored1) { + } return CompletableFuture.completedFuture(builder.build()); } private static List getAllTemplates(Path path) throws IOException { - if(Files.notExists(path)) { + if (Files.notExists(path)) { Path asName = path.getParent().resolve(path.getFileName() + ".dft"); - if(Files.exists(asName)) return getAllTemplates(asName); + if (Files.exists(asName)) return getAllTemplates(asName); return null; } - if(Files.isDirectory(path)) { + if (Files.isDirectory(path)) { var list = new ArrayList(); var files = Files.list(path); - for (var file: files.toList()) list.addAll(getAllTemplates(file)); + for (var file : files.toList()) list.addAll(getAllTemplates(file)); files.close(); return list; - } - else { + } else { byte[] data = Files.readAllBytes(path); return Collections.singletonList(new String(Base64.getEncoder().encode(data))); } diff --git a/src/main/java/dev/dfonline/codeclient/Event.java b/src/main/java/dev/dfonline/codeclient/Event.java index f4741e9b..969a63f1 100644 --- a/src/main/java/dev/dfonline/codeclient/Event.java +++ b/src/main/java/dev/dfonline/codeclient/Event.java @@ -2,8 +2,8 @@ import dev.dfonline.codeclient.config.Config; import dev.dfonline.codeclient.location.*; -import net.minecraft.network.packet.Packet; import net.minecraft.network.listener.PacketListener; +import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.c2s.play.CommandExecutionC2SPacket; import net.minecraft.network.packet.s2c.play.*; @@ -19,41 +19,41 @@ public class Event { private static boolean switchingMode = false; public static void handlePacket(Packet packet) { - if(packet instanceof ClearTitleS2CPacket clear) { + if (packet instanceof ClearTitleS2CPacket clear) { if (clear.shouldReset()) step = Sequence.WAIT_FOR_POS; } - if(packet instanceof PlayerPositionLookS2CPacket pos) { + if (packet instanceof PlayerPositionLookS2CPacket pos) { x = pos.getX(); z = pos.getZ(); - if(step == Sequence.WAIT_FOR_POS) step = Sequence.WAIT_FOR_MESSAGE; + if (step == Sequence.WAIT_FOR_POS) step = Sequence.WAIT_FOR_MESSAGE; } - if(packet instanceof OverlayMessageS2CPacket overlay) { + if (packet instanceof OverlayMessageS2CPacket overlay) { if (step == Sequence.WAIT_FOR_MESSAGE && overlay.getMessage().getString().startsWith("DiamondFire - ")) { updateLocation(new Spawn()); } } - if(packet instanceof GameMessageS2CPacket message) { - if(step == Sequence.WAIT_FOR_MESSAGE) { + if (packet instanceof GameMessageS2CPacket message) { + if (step == Sequence.WAIT_FOR_MESSAGE) { String content = message.content().getString(); - if(content.equals("» You are now in dev mode.")) { - updateLocation(new Dev(x,z)); + if (content.equals("» You are now in dev mode.")) { + updateLocation(new Dev(x, z)); } - if(content.equals("» You are now in build mode.")) { + if (content.equals("» You are now in build mode.")) { updateLocation(new Build()); } - if(content.startsWith("» Joined game: ")) { + if (content.startsWith("» Joined game: ")) { updateLocation(new Play()); } } } - if(packet instanceof GameJoinS2CPacket) { + if (packet instanceof GameJoinS2CPacket) { updateLocation(new Spawn()); } } public static void onSendPacket(Packet packet) { - if(packet instanceof CommandExecutionC2SPacket command) { - if(List.of("play","build","code","dev").contains(command.command().replaceFirst("mode ",""))) { + if (packet instanceof CommandExecutionC2SPacket command) { + if (List.of("play", "build", "code", "dev").contains(command.command().replaceFirst("mode ", ""))) { switchingMode = true; } } @@ -62,12 +62,12 @@ public static void onSendPacket(Packet packet) { public static void updateLocation(Location location) { CodeClient.lastLocation = CodeClient.location; CodeClient.location = location; - if(switchingMode) { + if (switchingMode) { switchingMode = false; - if(location instanceof Plot plot && CodeClient.lastLocation instanceof Plot last) plot.copyValuesFrom(last); + if (location instanceof Plot plot && CodeClient.lastLocation instanceof Plot last) + plot.copyValuesFrom(last); CodeClient.LOGGER.info("Switched location: " + location.name()); - } - else CodeClient.LOGGER.info("Changed location: " + location.name()); + } else CodeClient.LOGGER.info("Changed location: " + location.name()); step = Sequence.WAIT_FOR_CLEAR; CodeClient.LOGGER.info("" + Config.getConfig().InvisibleBlocksInDev); if (Config.getConfig().InvisibleBlocksInDev) CodeClient.shouldReload = true; diff --git a/src/main/java/dev/dfonline/codeclient/FileManager.java b/src/main/java/dev/dfonline/codeclient/FileManager.java index 7ac7be75..9cae516a 100644 --- a/src/main/java/dev/dfonline/codeclient/FileManager.java +++ b/src/main/java/dev/dfonline/codeclient/FileManager.java @@ -13,9 +13,10 @@ public class FileManager { /** * Verify the existence and get the mod data folder. + * * @return */ - public static Path Path(){ + public static Path Path() { Path path = CodeClient.MC.runDirectory.toPath().resolve(CodeClient.MOD_ID); path.toFile().mkdir(); return path; @@ -34,14 +35,16 @@ public static Path writeFile(String fileName, String content) throws IOException public static File getConfigFile() { return new File(FabricLoader.getInstance().getConfigDir().toFile(), CodeClient.MOD_ID + ".json"); } + public static void writeConfig(String content) throws IOException { boolean ignore; File file = getConfigFile(); Files.deleteIfExists(file.toPath()); Files.createFile(file.toPath()); - if(!file.exists()) ignore = file.createNewFile(); + if (!file.exists()) ignore = file.createNewFile(); Files.write(file.toPath(), content.getBytes(), StandardOpenOption.WRITE); } + public static String readConfig() throws IOException { return Files.readString(getConfigFile().toPath()); } @@ -50,10 +53,9 @@ public static Path writeFile(String fileName, String content, boolean doCharSet) Path path = Path().resolve(fileName); Files.deleteIfExists(path); Files.createFile(path); - if(doCharSet) { + if (doCharSet) { Files.write(path, content.getBytes(Config.getConfig().SaveCharSet.charSet), StandardOpenOption.WRITE); - } - else { + } else { Files.write(path, content.getBytes(), StandardOpenOption.WRITE); } return path; diff --git a/src/main/java/dev/dfonline/codeclient/MoveToLocation.java b/src/main/java/dev/dfonline/codeclient/MoveToLocation.java index 900b02b0..7cb586d6 100644 --- a/src/main/java/dev/dfonline/codeclient/MoveToLocation.java +++ b/src/main/java/dev/dfonline/codeclient/MoveToLocation.java @@ -9,6 +9,7 @@ */ public class MoveToLocation { private final ClientPlayerEntity player; + public MoveToLocation(ClientPlayerEntity player) { this.player = player; } @@ -20,20 +21,24 @@ public MoveToLocation(ClientPlayerEntity player) { public static Vec3d shiftTowards(Vec3d origin, Vec3d location) { Vec3d pos = origin.relativize(location); double maxLength = 9.9; - if(pos.length() > maxLength) { + if (pos.length() > maxLength) { return origin.add(pos.normalize().multiply(maxLength)); - } - else { + } else { return location; } } + public static void shove(ClientPlayerEntity player, Vec3d location) { + new MoveToLocation(player).teleportTowards(player.getPos(), location); + } + public void setPos(Vec3d pos) { setPos(pos.x, pos.y, pos.z); } + public void setPos(double x, double y, double z) { - if(CodeClient.MC.getNetworkHandler() == null) return; - if(new Vec3d(x,y,x).distanceTo(player.getPos()) > 10) { + if (CodeClient.MC.getNetworkHandler() == null) return; + if (new Vec3d(x, y, x).distanceTo(player.getPos()) > 10) { // I've always done it like this, problems? CodeClient.MC.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.OnGroundOnly(false)); CodeClient.MC.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.OnGroundOnly(false)); @@ -51,14 +56,10 @@ public void setPos(double x, double y, double z) { CodeClient.MC.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(x, y, z, false)); } - public static void shove(ClientPlayerEntity player, Vec3d location) { - new MoveToLocation(player).teleportTowards(player.getPos(), location); - } - /** * Moves the player up to 10 blocks towards `to` from `from` */ public void teleportTowards(Vec3d from, Vec3d to) { - setPos(shiftTowards(from,to)); + setPos(shiftTowards(from, to)); } } diff --git a/src/main/java/dev/dfonline/codeclient/OverlayManager.java b/src/main/java/dev/dfonline/codeclient/OverlayManager.java index aa103ca8..ef589a7a 100644 --- a/src/main/java/dev/dfonline/codeclient/OverlayManager.java +++ b/src/main/java/dev/dfonline/codeclient/OverlayManager.java @@ -16,13 +16,6 @@ public static List getOverlayText() { return overlayText; } - /** - * Clears the overlay text. - */ - public static void setOverlayText() { - setOverlayText(new ArrayList<>()); - } - /** * Clears and sets the overlay text. */ @@ -37,6 +30,13 @@ public static void setOverlayText(ArrayList overlayText) { OverlayManager.overlayText = overlayText; } + /** + * Clears the overlay text. + */ + public static void setOverlayText() { + setOverlayText(new ArrayList<>()); + } + public static void addOverlayText(Text overlayText) { OverlayManager.overlayText.add(overlayText); } diff --git a/src/main/java/dev/dfonline/codeclient/Utility.java b/src/main/java/dev/dfonline/codeclient/Utility.java index 88ced1d4..8fba2b9c 100644 --- a/src/main/java/dev/dfonline/codeclient/Utility.java +++ b/src/main/java/dev/dfonline/codeclient/Utility.java @@ -3,10 +3,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import dev.dfonline.codeclient.action.Action; -import dev.dfonline.codeclient.action.None; import dev.dfonline.codeclient.action.impl.PlaceTemplates; -import dev.dfonline.codeclient.hypercube.item.BlockTag; import dev.dfonline.codeclient.hypercube.template.Template; import dev.dfonline.codeclient.hypercube.template.TemplateBlock; import dev.dfonline.codeclient.location.Dev; @@ -23,14 +20,12 @@ import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; import net.minecraft.text.MutableText; -import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.text.TextColor; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import org.apache.commons.lang3.ObjectUtils; -import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.ByteArrayOutputStream; @@ -45,10 +40,9 @@ public class Utility { * Get the slot id to be used with a creative packet, from a local slot id. */ public static int getRemoteSlot(int slot) { - if(0 <= slot && slot <= 8) { // this is for the hotbar, which is after the inventory in packets. + if (0 <= slot && slot <= 8) { // this is for the hotbar, which is after the inventory in packets. return slot + 36; - } - else return slot; + } else return slot; } /** @@ -62,6 +56,7 @@ public static void sendInventory() { /** * Ensure the player is holding an item, by holding and setting the first slot. + * * @param item Any item */ public static void makeHolding(ItemStack item) { @@ -74,6 +69,7 @@ public static void makeHolding(ItemStack item) { public static void debug(Object object) { debug(Objects.toString(object)); } + public static void debug(String message) { CodeClient.LOGGER.info("%%% DEBUG: " + message); } @@ -96,7 +92,7 @@ public static ItemStack makeTemplate(String message) { ItemStack template = new ItemStack(Items.ENDER_CHEST); NbtCompound nbt = new NbtCompound(); NbtCompound PublicBukkitValues = new NbtCompound(); - PublicBukkitValues.putString("hypercube:codetemplatedata","{\"author\":\"CodeClient\",\"name\":\"Template to be placed\",\"version\":1,\"code\":\"" + message + "\"}"); + PublicBukkitValues.putString("hypercube:codetemplatedata", "{\"author\":\"CodeClient\",\"name\":\"Template to be placed\",\"version\":1,\"code\":\"" + message + "\"}"); nbt.put("PublicBukkitValues", PublicBukkitValues); template.setNbt(nbt); return template; @@ -114,7 +110,7 @@ public static Template templateItem(ItemStack item) { * Doesn't add .swap(), that needs to be added yourself. */ public static PlaceTemplates createSwapper(List templates, Callback callback) { - if(CodeClient.location instanceof Dev dev) { + if (CodeClient.location instanceof Dev dev) { HashMap map = new HashMap<>(); var scan = dev.scanForSigns(Pattern.compile(".*")); ArrayList leftOvers = new ArrayList<>(templates); @@ -128,28 +124,27 @@ public static PlaceTemplates createSwapper(List templates, Callback c String codeTemplateData = publicBukkit.getString("hypercube:codetemplatedata"); try { Template template = Template.parse64(JsonParser.parseString(codeTemplateData).getAsJsonObject().get("code").getAsString()); - if(template.blocks.isEmpty()) continue; + if (template.blocks.isEmpty()) continue; TemplateBlock block = template.blocks.get(0); - if(block.block == null) continue; + if (block.block == null) continue; TemplateBlock.Block blockName = TemplateBlock.Block.valueOf(block.block.toUpperCase()); String name = ObjectUtils.firstNonNull(block.action, block.data); - for (Map.Entry sign: scan.entrySet()) { // Loop through scanned signs + for (Map.Entry sign : scan.entrySet()) { // Loop through scanned signs SignText text = sign.getValue(); // ↓ If the blockName and name match - if(text.getMessage(0,false).getString().equals(blockName.name) && text.getMessage(1,false).getString().equals(name)) { + if (text.getMessage(0, false).getString().equals(blockName.name) && text.getMessage(1, false).getString().equals(name)) { map.put(sign.getKey().east(), item); // Put it into map leftOvers.remove(item); // Remove the template, so we can see if there's anything left over break; // break out :D } } - } - catch (Exception e) { + } catch (Exception e) { CodeClient.LOGGER.warn(e.getMessage()); } } - if(!leftOvers.isEmpty()) { + if (!leftOvers.isEmpty()) { BlockPos freePos = dev.findFreePlacePos(); for (var item : leftOvers) { - map.put(freePos,item); + map.put(freePos, item); freePos = dev.findFreePlacePos(freePos.west(2)); } } @@ -163,7 +158,7 @@ public static PlaceTemplates createSwapper(List templates, Callback c * This will use any free spaces instead. */ public static PlaceTemplates createPlacer(List templates, Callback callback) { - return createPlacer(templates,callback,false); + return createPlacer(templates, callback, false); } /** @@ -171,29 +166,27 @@ public static PlaceTemplates createPlacer(List templates, Callback ca * This will use any free spaces instead. */ public static PlaceTemplates createPlacer(List templates, Callback callback, boolean compacter) { - if(CodeClient.location instanceof Dev dev) { + if (CodeClient.location instanceof Dev dev) { var map = new HashMap(); - if(!compacter) { + if (!compacter) { BlockPos lastPos = dev.findFreePlacePos(); - for (var template: templates) { + for (var template : templates) { map.put(lastPos, template); lastPos = dev.findFreePlacePos(lastPos.west(2)); } - } - else { + } else { BlockPos nextPos = dev.findFreePlacePos(); - for (var template: templates) { + for (var template : templates) { int size = Template.parse64(Utility.templateDataItem(template)).getLength(); var placePos = nextPos; var templateEndPos = placePos.south(size); - if(dev.isInDev(templateEndPos)) { + if (dev.isInDev(templateEndPos)) { nextPos = templateEndPos; - } - else { + } else { placePos = dev.findFreePlacePos(placePos.west(2)); nextPos = placePos.south(size); } - map.put(placePos,template); + map.put(placePos, template); } } return new PlaceTemplates(map, callback); @@ -201,12 +194,12 @@ public static PlaceTemplates createPlacer(List templates, Callback ca return null; } - public static void addLore(ItemStack stack, Text ...lore) { + public static void addLore(ItemStack stack, Text... lore) { var display = stack.getSubNbt("display"); var loreList = new NbtList(); - for (Text line: lore) loreList.add(Utility.nbtify(Text.empty().append(line))); - display.put("Lore",loreList); - stack.setSubNbt("display",display); + for (Text line : lore) loreList.add(Utility.nbtify(Text.empty().append(line))); + display.put("Lore", loreList); + stack.setSubNbt("display", display); } public static void sendHandItem(ItemStack item) { @@ -237,6 +230,7 @@ public static String compileTemplate(JsonObject data) throws IOException { /** * GZIPs and base64's data for use in templates. + * * @throws IOException If an I/O error happened with gzip */ public static String compileTemplate(String data) throws IOException { @@ -261,6 +255,7 @@ public static void sendMessage(String message, ChatType type) { public static void sendMessage(String message) { sendMessage(Text.literal(message), ChatType.INFO); } + public static void sendMessage(Text message) { sendMessage(message, ChatType.INFO); } @@ -283,24 +278,25 @@ public static void sendMessage(Text message, @Nullable ChatType type) { /** * Prepares a text object for use in an item's display tag + * * @return Usable in lore and as a name in nbt. */ public static NbtString nbtify(Text text) { JsonElement json = Text.Serialization.toJsonTree(text); - if(json.isJsonObject()) { + if (json.isJsonObject()) { JsonObject obj = (JsonObject) json; - if(!obj.has("color")) obj.addProperty("color","white"); - if(!obj.has("italic")) obj.addProperty("italic",false); - if(!obj.has("bold")) obj.addProperty("bold",false); + if (!obj.has("color")) obj.addProperty("color", "white"); + if (!obj.has("italic")) obj.addProperty("italic", false); + if (!obj.has("bold")) obj.addProperty("bold", false); return NbtString.of(obj.toString()); - } - else return NbtString.of(json.toString()); + } else return NbtString.of(json.toString()); } /** * Parses § formatted strings. + * * @param text § formatted string. * @return Text with all parsed text as siblings. */ @@ -311,15 +307,13 @@ public static MutableText textFromString(String text) { Matcher m = Pattern.compile("§(([0-9a-kfmnolr])|x(§[0-9a-f]){6})|[^§]+").matcher(text); while (m.find()) { String data = m.group(); - if(data.startsWith("§")) { - if(data.startsWith("§x")) { - component = component.setStyle(component.getStyle().withColor(Integer.valueOf(data.replaceAll("§x|§",""), 16))); - } - else { + if (data.startsWith("§")) { + if (data.startsWith("§x")) { + component = component.setStyle(component.getStyle().withColor(Integer.valueOf(data.replaceAll("§x|§", ""), 16))); + } else { component = component.formatted(Formatting.byCode(data.charAt(1))); } - } - else { + } else { component.append(data); output.append(component); component = Text.empty().setStyle(component.getStyle()); @@ -329,18 +323,19 @@ public static MutableText textFromString(String text) { } public static boolean isGlitchStick(ItemStack item) { - if(item == null) return false; + if (item == null) return false; NbtCompound nbt = item.getNbt(); - if(nbt == null) return false; - if(nbt.isEmpty()) return false; - if(Objects.equals(nbt.getCompound("PublicBukkitValues").getString("hypercube:item_instance"), "")) return false; + if (nbt == null) return false; + if (nbt.isEmpty()) return false; + if (Objects.equals(nbt.getCompound("PublicBukkitValues").getString("hypercube:item_instance"), "")) + return false; return Objects.equals(nbt.getCompound("display").getString("Name"), "{\"italic\":false,\"color\":\"red\",\"text\":\"Glitch Stick\"}"); } public static HashMap getBlockTagLines(ItemStack item) { NbtCompound display = item.getSubNbt("display"); NbtList lore = (NbtList) display.get("Lore"); - if(lore == null) throw new NullPointerException("Can't get lore."); + if (lore == null) throw new NullPointerException("Can't get lore."); HashMap options = new HashMap<>(); @@ -348,10 +343,10 @@ public static HashMap getBlockTagLines(ItemStack item) { NbtElement element = lore.get(index); Text text = Text.Serialization.fromJson(element.asString()); var data = text.getString(); - if(data.isBlank() || data.equals("Default Value:")) { + if (data.isBlank() || data.equals("Default Value:")) { break; } - options.put(index, data.replaceAll("» ","")); + options.put(index, data.replaceAll("» ", "")); } return options; diff --git a/src/main/java/dev/dfonline/codeclient/action/Action.java b/src/main/java/dev/dfonline/codeclient/action/Action.java index d651f83a..77c15167 100644 --- a/src/main/java/dev/dfonline/codeclient/action/Action.java +++ b/src/main/java/dev/dfonline/codeclient/action/Action.java @@ -5,6 +5,7 @@ public abstract class Action { private final Callback callback; + public Action(Callback callback) { this.callback = callback; } @@ -19,7 +20,8 @@ public boolean onSendPacket(Packet packet) { return false; } - public void onTick() {} + public void onTick() { + } protected void callback() { this.callback.run(); diff --git a/src/main/java/dev/dfonline/codeclient/action/None.java b/src/main/java/dev/dfonline/codeclient/action/None.java index 84295ac9..a548cd83 100644 --- a/src/main/java/dev/dfonline/codeclient/action/None.java +++ b/src/main/java/dev/dfonline/codeclient/action/None.java @@ -4,11 +4,13 @@ public class None extends Action { public None() { - super(() -> {}); + super(() -> { + }); this.init(); } - @Override public void init() { + @Override + public void init() { OverlayManager.setOverlayText(); } } diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/ClearPlot.java b/src/main/java/dev/dfonline/codeclient/action/impl/ClearPlot.java index 842830cf..d6194ff5 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/ClearPlot.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/ClearPlot.java @@ -32,9 +32,9 @@ public void init() { @Override public boolean onReceivePacket(Packet packet) { - if(packet instanceof InventoryS2CPacket inventoryS2CPacket) { - if(currentStep == Step.WAIT_FOR_OPTIONS) { - for (int i : List.of(9,14,15,44)) { + if (packet instanceof InventoryS2CPacket inventoryS2CPacket) { + if (currentStep == Step.WAIT_FOR_OPTIONS) { + for (int i : List.of(9, 14, 15, 44)) { ItemStack itemStack = inventoryS2CPacket.getContents().get(i); Int2ObjectMap modified = Int2ObjectMaps.singleton(i, new ItemStack(Items.AIR)); CodeClient.MC.getNetworkHandler().sendPacket(new ClickSlotC2SPacket(inventoryS2CPacket.getSyncId(), inventoryS2CPacket.getRevision(), i, 0, SlotActionType.PICKUP, itemStack, modified)); @@ -42,10 +42,10 @@ public boolean onReceivePacket(Packet packet) { currentStep = Step.WAIT_FOR_CLEAR; return true; } - if(currentStep == Step.WAIT_FOR_CLEAR) { + if (currentStep == Step.WAIT_FOR_CLEAR) { int i = 11; ItemStack itemStack = inventoryS2CPacket.getContents().get(i); - if(itemStack.getItem().equals(Items.GREEN_CONCRETE)) { + if (itemStack.getItem().equals(Items.GREEN_CONCRETE)) { Int2ObjectMap modified = Int2ObjectMaps.singleton(i, new ItemStack(Items.AIR)); CodeClient.MC.getNetworkHandler().sendPacket(new ClickSlotC2SPacket(inventoryS2CPacket.getSyncId(), inventoryS2CPacket.getRevision(), i, 0, SlotActionType.PICKUP, itemStack, modified)); currentStep = Step.DONE; @@ -54,11 +54,11 @@ public boolean onReceivePacket(Packet packet) { } } } - if(currentStep != Step.DONE) { - if(packet instanceof InventoryS2CPacket) return true; - if(packet instanceof PlaySoundS2CPacket) return true; - if(packet instanceof OpenScreenS2CPacket) return true; - if(packet instanceof ScreenHandlerSlotUpdateS2CPacket) return true; + if (currentStep != Step.DONE) { + if (packet instanceof InventoryS2CPacket) return true; + if (packet instanceof PlaySoundS2CPacket) return true; + if (packet instanceof OpenScreenS2CPacket) return true; + if (packet instanceof ScreenHandlerSlotUpdateS2CPacket) return true; } return super.onReceivePacket(packet); } diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/GetActionDump.java b/src/main/java/dev/dfonline/codeclient/action/impl/GetActionDump.java index 4b8c6872..a844bbb0 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/GetActionDump.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/GetActionDump.java @@ -7,7 +7,6 @@ import dev.dfonline.codeclient.action.Action; import net.minecraft.network.packet.Packet; import net.minecraft.network.packet.s2c.play.GameMessageS2CPacket; -import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.text.TextColor; import net.minecraft.util.Formatting; @@ -18,9 +17,8 @@ import java.util.Objects; public class GetActionDump extends Action { - public StringBuilder capturedData = null; private final ColorMode colorMode; - + public StringBuilder capturedData = null; private int lines; private int length; private Date startTime; @@ -33,7 +31,7 @@ public GetActionDump(ColorMode colorMode, Callback callback) { @Override public void init() { - if(CodeClient.MC == null || CodeClient.MC.getNetworkHandler() == null) return; + if (CodeClient.MC == null || CodeClient.MC.getNetworkHandler() == null) return; CodeClient.MC.getNetworkHandler().sendCommand("dumpactioninfo"); capturedData = new StringBuilder(); startTime = new Date(); @@ -41,23 +39,23 @@ public void init() { @Override public boolean onReceivePacket(Packet packet) { - if(capturedData == null || isDone) return false; - if(packet instanceof GameMessageS2CPacket message) { - if(message.content().getString().startsWith("Error:")) { + if (capturedData == null || isDone) return false; + if (packet instanceof GameMessageS2CPacket message) { + if (message.content().getString().startsWith("Error:")) { isDone = true; OverlayManager.setOverlayText(Text.translatable("codeclient.action.get_action_dump.error.could_not_start").formatted(Formatting.RED)); OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.error.beta_broke").formatted(Formatting.RED)); - OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.abort",Text.literal(" /abort ").formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); + OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.abort", Text.literal(" /abort ").formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); return true; } TextColor lastColor = null; - for(Text text : message.content().getSiblings()) { + for (Text text : message.content().getSiblings()) { TextColor color = text.getStyle().getColor(); - if(color != null && (lastColor != color) && (colorMode != ColorMode.NONE)) { + if (color != null && (lastColor != color) && (colorMode != ColorMode.NONE)) { lastColor = color; - if(color.getName().contains("#")) { - capturedData.append(String.join(colorMode.text,color.getName().split("")).replace("#", colorMode.text+"x").toLowerCase()); + if (color.getName().contains("#")) { + capturedData.append(String.join(colorMode.text, color.getName().split("")).replace("#", colorMode.text + "x").toLowerCase()); } else { capturedData.append(Formatting.valueOf(String.valueOf(color).toUpperCase()).toString().replace("§", colorMode.text)); } @@ -70,17 +68,17 @@ public boolean onReceivePacket(Packet packet) { length += content.length(); OverlayManager.setOverlayText(); OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.title").formatted(Formatting.GOLD)); - OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.size",Text.literal(String.valueOf(length)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); - OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.lines",Text.literal(String.valueOf(lines)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); - OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.time",Text.literal(String.valueOf((float) (new Date().getTime() - startTime.getTime()) / 1000)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); - if(Objects.equals(content, "}")) { + OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.size", Text.literal(String.valueOf(length)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); + OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.lines", Text.literal(String.valueOf(lines)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); + OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.time", Text.literal(String.valueOf((float) (new Date().getTime() - startTime.getTime()) / 1000)).formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); + if (Objects.equals(content, "}")) { isDone = true; OverlayManager.addOverlayText(Text.literal("")); OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.complete").formatted(Formatting.LIGHT_PURPLE)); - OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.abort",Text.literal(" /abort ").formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); + OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.abort", Text.literal(" /abort ").formatted(Formatting.GREEN)).formatted(Formatting.LIGHT_PURPLE)); OverlayManager.addOverlayText(Text.literal("")); try { - Path path = FileManager.writeFile("actiondump.json",capturedData.toString()); + Path path = FileManager.writeFile("actiondump.json", capturedData.toString()); OverlayManager.addOverlayText(Text.translatable("codeclient.action.get_action_dump.scanning.complete.file").formatted(Formatting.LIGHT_PURPLE)); OverlayManager.addOverlayText(Text.literal(path.toString()).formatted(Formatting.GREEN)); } catch (IOException e) { @@ -105,6 +103,7 @@ public enum ColorMode { SECTION("§"); public final String text; + ColorMode(String text) { this.text = text; } diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/GetPlotSize.java b/src/main/java/dev/dfonline/codeclient/action/impl/GetPlotSize.java index 80cd3e79..668de1da 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/GetPlotSize.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/GetPlotSize.java @@ -18,15 +18,8 @@ import net.minecraft.util.math.Direction; public class GetPlotSize extends Action { - private enum Step { - WAIT, - TP, - DONE, - } - private Step step = Step.WAIT; private ItemStack recoverMainHand; - public GetPlotSize(Callback callback) { super(callback); } @@ -37,37 +30,37 @@ public void init() { ItemStack item = Items.PAPER.getDefaultStack(); NbtCompound compound = new NbtCompound(); NbtCompound publicBukkitValues = new NbtCompound(); - publicBukkitValues.put("hypercube:varitem",NbtString.of("{\"id\":\"loc\",\"data\":{\"isBlock\":false,\"loc\":{\"x\":0.0,\"y\":256.0,\"z\":300.0,\"pitch\":0.0,\"yaw\":0.0}}}")); - compound.put("PublicBukkitValues",publicBukkitValues); + publicBukkitValues.put("hypercube:varitem", NbtString.of("{\"id\":\"loc\",\"data\":{\"isBlock\":false,\"loc\":{\"x\":0.0,\"y\":256.0,\"z\":300.0,\"pitch\":0.0,\"yaw\":0.0}}}")); + compound.put("PublicBukkitValues", publicBukkitValues); item.setNbt(compound); Utility.makeHolding(item); } @Override public void onTick() { - if(step == Step.WAIT) { + if (step == Step.WAIT) { step = Step.TP; CodeClient.MC.getNetworkHandler().sendPacket(new ClientCommandC2SPacket(CodeClient.MC.player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); CodeClient.MC.interactionManager.attackBlock(CodeClient.MC.player.getBlockPos(), Direction.UP); CodeClient.MC.getNetworkHandler().sendPacket(new HandSwingC2SPacket(Hand.MAIN_HAND)); CodeClient.MC.getNetworkHandler().sendPacket(new ClientCommandC2SPacket(CodeClient.MC.player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); - if(recoverMainHand != null) Utility.makeHolding(recoverMainHand); + if (recoverMainHand != null) Utility.makeHolding(recoverMainHand); } } @Override public boolean onReceivePacket(Packet packet) { - if(CodeClient.location instanceof Dev plot) { - if(step == Step.TP && packet instanceof PlayerPositionLookS2CPacket position) { + if (CodeClient.location instanceof Dev plot) { + if (step == Step.TP && packet instanceof PlayerPositionLookS2CPacket position) { step = Step.DONE; double size = position.getZ() - plot.getZ(); - if(size > 49) { + if (size > 49) { plot.setSize(Plot.Size.BASIC); } - if(size > 99) { + if (size > 99) { plot.setSize(Plot.Size.LARGE); } - if(size > 299) { + if (size > 299) { plot.setSize(Plot.Size.MASSIVE); } callback(); @@ -75,4 +68,10 @@ public boolean onReceivePacket(Packet packet) { } return false; } + + private enum Step { + WAIT, + TP, + DONE, + } } diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/GoTo.java b/src/main/java/dev/dfonline/codeclient/action/impl/GoTo.java index 6d5c978b..dc0f4fad 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/GoTo.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/GoTo.java @@ -4,8 +4,8 @@ import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.Utility; import dev.dfonline.codeclient.action.Action; -import dev.dfonline.codeclient.location.Dev; import dev.dfonline.codeclient.hypercube.item.Location; +import dev.dfonline.codeclient.location.Dev; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.item.ItemStack; @@ -20,6 +20,8 @@ public class GoTo extends Action { public final Vec3d target; + boolean doNotSuppress = false; + boolean complete = false; /** * If not null, we are using a location item to teleport. */ @@ -28,8 +30,6 @@ public class GoTo extends Action { private int buffer = 0; private int lastTickPackets = 1; private int thisTickPackets = 0; - boolean doNotSuppress = false; - boolean complete = false; public GoTo(Vec3d target, Callback callback) { super(callback); @@ -39,8 +39,8 @@ public GoTo(Vec3d target, Callback callback) { @Override public void init() { active = true; - if(CodeClient.MC.player == null) return; - if(CodeClient.location instanceof Dev dev && dev.isInArea(target)) { + if (CodeClient.MC.player == null) return; + if (CodeClient.location instanceof Dev dev && dev.isInArea(target)) { locationItem = new Location(dev.getPos().relativize(target)).setRotation(CodeClient.MC.player.getPitch(), CodeClient.MC.player.getYaw()).toStack(); locationItemTeleport(); } @@ -48,9 +48,9 @@ public void init() { @Override public boolean onReceivePacket(Packet packet) { - if(locationItem == null) return super.onReceivePacket(packet); - if(packet instanceof PlayerPositionLookS2CPacket tp) { - if(CodeClient.MC.getNetworkHandler() == null || CodeClient.MC.player == null) return false; + if (locationItem == null) return super.onReceivePacket(packet); + if (packet instanceof PlayerPositionLookS2CPacket tp) { + if (CodeClient.MC.getNetworkHandler() == null || CodeClient.MC.player == null) return false; CodeClient.MC.getNetworkHandler().sendPacket(new TeleportConfirmC2SPacket(tp.getTeleportId())); CodeClient.MC.player.setPosition(target); active = false; @@ -62,8 +62,8 @@ public boolean onReceivePacket(Packet packet) { @Override public boolean onSendPacket(Packet packet) { - if(packet instanceof PlayerPositionLookS2CPacket pos) { - if(doNotSuppress) doNotSuppress = false; + if (packet instanceof PlayerPositionLookS2CPacket pos) { + if (doNotSuppress) doNotSuppress = false; else return true; } return super.onSendPacket(packet); @@ -72,34 +72,34 @@ public boolean onSendPacket(Packet packet) { @Override public void onTick() { thisTickPackets = 0; - if(CodeClient.MC.player == null || CodeClient.MC.getNetworkHandler() == null) { + if (CodeClient.MC.player == null || CodeClient.MC.getNetworkHandler() == null) { callback(); return; } - CodeClient.MC.player.setVelocity(0,0,0); - if(CodeClient.MC.player.getPos().equals(target)) { + CodeClient.MC.player.setVelocity(0, 0, 0); + if (CodeClient.MC.player.getPos().equals(target)) { active = false; complete = true; callback(); return; } - if(locationItem != null) return; + if (locationItem != null) return; hackTowards(); - lastTickPackets=thisTickPackets; + lastTickPackets = thisTickPackets; } private void locationItemTeleport() { ClientPlayerEntity player = CodeClient.MC.player; ClientPlayNetworkHandler net = CodeClient.MC.getNetworkHandler(); - if(player == null || net == null) return; + if (player == null || net == null) return; ItemStack handItem = player.getMainHandStack(); Utility.sendHandItem(locationItem); boolean sneaky = !player.isSneaking(); - if(sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); + if (sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); net.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, player.getBlockPos(), Direction.UP)); net.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, player.getBlockPos(), Direction.UP)); - if(sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); + if (sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); Utility.sendHandItem(handItem); } @@ -107,28 +107,28 @@ private void locationItemTeleport() { * Use hacky movement packets. */ private void hackTowards() { - if(CodeClient.MC.player == null || CodeClient.MC.getNetworkHandler() == null) return; + if (CodeClient.MC.player == null || CodeClient.MC.getNetworkHandler() == null) return; int bufferStop = 1; int bufferReset = 0; buffer++; - if(buffer > bufferStop) { - if(buffer >= bufferReset) { + if (buffer > bufferStop) { + if (buffer >= bufferReset) { buffer = 0; } return; } - if(!active) return; - if(CodeClient.MC.player == null) return; + if (!active) return; + if (CodeClient.MC.player == null) return; Vec3d pos = CodeClient.MC.player.getPos(); Vec3d offset = pos.relativize(target); double maxLength = 50; double distance = offset.length(); Vec3d jump = distance > maxLength ? pos.add(offset.normalize().multiply(maxLength)) : target; - if(distance > 10) { - for (int i = 0; i < Math.min(lastTickPackets + 5,50); i++) { + if (distance > 10) { + for (int i = 0; i < Math.min(lastTickPackets + 5, 50); i++) { thisTickPackets++; this.doNotSuppress = true; CodeClient.MC.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.OnGroundOnly(false)); diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/MoveToSpawn.java b/src/main/java/dev/dfonline/codeclient/action/impl/MoveToSpawn.java index ab1976ce..2d81f560 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/MoveToSpawn.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/MoveToSpawn.java @@ -12,9 +12,8 @@ import net.minecraft.util.math.Vec3d; public class MoveToSpawn extends Action { - public Step currentStep = Step.WAIT_FOR_TELEPORT; - private final ClientPlayerEntity player = CodeClient.MC.player; + public Step currentStep = Step.WAIT_FOR_TELEPORT; public MoveToSpawn(Callback callback) { super(callback); @@ -28,14 +27,15 @@ public void init() { @Override public boolean onReceivePacket(Packet packet) { - if(packet instanceof PlayerPositionLookS2CPacket positionLookS2CPacket) return onTeleport(positionLookS2CPacket); - if(packet instanceof PlaySoundS2CPacket && currentStep != Step.DONE) return true; + if (packet instanceof PlayerPositionLookS2CPacket positionLookS2CPacket) + return onTeleport(positionLookS2CPacket); + if (packet instanceof PlaySoundS2CPacket && currentStep != Step.DONE) return true; return super.onReceivePacket(packet); } public boolean onTeleport(PlayerPositionLookS2CPacket packet) { Dev plot = (Dev) CodeClient.location; - if(currentStep == Step.WAIT_FOR_TELEPORT) { + if (currentStep == Step.WAIT_FOR_TELEPORT) { plot.setDevSpawn(packet.getX(), packet.getZ()); currentStep = Step.MOVE_TO_CORNER; } @@ -45,8 +45,8 @@ public boolean onTeleport(PlayerPositionLookS2CPacket packet) { public boolean moveModifier() { Dev plot = (Dev) CodeClient.location; Vec3d location = new Vec3d(plot.getX(), plot.getFloorY(), plot.getZ()); - if(currentStep == Step.MOVE_TO_CORNER) { - if(player.getPos().distanceTo(location) == 0) { + if (currentStep == Step.MOVE_TO_CORNER) { + if (player.getPos().distanceTo(location) == 0) { currentStep = Step.DONE; this.callback(); return false; diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/PlaceTemplates.java b/src/main/java/dev/dfonline/codeclient/action/impl/PlaceTemplates.java index 054cbc97..7f65303f 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/PlaceTemplates.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/PlaceTemplates.java @@ -34,10 +34,10 @@ public class PlaceTemplates extends Action { public PlaceTemplates(List templates, Callback callback) { super(callback); - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { int i = 0; ArrayList templatesToPlace = new ArrayList<>(); - for (ItemStack template: templates) { + for (ItemStack template : templates) { int row = i % rowSize; int level = i / rowSize; i++; @@ -45,15 +45,15 @@ public PlaceTemplates(List templates, Callback callback) { templatesToPlace.add(new TemplateToPlace(pos, template)); } this.operations = templatesToPlace; - } - else { + } else { throw new IllegalStateException("Player must be in dev mode."); } } - public PlaceTemplates(HashMap templates, Callback callback) { + + public PlaceTemplates(HashMap templates, Callback callback) { super(callback); ArrayList templatesToPlace = new ArrayList<>(); - for (var template: templates.entrySet()) { + for (var template : templates.entrySet()) { templatesToPlace.add(new TemplateToPlace(template.getKey(), template.getValue())); } this.operations = templatesToPlace; @@ -75,10 +75,10 @@ public void init() { @Override public boolean onReceivePacket(Packet packet) { - if(packet instanceof OpenScreenS2CPacket) { + if (packet instanceof OpenScreenS2CPacket) { return true; } - if(packet instanceof ChunkDeltaUpdateS2CPacket updates) { + if (packet instanceof ChunkDeltaUpdateS2CPacket updates) { for (Operation operation : operations) { var block = new Object() { boolean isTemplate = false; @@ -101,19 +101,19 @@ public boolean onReceivePacket(Packet packet) { @Override public void onTick() { - if(CodeClient.MC.interactionManager == null) return; - if(CodeClient.location instanceof Dev) { - if(operations.isEmpty()) { + if (CodeClient.MC.interactionManager == null) return; + if (CodeClient.location instanceof Dev) { + if (operations.isEmpty()) { callback(); return; } - if(goTo != null) { + if (goTo != null) { goTo.onTick(); } - if(cooldown > 0) cooldown--; + if (cooldown > 0) cooldown--; Operation closestOperation = null; operations.removeIf(Operation::isComplete); - for (Operation operation: operations.stream().toList()) { + for (Operation operation : operations.stream().toList()) { double distanceToCurrentOperation = (operation.pos().distanceTo(CodeClient.MC.player.getEyePos())); if (distanceToCurrentOperation <= 5.8 && operation.isOpen() && !operation.isComplete()) { if (cooldown == 0) { @@ -137,16 +137,15 @@ public void onTick() { } return; } - if((closestOperation == null) || (distanceToCurrentOperation < closestOperation.pos().distanceTo(CodeClient.MC.player.getEyePos()))) { + if ((closestOperation == null) || (distanceToCurrentOperation < closestOperation.pos().distanceTo(CodeClient.MC.player.getEyePos()))) { closestOperation = operation; } } - if(closestOperation == null) { - for (Operation operation: operations) { + if (closestOperation == null) { + for (Operation operation : operations) { operation.setOpen(!operation.isComplete()); } - } - else { + } else { goTo = new GoTo(closestOperation.pos().add(-2, 0.5, 0), () -> this.goTo = null); goTo.init(); cooldown = 2; @@ -169,6 +168,7 @@ private static abstract class Operation { public Operation(BlockPos pos) { this.pos = pos; } + public Operation(Vec3d pos) { this.pos = new BlockPos((int) pos.x, (int) pos.y, (int) pos.z); } @@ -177,13 +177,14 @@ public Vec3d pos() { return pos.toCenterPos(); } - public void setOpen(boolean open) { - this.open = open; - } public boolean isOpen() { return open; } + public void setOpen(boolean open) { + this.open = open; + } + /** * Mark for dismissing. Doesn't need to be used again. */ @@ -191,10 +192,12 @@ public void setComplete() { this.open = false; this.complete = true; } + public boolean isComplete() { return complete; } } + private static class TemplateToPlace extends Operation { private final ItemStack template; diff --git a/src/main/java/dev/dfonline/codeclient/action/impl/ScanPlot.java b/src/main/java/dev/dfonline/codeclient/action/impl/ScanPlot.java index 282124cf..0b2b9b7e 100644 --- a/src/main/java/dev/dfonline/codeclient/action/impl/ScanPlot.java +++ b/src/main/java/dev/dfonline/codeclient/action/impl/ScanPlot.java @@ -24,11 +24,11 @@ import java.util.regex.Pattern; public class ScanPlot extends Action { + private static final Vec3d goToOffset = new Vec3d(0, 1.5, 0); + private final ArrayList returnList; private List blocks = null; private HashMap scanned = null; private Action step = null; - private static final Vec3d goToOffset = new Vec3d(0, 1.5, 0); - private final ArrayList returnList; public ScanPlot(Callback callback, ArrayList scanList) { super(callback); @@ -67,9 +67,9 @@ public boolean onReceivePacket(Packet packet) { private BlockPos findNextBlock() { var player = CodeClient.MC.player.getPos(); BlockPos nearest = null; - for (BlockPos pos: blocks) { - if(nearest == null || pos.isWithinDistance(player,nearest.toCenterPos().distanceTo(player))) { - if(scanned.containsKey(pos) && scanned.get(pos) != null) { + for (BlockPos pos : blocks) { + if (nearest == null || pos.isWithinDistance(player, nearest.toCenterPos().distanceTo(player))) { + if (scanned.containsKey(pos) && scanned.get(pos) != null) { continue; } nearest = pos; @@ -80,14 +80,14 @@ private BlockPos findNextBlock() { private void next() { var block = findNextBlock(); - if(block == null) { + if (block == null) { returnList.clear(); returnList.addAll(scanned.values()); callback(); return; } step = new GoTo(block.toCenterPos().add(goToOffset), () -> { - this.step = new PickUpBlock(block,() -> { + this.step = new PickUpBlock(block, () -> { this.step = null; // next(progress + 1); }); @@ -98,7 +98,7 @@ private void next() { @Override public void onTick() { - if(blocks == null) return; + if (blocks == null) return; if (step != null) step.onTick(); else { next(); @@ -124,7 +124,8 @@ public void init() { boolean sneaky = !player.isSneaking(); if (sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); inter.interactBlock(player, Hand.MAIN_HAND, new BlockHitResult(this.pos.toCenterPos(), Direction.UP, this.pos, false)); - if (sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); + if (sneaky) + net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); } @Override @@ -134,7 +135,7 @@ public boolean onReceivePacket(Packet packet) { var data = Utility.templateDataItem(slot.getStack()); var template = Template.parse64(data); if (template == null) return false; - scanned.put(pos,slot.getStack()); + scanned.put(pos, slot.getStack()); net.sendPacket(new CreativeInventoryActionC2SPacket(slot.getSlot(), ItemStack.EMPTY)); this.callback(); return true; @@ -145,7 +146,7 @@ public boolean onReceivePacket(Packet packet) { @Override public void onTick() { ticks += 1; - if(ticks == 10) { + if (ticks == 10) { ticks = 0; init(); } diff --git a/src/main/java/dev/dfonline/codeclient/config/Config.java b/src/main/java/dev/dfonline/codeclient/config/Config.java index 1019ac5b..5a5ca007 100644 --- a/src/main/java/dev/dfonline/codeclient/config/Config.java +++ b/src/main/java/dev/dfonline/codeclient/config/Config.java @@ -3,7 +3,6 @@ import com.google.gson.JsonObject; import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.FileManager; -import dev.dfonline.codeclient.dev.menu.customchest.CustomChestHandler; import dev.dfonline.codeclient.dev.menu.customchest.CustomChestNumbers; import dev.dfonline.codeclient.hypercube.actiondump.ActionDump; import dev.isxander.yacl3.api.*; @@ -65,63 +64,14 @@ public class Config { public CustomChestMenuType CustomCodeChest = CustomChestMenuType.OFF; public boolean PickAction = true; - private void save() { - try { - JsonObject object = new JsonObject(); - object.addProperty("NoClipEnabled",NoClipEnabled); - object.addProperty("AirSpeed", AirSpeed); - object.addProperty("PlaceOnAir",PlaceOnAir); - object.addProperty("CodeClientAPI",CodeClientAPI); - object.addProperty("CCDBUG",CCDBUG); - object.addProperty("CustomBlockInteractions",CustomBlockInteractions); - object.addProperty("CustomTagInteraction",CustomTagInteraction); - object.addProperty("AutoJoin", AutoJoin); - object.addProperty("AutoNode",AutoNode.name()); - object.addProperty("AutoJoinPlot",AutoJoinPlot); - object.addProperty("AutoJoinPlotId",AutoJoinPlotId); - object.addProperty("FileCharSet",FileCharSet.name()); - object.addProperty("InvisibleBlocksInDev",InvisibleBlocksInDev); - object.addProperty("ReachDistance",ReachDistance); - object.addProperty("AutoFly",AutoFly); - object.addProperty("CodeLayerInteractionMode",CodeLayerInteractionMode.name()); - object.addProperty("AirControl",AirControl); - object.addProperty("FocusSearch",FocusSearch); - object.addProperty("SaveCharSet",SaveCharSet.name()); - object.addProperty("RecentChestInsert",RecentChestInsert); - object.addProperty("HighlightChestsWithAir",HighlightChestsWithAir); - object.addProperty("HighlightChestDuration",HighlightChestDuration); - object.addProperty("ChestHighlightColor",ChestHighlightColor); - object.addProperty("UseIForLineScope",UseIForLineScope); - object.addProperty("CustomBlockBreaking",CustomBlockBreaking); - object.addProperty("ChestPeeker",ChestPeeker); - object.addProperty("ChestPeekerX",ChestPeekerX); - object.addProperty("ChestPeekerY",ChestPeekerY); - object.addProperty("ReportBrokenBlock",ReportBrokenBlock); - object.addProperty("ScopeSwitcher",ScopeSwitcher); - object.addProperty("UpAngle",UpAngle); - object.addProperty("DownAngle",DownAngle); - object.addProperty("TeleportUp",TeleportUp); - object.addProperty("TeleportDown",TeleportDown); - object.addProperty("Line1Color",Line1Color); - object.addProperty("Line2Color",Line2Color); - object.addProperty("Line3Color",Line3Color); - object.addProperty("UseSelectionColor",UseSelectionColor); - object.addProperty("Line4Color",Line4Color); - object.addProperty("SignPeeker",SignPeeker); - object.addProperty("CustomCodeChest",CustomCodeChest.name()); - object.addProperty("PickAction",PickAction); - FileManager.writeConfig(object.toString()); - } catch (Exception e) { - CodeClient.LOGGER.info("Couldn't save config: " + e); - } + public Config() { } public static Config getConfig() { - if(instance == null) { + if (instance == null) { try { instance = CodeClient.gson.fromJson(FileManager.readConfig(), Config.class); - } - catch (Exception exception) { + } catch (Exception exception) { CodeClient.LOGGER.info("Config didn't load: " + exception); CodeClient.LOGGER.info("Making a new one."); instance = new Config(); @@ -130,10 +80,62 @@ public static Config getConfig() { } return instance; } + public static void clear() { instance = null; } + private void save() { + try { + JsonObject object = new JsonObject(); + object.addProperty("NoClipEnabled", NoClipEnabled); + object.addProperty("AirSpeed", AirSpeed); + object.addProperty("PlaceOnAir", PlaceOnAir); + object.addProperty("CodeClientAPI", CodeClientAPI); + object.addProperty("CCDBUG", CCDBUG); + object.addProperty("CustomBlockInteractions", CustomBlockInteractions); + object.addProperty("CustomTagInteraction", CustomTagInteraction); + object.addProperty("AutoJoin", AutoJoin); + object.addProperty("AutoNode", AutoNode.name()); + object.addProperty("AutoJoinPlot", AutoJoinPlot); + object.addProperty("AutoJoinPlotId", AutoJoinPlotId); + object.addProperty("FileCharSet", FileCharSet.name()); + object.addProperty("InvisibleBlocksInDev", InvisibleBlocksInDev); + object.addProperty("ReachDistance", ReachDistance); + object.addProperty("AutoFly", AutoFly); + object.addProperty("CodeLayerInteractionMode", CodeLayerInteractionMode.name()); + object.addProperty("AirControl", AirControl); + object.addProperty("FocusSearch", FocusSearch); + object.addProperty("SaveCharSet", SaveCharSet.name()); + object.addProperty("RecentChestInsert", RecentChestInsert); + object.addProperty("HighlightChestsWithAir", HighlightChestsWithAir); + object.addProperty("HighlightChestDuration", HighlightChestDuration); + object.addProperty("ChestHighlightColor", ChestHighlightColor); + object.addProperty("UseIForLineScope", UseIForLineScope); + object.addProperty("CustomBlockBreaking", CustomBlockBreaking); + object.addProperty("ChestPeeker", ChestPeeker); + object.addProperty("ChestPeekerX", ChestPeekerX); + object.addProperty("ChestPeekerY", ChestPeekerY); + object.addProperty("ReportBrokenBlock", ReportBrokenBlock); + object.addProperty("ScopeSwitcher", ScopeSwitcher); + object.addProperty("UpAngle", UpAngle); + object.addProperty("DownAngle", DownAngle); + object.addProperty("TeleportUp", TeleportUp); + object.addProperty("TeleportDown", TeleportDown); + object.addProperty("Line1Color", Line1Color); + object.addProperty("Line2Color", Line2Color); + object.addProperty("Line3Color", Line3Color); + object.addProperty("UseSelectionColor", UseSelectionColor); + object.addProperty("Line4Color", Line4Color); + object.addProperty("SignPeeker", SignPeeker); + object.addProperty("CustomCodeChest", CustomCodeChest.name()); + object.addProperty("PickAction", PickAction); + FileManager.writeConfig(object.toString()); + } catch (Exception e) { + CodeClient.LOGGER.info("Couldn't save config: " + e); + } + } + public YetAnotherConfigLib getLibConfig() { return YetAnotherConfigLib.createBuilder() .title(Text.literal("CodeClient Config")) @@ -171,7 +173,7 @@ public YetAnotherConfigLib getLibConfig() { .option(Option.createBuilder(CharSetOption.class) .name(Text.literal("Save Charset")) .description(OptionDescription.createBuilder() - .text(Text.literal("When getting the actiondump get it in a needed format."),Text.literal("Default recommended.")) + .text(Text.literal("When getting the actiondump get it in a needed format."), Text.literal("Default recommended.")) .build()) .binding( CharSetOption.UTF_8, @@ -195,7 +197,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(boolean.class) .name(Text.literal("Auto Focus Search")) - .description(OptionDescription.of(Text.literal("When opening the Code Palette (").append(Text.keybind("key.codeclient.codepalette")).append(") automatically select the search bar."),Text.literal("This is disabled because it interferes with navigation binds."))) + .description(OptionDescription.of(Text.literal("When opening the Code Palette (").append(Text.keybind("key.codeclient.codepalette")).append(") automatically select the search bar."), Text.literal("This is disabled because it interferes with navigation binds."))) .binding( false, () -> FocusSearch, @@ -313,7 +315,7 @@ public YetAnotherConfigLib getLibConfig() { () -> UpAngle, opt -> UpAngle = opt ) - .controller(opt -> FloatSliderControllerBuilder.create(opt).range(0F,180F).step(1F)) + .controller(opt -> FloatSliderControllerBuilder.create(opt).range(0F, 180F).step(1F)) .build()) .option(Option.createBuilder(float.class) .name(Text.literal("Angle to go down")) @@ -322,7 +324,7 @@ public YetAnotherConfigLib getLibConfig() { () -> DownAngle, opt -> DownAngle = opt ) - .controller(opt -> FloatSliderControllerBuilder.create(opt).range(0F,180F).step(1F)) + .controller(opt -> FloatSliderControllerBuilder.create(opt).range(0F, 180F).step(1F)) .build()) .option(Option.createBuilder(boolean.class) .name(Text.literal("Teleport Up")) @@ -377,7 +379,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(boolean.class) .name(Text.literal("Custom Block Breaking")) - .description(OptionDescription.of(Text.literal("Keep codeblocks safe from accidental breaking."),Text.literal("They will have the survival breaking animation."),Text.literal("They will take 5 ticks to break (0.25 seconds)"))) + .description(OptionDescription.of(Text.literal("Keep codeblocks safe from accidental breaking."), Text.literal("They will have the survival breaking animation."), Text.literal("They will take 5 ticks to break (0.25 seconds)"))) .binding( false, () -> CustomBlockBreaking, @@ -402,7 +404,7 @@ public YetAnotherConfigLib getLibConfig() { .description(OptionDescription.createBuilder() .text(Text.literal("Use a custom menu for chests, with value text boxes for quick editing.")) .text(Text.of(CustomCodeChest.description)) - .text(Text.literal("THIS IS IN BETA!").formatted(Formatting.YELLOW,Formatting.BOLD)) + .text(Text.literal("THIS IS IN BETA!").formatted(Formatting.YELLOW, Formatting.BOLD)) .build()) .binding( CustomChestMenuType.OFF, @@ -415,7 +417,7 @@ public YetAnotherConfigLib getLibConfig() { .name(Text.literal("Place on Air")) .description(OptionDescription.createBuilder() .text(Text.literal("Allows you to place on air where codespaces would go.")) - .text(Text.literal("This will interfere with other players who don't have this mod, such as helpers!").formatted(Formatting.YELLOW,Formatting.BOLD)) + .text(Text.literal("This will interfere with other players who don't have this mod, such as helpers!").formatted(Formatting.YELLOW, Formatting.BOLD)) .build()) .binding( false, @@ -476,7 +478,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(Boolean.class) .name(Text.literal("Pick Block Action")) - .description(OptionDescription.of(Text.literal("Replaces pick block with the action"),Text.literal("Requires actiondump.").setStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,"https://github.com/DFOnline/CodeClient/wiki/actiondump")).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,Text.literal("Click to open link."))).withUnderline(true).withColor(Formatting.AQUA)))) + .description(OptionDescription.of(Text.literal("Replaces pick block with the action"), Text.literal("Requires actiondump.").setStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/DFOnline/CodeClient/wiki/actiondump")).withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal("Click to open link."))).withUnderline(true).withColor(Formatting.AQUA)))) .binding( true, () -> PickAction, @@ -547,7 +549,7 @@ public YetAnotherConfigLib getLibConfig() { () -> ChestPeekerX, opt -> ChestPeekerX = opt ) - .controller(integerOption -> IntegerFieldControllerBuilder.create(integerOption).range(-500,500)) + .controller(integerOption -> IntegerFieldControllerBuilder.create(integerOption).range(-500, 500)) .build()) .option(Option.createBuilder(int.class) .name(Text.literal("Preview Y Offset")) @@ -557,69 +559,69 @@ public YetAnotherConfigLib getLibConfig() { () -> ChestPeekerY, opt -> ChestPeekerY = opt ) - .controller(integerOption -> IntegerFieldControllerBuilder.create(integerOption).range(-500,500)) + .controller(integerOption -> IntegerFieldControllerBuilder.create(integerOption).range(-500, 500)) .build()) .build()) // // - .group(OptionGroup.createBuilder() - .name(Text.literal("Chest Highlight")) - .description(OptionDescription.of( - Text.literal("A highlight for inserting items into chests"), - Text.literal("Helpful with finding where you where, or accidentally punching chests."))) - .option(Option.createBuilder(Boolean.class) - .name(Text.literal("Highlight Recent Inserted Chest")) - .description(OptionDescription.createBuilder() - .text(Text.literal("Highlights the chest you inserted (via punching with an item) an item into")) - .build()) - .binding( - true, - () -> RecentChestInsert, - opt -> RecentChestInsert = opt - ) - .controller(TickBoxControllerBuilder::create) - .build()) - .option(Option.createBuilder(Boolean.class) - .name(Text.literal("Highlight With Empty Hand")) - .description(OptionDescription.of(Text.literal("If punching a chest with an empty hand should highlight it."))) - .binding( - false, - () -> HighlightChestsWithAir, - opt -> HighlightChestsWithAir = opt - ) - .controller(TickBoxControllerBuilder::create) - .build()) - .option(Option.createBuilder(int.class) - .name(Text.literal("Highlight Duration")) - .description(OptionDescription.of(Text.literal("How long the highlight should show."),Text.literal("The last second will fade out."))) - .binding( - 10, - () -> HighlightChestDuration, - opt -> HighlightChestDuration = opt - ) - .controller(integerOption -> new IntegerFieldControllerBuilderImpl(integerOption).min(1)) + .group(OptionGroup.createBuilder() + .name(Text.literal("Chest Highlight")) + .description(OptionDescription.of( + Text.literal("A highlight for inserting items into chests"), + Text.literal("Helpful with finding where you where, or accidentally punching chests."))) + .option(Option.createBuilder(Boolean.class) + .name(Text.literal("Highlight Recent Inserted Chest")) + .description(OptionDescription.createBuilder() + .text(Text.literal("Highlights the chest you inserted (via punching with an item) an item into")) .build()) - .option(Option.createBuilder(Color.class) - .name(Text.literal("Recent Inserted Chest Highlight Color")) - .description(OptionDescription.createBuilder() - .text(Text.literal("Color of chest highlight")) - .build()) - .binding( - new Color(0.2F, 1.0F, 1.0F), - () -> new Color(ChestHighlightColor), - opt -> ChestHighlightColor = opt.getRGB() - ) - .controller(ColorControllerBuilder::create) + .binding( + true, + () -> RecentChestInsert, + opt -> RecentChestInsert = opt + ) + .controller(TickBoxControllerBuilder::create) + .build()) + .option(Option.createBuilder(Boolean.class) + .name(Text.literal("Highlight With Empty Hand")) + .description(OptionDescription.of(Text.literal("If punching a chest with an empty hand should highlight it."))) + .binding( + false, + () -> HighlightChestsWithAir, + opt -> HighlightChestsWithAir = opt + ) + .controller(TickBoxControllerBuilder::create) + .build()) + .option(Option.createBuilder(int.class) + .name(Text.literal("Highlight Duration")) + .description(OptionDescription.of(Text.literal("How long the highlight should show."), Text.literal("The last second will fade out."))) + .binding( + 10, + () -> HighlightChestDuration, + opt -> HighlightChestDuration = opt + ) + .controller(integerOption -> new IntegerFieldControllerBuilderImpl(integerOption).min(1)) + .build()) + .option(Option.createBuilder(Color.class) + .name(Text.literal("Recent Inserted Chest Highlight Color")) + .description(OptionDescription.createBuilder() + .text(Text.literal("Color of chest highlight")) .build()) + .binding( + new Color(0.2F, 1.0F, 1.0F), + () -> new Color(ChestHighlightColor), + opt -> ChestHighlightColor = opt.getRGB() + ) + .controller(ColorControllerBuilder::create) .build()) + .build()) // // .group(OptionGroup.createBuilder() .name(Text.literal("Sign Colors")) - .description(OptionDescription.of(Text.literal("Override the color of text on the signs in the dev space."),Text.literal("Using #000000 (pure black) has no effect and disable disable it."))) + .description(OptionDescription.of(Text.literal("Override the color of text on the signs in the dev space."), Text.literal("Using #000000 (pure black) has no effect and disable disable it."))) .option(Option.createBuilder(Color.class) .name(Text.literal("Line 1")) - .description(OptionDescription.of(Text.literal("The top line on a sign."),Text.literal("Tells you what block it is, such as PLAYER ACTION"))) + .description(OptionDescription.of(Text.literal("The top line on a sign."), Text.literal("Tells you what block it is, such as PLAYER ACTION"))) .binding( new Color(0xAAAAAA), () -> new Color(Line1Color), @@ -629,7 +631,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(Color.class) .name(Text.literal("Line 2")) - .description(OptionDescription.of(Text.literal("The second line on a sign."),Text.literal("Tells you the action or data, such as SendMessage"))) + .description(OptionDescription.of(Text.literal("The second line on a sign."), Text.literal("Tells you the action or data, such as SendMessage"))) .binding( new Color(0xC5C5C5), () -> new Color(Line2Color), @@ -639,7 +641,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(Color.class) .name(Text.literal("Line 3")) - .description(OptionDescription.of(Text.literal("The third line on a sign."),Text.literal("Tells you either the selection or SubAction"))) + .description(OptionDescription.of(Text.literal("The third line on a sign."), Text.literal("Tells you either the selection or SubAction"))) .binding( new Color(0xAAFFAA), () -> new Color(Line3Color), @@ -659,7 +661,7 @@ public YetAnotherConfigLib getLibConfig() { .build()) .option(Option.createBuilder(Color.class) .name(Text.literal("Line 4")) - .description(OptionDescription.of(Text.literal("The bottom line on a sign."),Text.literal("Only tells you if it is inverted: NOT"))) + .description(OptionDescription.of(Text.literal("The bottom line on a sign."), Text.literal("Only tells you if it is inverted: NOT"))) .binding( new Color(0xFF8800), () -> new Color(Line4Color), @@ -687,6 +689,7 @@ public enum Node { Beta("beta."); public final String prepend; + Node(String prepend) { this.prepend = prepend; } @@ -697,6 +700,7 @@ public enum CharSetOption { UTF_8(StandardCharsets.UTF_8); public final Charset charSet; + CharSetOption(Charset charSet) { this.charSet = charSet; } @@ -708,13 +712,14 @@ public enum LayerInteractionMode { ON("Code layers are always custom."); public final String description; + LayerInteractionMode(String description) { this.description = description; } } public enum CustomChestMenuType { - OFF("No changes.",null), + OFF("No changes.", null), SMALL("A small menu with a few lines for editing code values", CustomChestNumbers.SMALL), LARGE("A large menu with lots of lines for editing values, and extra slots showing values without editable lines.", CustomChestNumbers.LARGE); @@ -726,7 +731,4 @@ public enum CustomChestMenuType { this.size = size; } } - - public Config() { - } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/BlockBreakDeltaCalculator.java b/src/main/java/dev/dfonline/codeclient/dev/BlockBreakDeltaCalculator.java index acef105b..0c889c46 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/BlockBreakDeltaCalculator.java +++ b/src/main/java/dev/dfonline/codeclient/dev/BlockBreakDeltaCalculator.java @@ -6,7 +6,6 @@ import java.util.Date; import java.util.List; import java.util.Objects; -import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; /** @@ -19,7 +18,7 @@ public class BlockBreakDeltaCalculator { * Only invoked when a codeblock is broken. */ public static void breakBlock(BlockPos pos) { - if(pos == null) return; + if (pos == null) return; oldBlocks.addBlock(pos); } @@ -44,6 +43,7 @@ private static class RecentBlocks { public void addBlock(BlockPos pos) { blocks.add(new RecentBlock(pos, new Date())); } + public Stream getBlock(BlockPos pos) { return blocks.stream().filter(recentBlock -> Objects.equals(recentBlock.pos, pos)); } @@ -52,6 +52,7 @@ public List getBlocks() { return blocks; } } + private record RecentBlock(BlockPos pos, Date time) { /** * Milliseconds diff --git a/src/main/java/dev/dfonline/codeclient/dev/BuildPhaser.java b/src/main/java/dev/dfonline/codeclient/dev/BuildPhaser.java index a19ad271..34f9ec94 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/BuildPhaser.java +++ b/src/main/java/dev/dfonline/codeclient/dev/BuildPhaser.java @@ -30,72 +30,73 @@ public class BuildPhaser { private static boolean clipping = false; - public static boolean isClipping() { - return clipping; - } - private static boolean wasFlying = true; - private static Vec3d lastPos = new Vec3d(0,0,0); + private static Vec3d lastPos = new Vec3d(0, 0, 0); private static boolean allowPacket = false; private static boolean waitForTP = false; private static boolean dontSpamBuildWarn = false; + public static boolean isClipping() { + return clipping; + } + public static void tick() { // CodeClient.LOGGER.info(String.valueOf(CodeClient.MC.player.getPos())); - if(CodeClient.location instanceof Dev plot) { - if(plot.getX() == null) { - if(CodeClient.clipBind.wasPressed()) Utility.sendMessage(Text.translatable("codeclient.phaser.plot_origin")); + if (CodeClient.location instanceof Dev plot) { + if (plot.getX() == null) { + if (CodeClient.clipBind.wasPressed()) + Utility.sendMessage(Text.translatable("codeclient.phaser.plot_origin")); } // CodeClient.LOGGER.info("dev and X"); - if(!clipping && CodeClient.clipBind.isPressed() && plot.getX() != null) startClipping(); - if(clipping) { + if (!clipping && CodeClient.clipBind.isPressed() && plot.getX() != null) startClipping(); + if (clipping) { var player = CodeClient.MC.player; player.setPos( - Math.min(Math.max(player.getX(),plot.getX() - 20),plot.getX() + plot.assumeSize().size + 1), + Math.min(Math.max(player.getX(), plot.getX() - 20), plot.getX() + plot.assumeSize().size + 1), player.getY(), - Math.min(Math.max(player.getZ(),plot.getZ()),plot.getZ() + plot.assumeSize().size + 1) + Math.min(Math.max(player.getZ(), plot.getZ()), plot.getZ() + plot.assumeSize().size + 1) ); allowPacket = true; CodeClient.MC.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(lastPos.x, lastPos.y, lastPos.z, false)); CodeClient.MC.player.getAbilities().flying = true; - if(!CodeClient.clipBind.isPressed()) finishClipping(); + if (!CodeClient.clipBind.isPressed()) finishClipping(); } - } - else if(clipping || waitForTP) { + } else if (clipping || waitForTP) { disableClipping(); } - if(CodeClient.location instanceof Build) { - if(CodeClient.clipBind.isPressed() && !dontSpamBuildWarn) { + if (CodeClient.location instanceof Build) { + if (CodeClient.clipBind.isPressed() && !dontSpamBuildWarn) { dontSpamBuildWarn = true; Utility.sendMessage(Text.translatable("codeclient.phaser.dev_mode1", - Text.translatable("codeclient.phaser.dev_mode2") - .setStyle(Text.empty().getStyle() - .withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL,"https://github.com/DFOnline/CodeClient/wiki/phaser#internal")) - .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.translatable("chat.link.open"))) - ).formatted(Formatting.AQUA,Formatting.UNDERLINE)), - ChatType.FAIL); + Text.translatable("codeclient.phaser.dev_mode2") + .setStyle(Text.empty().getStyle() + .withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/DFOnline/CodeClient/wiki/phaser#internal")) + .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.translatable("chat.link.open"))) + ).formatted(Formatting.AQUA, Formatting.UNDERLINE)), + ChatType.FAIL); } - if(dontSpamBuildWarn && !CodeClient.clipBind.isPressed()) dontSpamBuildWarn = false; + if (dontSpamBuildWarn && !CodeClient.clipBind.isPressed()) dontSpamBuildWarn = false; } } public static boolean onPacket(Packet packet) { - if(allowPacket) { + if (allowPacket) { allowPacket = false; return false; } return clipping && (packet instanceof PlayerMoveC2SPacket || packet instanceof ClientCommandC2SPacket); } + public static boolean handlePacket(Packet packet) { - if(!waitForTP) return false; - if(packet instanceof PlayerPositionLookS2CPacket move) { + if (!waitForTP) return false; + if (packet instanceof PlayerPositionLookS2CPacket move) { CodeClient.MC.getNetworkHandler().sendPacket(new TeleportConfirmC2SPacket(move.getTeleportId())); return true; } - if(packet instanceof EntityAnimationS2CPacket) return true; - if(packet instanceof PlaySoundFromEntityS2CPacket) { + if (packet instanceof EntityAnimationS2CPacket) return true; + if (packet instanceof PlaySoundFromEntityS2CPacket) { waitForTP = false; return true; } @@ -113,7 +114,7 @@ private static void startClipping() { private static void finishClipping() { disableClipping(); - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { ClientPlayerEntity player = CodeClient.MC.player; PlayerAbilities abilities = player.getAbilities(); abilities.allowFlying = true; @@ -127,12 +128,13 @@ private static void finishClipping() { Utility.sendHandItem(location); boolean sneaky = !player.isSneaking(); - BlockPos lastBlockPos = new BlockPos((int) lastPos.x,(int) lastPos.y,(int) lastPos.z); + BlockPos lastBlockPos = new BlockPos((int) lastPos.x, (int) lastPos.y, (int) lastPos.z); ClientPlayNetworkHandler net = CodeClient.MC.getNetworkHandler(); - if(sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); + if (sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); net.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.START_DESTROY_BLOCK, lastBlockPos, Direction.UP)); net.sendPacket(new PlayerActionC2SPacket(PlayerActionC2SPacket.Action.ABORT_DESTROY_BLOCK, lastBlockPos, Direction.UP)); - if(sneaky) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); + if (sneaky) + net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); Utility.sendHandItem(lastItem); } diff --git a/src/main/java/dev/dfonline/codeclient/dev/Debug/Debug.java b/src/main/java/dev/dfonline/codeclient/dev/Debug/Debug.java index 760a4339..a65cd164 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/Debug/Debug.java +++ b/src/main/java/dev/dfonline/codeclient/dev/Debug/Debug.java @@ -106,24 +106,23 @@ public static boolean handlePacket(Packet packet) } public static void updateDisplay() { - if(!active) return; - if(text == null) return; + if (!active) return; + if (text == null) return; OverlayManager.setOverlayText(); - OverlayManager.addOverlayText(Text.empty().append(Text.literal("CCDBUG").formatted(Formatting.YELLOW,Formatting.BOLD)).append(" (/abort to hide)")); - if(CPU != null) { + OverlayManager.addOverlayText(Text.empty().append(Text.literal("CCDBUG").formatted(Formatting.YELLOW, Formatting.BOLD)).append(" (/abort to hide)")); + if (CPU != null) { OverlayManager.addOverlayText(Text.literal("CPU Usage: ").formatted(Formatting.GOLD).append(Text.literal(String.valueOf(CPU)).formatted(Formatting.AQUA))); OverlayManager.addOverlayText(Text.empty()); } - for(var line: text) { + for (var line : text) { OverlayManager.addOverlayText(line); } } public static void tick() { - if(Config.getConfig().CCDBUG && active && CodeClient.location instanceof Plot) { + if (Config.getConfig().CCDBUG && active && CodeClient.location instanceof Plot) { updateDisplay(); - } - else { + } else { CPU = null; } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/InteractionManager.java b/src/main/java/dev/dfonline/codeclient/dev/InteractionManager.java index 12fc56e5..b65ed1d2 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/InteractionManager.java +++ b/src/main/java/dev/dfonline/codeclient/dev/InteractionManager.java @@ -56,36 +56,38 @@ public class InteractionManager { /** * Assuming pos is in a codespace. + * * @param pos The targeted pos. * @return The origin of the codeblock to be broken. null if it shouldn't break. */ public static BlockPos isBlockBreakable(BlockPos pos) { if (pos.getY() % 5 != 0) return null; Block type = CodeClient.MC.world.getBlockState(pos).getBlock(); - if (List.of(Blocks.STONE, Blocks.DIRT, Blocks.PISTON, Blocks.STICKY_PISTON, Blocks.CHEST).contains(type)) return null; + if (List.of(Blocks.STONE, Blocks.DIRT, Blocks.PISTON, Blocks.STICKY_PISTON, Blocks.CHEST).contains(type)) + return null; if (type == Blocks.OAK_WALL_SIGN) return pos.east(); return pos; } public static boolean onBreakBlock(BlockPos pos) { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { if (!plot.isInCodeSpace(pos.getX(), pos.getZ())) return false; - if(CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) { + if (CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) { ChestPeeker.invalidate(); - if((!CodeClient.MC.player.getMainHandStack().isEmpty() || Config.getConfig().HighlightChestsWithAir) && Config.getConfig().RecentChestInsert) { + if ((!CodeClient.MC.player.getMainHandStack().isEmpty() || Config.getConfig().HighlightChestsWithAir) && Config.getConfig().RecentChestInsert) { RecentChestInsert.setLastChest(pos); } } BlockPos breakPos = isBlockBreakable(pos); - if(breakPos != null) { - if(Config.getConfig().ReportBrokenBlock && validBlocks.contains(CodeClient.MC.world.getBlockState(breakPos).getBlock()) && CodeClient.MC.world.getBlockEntity(breakPos.west()) instanceof SignBlockEntity sign) { - if(!sign.getFrontText().getMessage(1,false).equals(Text.empty())) - Utility.sendMessage(Text.translatable("codeclient.interaction.broke",Text.empty().formatted(Formatting.WHITE).append(sign.getFrontText().getMessage(1,false))).formatted(Formatting.AQUA), ChatType.INFO); + if (breakPos != null) { + if (Config.getConfig().ReportBrokenBlock && validBlocks.contains(CodeClient.MC.world.getBlockState(breakPos).getBlock()) && CodeClient.MC.world.getBlockEntity(breakPos.west()) instanceof SignBlockEntity sign) { + if (!sign.getFrontText().getMessage(1, false).equals(Text.empty())) + Utility.sendMessage(Text.translatable("codeclient.interaction.broke", Text.empty().formatted(Formatting.WHITE).append(sign.getFrontText().getMessage(1, false))).formatted(Formatting.AQUA), ChatType.INFO); } BlockBreakDeltaCalculator.breakBlock(pos); } - if(Config.getConfig().CustomBlockInteractions) { - if(breakPos != null) { + if (Config.getConfig().CustomBlockInteractions) { + if (breakPos != null) { breakCodeBlock(breakPos); } } @@ -98,15 +100,15 @@ private static void breakCodeBlock(BlockPos pos) { ClientWorld world = CodeClient.MC.world; CodeClient.MC.getSoundManager().play(new PositionedSoundInstance(SoundEvent.of(new Identifier("minecraft:block.stone.break")), SoundCategory.BLOCKS, 2, 0.8F, Random.create(), pos)); world.setBlockState(pos, Blocks.AIR.getDefaultState()); - world.setBlockState(pos.add(0,1,0), Blocks.AIR.getDefaultState()); - world.setBlockState(pos.add(-1,0,0), Blocks.AIR.getDefaultState()); - world.setBlockState(pos.add(0,0,1), Blocks.AIR.getDefaultState()); + world.setBlockState(pos.add(0, 1, 0), Blocks.AIR.getDefaultState()); + world.setBlockState(pos.add(-1, 0, 0), Blocks.AIR.getDefaultState()); + world.setBlockState(pos.add(0, 0, 1), Blocks.AIR.getDefaultState()); } public static boolean onClickSlot(Slot slot, int button, SlotActionType actionType, int syncId, int revision) { - if(!slot.hasStack()) return false; + if (!slot.hasStack()) return false; ItemStack item = slot.getStack(); - if(!item.hasNbt()) return false; + if (!item.hasNbt()) return false; NbtCompound nbt = item.getNbt(); if (nbt != null && !nbt.contains("PublicBukkitValues")) return false; if (nbt != null && nbt.get("PublicBukkitValues") instanceof NbtCompound bukkitValues) { @@ -126,7 +128,7 @@ public static boolean onClickSlot(Slot slot, int button, SlotActionType actionTy String selected = varObject.get("data").getAsJsonObject().get("option").getAsString(); NbtCompound display = nbt.getCompound("display"); NbtList lore = (NbtList) display.get("Lore"); - if(lore == null) return true; + if (lore == null) return true; int i = 0; Integer tagStartIndex = null; @@ -136,7 +138,7 @@ public static boolean onClickSlot(Slot slot, int button, SlotActionType actionTy // TODO: Utility.getBlockTagLines for (NbtElement element : lore) { Text text = Text.Serialization.fromJson(element.asString()); - if(text == null) return false; + if (text == null) return false; TextColor color = text.getStyle().getColor(); if (color == null) { List siblings = text.getSiblings(); @@ -170,8 +172,8 @@ public static boolean onClickSlot(Slot slot, int button, SlotActionType actionTy lore.set(tagStartIndex + optionIndex, Utility.nbtify(text)); optionIndex++; } - display.put("Lore",lore); - item.setSubNbt("display",display); + display.put("Lore", lore); + item.setSubNbt("display", display); slot.setStack(item); return true; } @@ -183,8 +185,8 @@ public static boolean onClickSlot(Slot slot, int button, SlotActionType actionTy } public static boolean isInsideWall(Vec3d playerPos) { - Vec3d middlePos = playerPos.add(0,0.75,0); - Box box = new EntityDimensions(0.6f,1.8f,true).getBoxAt(playerPos); //Box.of(middlePos, 0.6, 5, 0.6); + Vec3d middlePos = playerPos.add(0, 0.75, 0); + Box box = new EntityDimensions(0.6f, 1.8f, true).getBoxAt(playerPos); //Box.of(middlePos, 0.6, 5, 0.6); CodeClient.LOGGER.info(String.valueOf(box)); return BlockPos.stream(box).anyMatch((pos) -> { BlockState blockState = CodeClient.MC.world.getBlockState(pos); @@ -194,37 +196,41 @@ public static boolean isInsideWall(Vec3d playerPos) { /** * Gets where a df block will place from a hit result. + * * @return The pos for the block behind the sign. Null if the place should've failed. */ @Nullable public static BlockPos getPlacePos(BlockHitResult hitResult) { BlockState state = CodeClient.MC.world.getBlockState(hitResult.getBlockPos()); BlockPos pos = state.getBlock() == Blocks.STONE ? hitResult.getBlockPos().south() : hitResult.getBlockPos().offset(hitResult.getSide()); - if(pos.getY() % 5 != 0) return null; - Vec3i[] check = {new Vec3i(1,0,0), new Vec3i(1,0,1), new Vec3i(1, 0 ,2), new Vec3i(2,0,0), new Vec3i(-1,0,0)}; - for (Vec3i offset: check) { - if(CodeClient.MC.world.getBlockState(pos.add(offset)).isSolidBlock(CodeClient.MC.world,pos.add(offset))) return null; + if (pos.getY() % 5 != 0) return null; + Vec3i[] check = {new Vec3i(1, 0, 0), new Vec3i(1, 0, 1), new Vec3i(1, 0, 2), new Vec3i(2, 0, 0), new Vec3i(-1, 0, 0)}; + for (Vec3i offset : check) { + if (CodeClient.MC.world.getBlockState(pos.add(offset)).isSolidBlock(CodeClient.MC.world, pos.add(offset))) + return null; } return pos; } public static BlockHitResult onBlockInteract(BlockHitResult hitResult) { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { ChestPeeker.invalidate(); BlockPos pos = hitResult.getBlockPos(); - if(plot.isInDev(pos)) { - if(CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) { + if (plot.isInDev(pos)) { + if (CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) { isOpeningCodeChest = true; } - if(pos.getY() % 5 == 4) { // Is a code space level (glass) - if(hitResult.getSide() == Direction.UP || hitResult.getSide() == Direction.DOWN) { - if(CodeClient.MC.world.getBlockState(pos).isAir() && Config.getConfig().PlaceOnAir) return new BlockHitResult(hitResult.getPos(),Direction.UP,hitResult.getBlockPos().add(0,1,0),hitResult.isInsideBlock()); - if(Config.getConfig().CustomBlockInteractions) return new BlockHitResult(hitResult.getPos(), Direction.UP, hitResult.getBlockPos(), hitResult.isInsideBlock()); + if (pos.getY() % 5 == 4) { // Is a code space level (glass) + if (hitResult.getSide() == Direction.UP || hitResult.getSide() == Direction.DOWN) { + if (CodeClient.MC.world.getBlockState(pos).isAir() && Config.getConfig().PlaceOnAir) + return new BlockHitResult(hitResult.getPos(), Direction.UP, hitResult.getBlockPos().add(0, 1, 0), hitResult.isInsideBlock()); + if (Config.getConfig().CustomBlockInteractions) + return new BlockHitResult(hitResult.getPos(), Direction.UP, hitResult.getBlockPos(), hitResult.isInsideBlock()); } } } - if(hitResult.getSide() == Direction.DOWN) { - BlockHitResult newHitResult = new BlockHitResult(hitResult.getPos(),Direction.UP,hitResult.getBlockPos().add(0,-1,0), hitResult.isInsideBlock()); + if (hitResult.getSide() == Direction.DOWN) { + BlockHitResult newHitResult = new BlockHitResult(hitResult.getPos(), Direction.UP, hitResult.getBlockPos().add(0, -1, 0), hitResult.isInsideBlock()); return newHitResult; } } @@ -232,7 +238,7 @@ public static BlockHitResult onBlockInteract(BlockHitResult hitResult) { } public static boolean shouldTeleportUp() { - if(CodeClient.location instanceof Dev) { + if (CodeClient.location instanceof Dev) { ClientPlayerEntity pl = CodeClient.MC.player; return NoClip.isInDevSpace() && pl.isOnGround() && Config.getConfig().TeleportUp && pl.getPitch() <= Config.getConfig().UpAngle - 90; } @@ -240,18 +246,18 @@ public static boolean shouldTeleportUp() { } public static boolean onItemInteract(PlayerEntity player, Hand hand) { - if(player.isSneaking() || !Config.getConfig().ScopeSwitcher) return false; + if (player.isSneaking() || !Config.getConfig().ScopeSwitcher) return false; ItemStack stack = player.getStackInHand(hand); NbtCompound nbt = stack.getNbt(); - if(nbt == null) return false; + if (nbt == null) return false; NbtCompound pbv = (NbtCompound) nbt.get("PublicBukkitValues"); - if(pbv == null) return false; + if (pbv == null) return false; NbtString varItem = (NbtString) pbv.get("hypercube:varitem"); - if(varItem == null) return false; + if (varItem == null) return false; JsonObject var = JsonParser.parseString(varItem.asString()).getAsJsonObject(); - if(!var.get("id").getAsString().equals("var")) return false; + if (!var.get("id").getAsString().equals("var")) return false; JsonObject data = var.get("data").getAsJsonObject(); String scopeName = data.get("scope").getAsString(); @@ -320,39 +326,39 @@ public static boolean onItemInteract(PlayerEntity player, Hand hand) { @Nullable public static VoxelShape customVoxelShape(BlockView world, BlockPos pos) { - if(CodeClient.MC != null && CodeClient.MC.player != null && CodeClient.location instanceof Dev plot) { + if (CodeClient.MC != null && CodeClient.MC.player != null && CodeClient.location instanceof Dev plot) { Config.LayerInteractionMode mode = Config.getConfig().CodeLayerInteractionMode; Boolean isInDev = plot.isInDev(pos); - if(isInDev == null) return null; - if(!isInDev) { + if (isInDev == null) return null; + if (!isInDev) { var player = CodeClient.MC.player; boolean playerIsOutside = player.getEyeY() < 50 && ((player.getX() <= plot.getX() - 20) || player.getZ() <= (plot.getZ()) || (player.getZ() >= plot.getZ() + plot.assumeSize().size) ); - if(!playerIsOutside) return null; + if (!playerIsOutside) return null; boolean blockIsOutside = pos.getY() < 50 && (pos.getX() < plot.getX()) && (pos.getX() >= plot.getX() - 22) && (pos.getZ() >= (plot.getZ() - 2)) && (pos.getZ() <= plot.getZ() + plot.assumeSize().size + 2); - if(blockIsOutside) return VoxelShapes.empty(); + if (blockIsOutside) return VoxelShapes.empty(); return null; } boolean isLevel = pos.getY() % 5 == 4; boolean noClipAllowsBlock = Config.getConfig().NoClipEnabled || world.getBlockState(pos).isAir(); boolean hideCodeSpace = pos.getY() >= plot.getFloorY() && - noClipAllowsBlock && - mode != Config.LayerInteractionMode.OFF - && isLevel - && ( + noClipAllowsBlock && + mode != Config.LayerInteractionMode.OFF + && isLevel + && ( mode == Config.LayerInteractionMode.ON - || pos.getY() + 1 < CodeClient.MC.player.getEyeY() + || pos.getY() + 1 < CodeClient.MC.player.getEyeY() ) - && !world.getBlockState(pos.add(0,1,0)).isSolidBlock(world, pos) - ; - if(hideCodeSpace) return VoxelShapes.cuboid(0, 1 - 1d / (4096) ,0,1,1,1); - if(noClipAllowsBlock && mode != Config.LayerInteractionMode.OFF && pos.getY() + 1 > CodeClient.MC.player.getEyeY() && isLevel) return VoxelShapes.empty(); + && !world.getBlockState(pos.add(0, 1, 0)).isSolidBlock(world, pos); + if (hideCodeSpace) return VoxelShapes.cuboid(0, 1 - 1d / (4096), 0, 1, 1, 1); + if (noClipAllowsBlock && mode != Config.LayerInteractionMode.OFF && pos.getY() + 1 > CodeClient.MC.player.getEyeY() && isLevel) + return VoxelShapes.empty(); } return null; } diff --git a/src/main/java/dev/dfonline/codeclient/dev/LastPos.java b/src/main/java/dev/dfonline/codeclient/dev/LastPos.java index 462fcf89..daa8f1fa 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/LastPos.java +++ b/src/main/java/dev/dfonline/codeclient/dev/LastPos.java @@ -13,19 +13,20 @@ public class LastPos { public static void handlePacket(Packet packet) { - if(CodeClient.MC.player == null) return; - if(CodeClient.location instanceof Creator plot) { - if(plot.getSize() != null && !plot.isInPlot(BlockPos.ofFloored(CodeClient.MC.player.getPos()))) return; // todo: make a player version for this - if(!(packet instanceof PlayerPositionLookS2CPacket)) return; + if (CodeClient.MC.player == null) return; + if (CodeClient.location instanceof Creator plot) { + if (plot.getSize() != null && !plot.isInPlot(BlockPos.ofFloored(CodeClient.MC.player.getPos()))) + return; // todo: make a player version for this + if (!(packet instanceof PlayerPositionLookS2CPacket)) return; plot.devPos = CodeClient.MC.player.getPos(); } } public static boolean tpBack() { - if(CodeClient.MC.player == null) return false; - if(CodeClient.location instanceof Creator plot && CodeClient.currentAction instanceof None) { - if(plot.devPos == null) return false; - CodeClient.currentAction = new GoTo(plot.devPos,() -> { + if (CodeClient.MC.player == null) return false; + if (CodeClient.location instanceof Creator plot && CodeClient.currentAction instanceof None) { + if (plot.devPos == null) return false; + CodeClient.currentAction = new GoTo(plot.devPos, () -> { CodeClient.MC.player.playSound(SoundEvent.of(new Identifier("minecraft:entity.enderman.teleport")), SoundCategory.PLAYERS, 2, 1); CodeClient.currentAction = new None(); }); diff --git a/src/main/java/dev/dfonline/codeclient/dev/NoClip.java b/src/main/java/dev/dfonline/codeclient/dev/NoClip.java index e670fd33..20830e05 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/NoClip.java +++ b/src/main/java/dev/dfonline/codeclient/dev/NoClip.java @@ -14,12 +14,12 @@ import org.jetbrains.annotations.Nullable; public class NoClip { + public static final double PLAYER_FREEDOM = 0.621; public static LineType display = null; public static Vec3d lastPos = null; public static float lastYaw = 0; public static float lastPitch = 0; public static int timesSinceMoved = 0; - public static final double PLAYER_FREEDOM = 0.621; public static boolean isIgnoringWalls() { return CodeClient.noClipOn() && isInDevSpace(); @@ -30,7 +30,7 @@ public static boolean isInDevSpace() { } public static Vec3d handleClientPosition(Vec3d movement) { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { ClientPlayerEntity player = CodeClient.MC.player; double nearestFloor = Math.floor(player.getY() / 5) * 5; @@ -39,22 +39,23 @@ public static Vec3d handleClientPosition(Vec3d movement) { double x = Math.max(player.getX() + movement.x * 1.3, plot.getX() - 22); double y = Math.max(player.getY() + movement.y * 1, plot.getFloorY()); double z = Math.max(player.getZ() + movement.z * 1.3, plot.getZ() - 2); - if(plot.getSize() != null) { + if (plot.getSize() != null) { z = Math.min(z, plot.getZ() + plot.getSize().size + 3); - if(z == plot.getZ() + plot.getSize().size + 3 && velocity.getZ() > 0) player.setVelocityClient(velocity.x, velocity.y, 0); + if (z == plot.getZ() + plot.getSize().size + 3 && velocity.getZ() > 0) + player.setVelocityClient(velocity.x, velocity.y, 0); } - if(z == plot.getZ() - 2 && velocity.getZ() < 0) player.setVelocityClient(velocity.x, velocity.y, 0); - if(x == plot.getX() - 22 && velocity.getX() < 0) player.setVelocityClient(0, velocity.y, velocity.z); + if (z == plot.getZ() - 2 && velocity.getZ() < 0) player.setVelocityClient(velocity.x, velocity.y, 0); + if (x == plot.getX() - 22 && velocity.getX() < 0) player.setVelocityClient(0, velocity.y, velocity.z); player.setOnGround(false); boolean wantsToFall = !Config.getConfig().TeleportDown && player.isSneaking() && (player.getPitch() >= 90 - Config.getConfig().DownAngle); - if((y < nearestFloor && !wantsToFall && !player.getAbilities().flying) || y == plot.getFloorY()) { + if ((y < nearestFloor && !wantsToFall && !player.getAbilities().flying) || y == plot.getFloorY()) { player.setVelocityClient(velocity.x, 0, velocity.z); y = nearestFloor; player.setOnGround(true); } - return new Vec3d(x, Math.min(y,256), z); + return new Vec3d(x, Math.min(y, 256), z); } return null; } @@ -64,11 +65,11 @@ public static float getJumpHeight() { } public static Vec3d handleSeverPosition() { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { ClientPlayerEntity player = CodeClient.MC.player; double z = Math.max(player.getZ(), plot.getZ() + PLAYER_FREEDOM); - if(plot.getSize() != null) { + if (plot.getSize() != null) { z = Math.min(z, plot.getZ() + plot.getSize().size + PLAYER_FREEDOM); } @@ -86,7 +87,7 @@ public static Vec3d handleSeverPosition() { } public static boolean isInsideWall(Vec3d playerPos) { - Vec3d middlePos = playerPos.add(0,1.8 / 2,0); + Vec3d middlePos = playerPos.add(0, 1.8 / 2, 0); float f = 0.6F + 0.1F * 0.8F; Box box = Box.of(middlePos, f, (1.799 + 1.0E-6 * 0.8F), f); return BlockPos.stream(box).anyMatch((pos) -> { @@ -97,7 +98,7 @@ public static boolean isInsideWall(Vec3d playerPos) { @Nullable public static BlockState replaceBlockAt(BlockPos pos) { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { Boolean isInDev = plot.isInDev(pos.toCenterPos()); if (isInDev == null || !isInDev) return null; if (display == null) return null; diff --git a/src/main/java/dev/dfonline/codeclient/dev/RecentChestInsert.java b/src/main/java/dev/dfonline/codeclient/dev/RecentChestInsert.java index 22fa3ee1..4ea238f2 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/RecentChestInsert.java +++ b/src/main/java/dev/dfonline/codeclient/dev/RecentChestInsert.java @@ -11,28 +11,27 @@ import net.minecraft.util.math.BlockPos; import net.minecraft.util.shape.VoxelShape; -import java.awt.*; - public class RecentChestInsert { private static float alpha = 0; private static BlockPos lastChest = null; + public static void setLastChest(BlockPos pos) { lastChest = pos; alpha = Config.getConfig().HighlightChestDuration; } public static void render(MatrixStack matrices, VertexConsumerProvider.Immediate vertexConsumers, double cameraX, double cameraY, double cameraZ) { - if(CodeClient.location instanceof Dev) { - if(lastChest == null) return; - VoxelShape shape = CodeClient.MC.world.getBlockState(lastChest).getOutlineShape(CodeClient.MC.world, lastChest).offset(lastChest.getX(),lastChest.getY(),lastChest.getZ()); + if (CodeClient.location instanceof Dev) { + if (lastChest == null) return; + VoxelShape shape = CodeClient.MC.world.getBlockState(lastChest).getOutlineShape(CodeClient.MC.world, lastChest).offset(lastChest.getX(), lastChest.getY(), lastChest.getZ()); VertexConsumer vertexConsumer = vertexConsumers.getBuffer(RenderLayer.getLines()); - int color = Config.getConfig().ChestHighlightColor; - WorldRenderer.drawShapeOutline(matrices, vertexConsumer, shape, -cameraX, -cameraY, -cameraZ, (float) (color >> 16) / 255, (float) ((color & 0xFF00) >> 8) / 255, (float) (color & 0x0000FF) / 255, Math.min(alpha,1), true); + int color = Config.getConfig().ChestHighlightColor; + WorldRenderer.drawShapeOutline(matrices, vertexConsumer, shape, -cameraX, -cameraY, -cameraZ, (float) (color >> 16) / 255, (float) ((color & 0xFF00) >> 8) / 255, (float) (color & 0x0000FF) / 255, Math.min(alpha, 1), true); } } public static void tick() { - if(lastChest != null) alpha -= 0.05F; - if(alpha <= 0) lastChest = null; + if (lastChest != null) alpha -= 0.05F; + if (alpha <= 0) lastChest = null; } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryGroup.java b/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryGroup.java index ac4e325a..c562e4c8 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryGroup.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryGroup.java @@ -18,6 +18,127 @@ public class DevInventoryGroup { + public static final int TAB_WIDTH = 28; + public static final int TAB_HEIGHT = 28; + public static final DevInventoryGroup[] GROUPS = new DevInventoryGroup[21]; + public static final DevInventoryGroup PLAYER_EVENT = new DevInventoryGroup("event", "Player Event", Items.DIAMOND_BLOCK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup PLAYER_IF = new DevInventoryGroup("if_player", "If Player", Items.OAK_PLANKS.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup PLAYER_ACTION = new DevInventoryGroup("player_action", "Player Action", Items.COBBLESTONE.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup ENTITY_EVENT = new DevInventoryGroup("entity_event", "Entity Event", Items.GOLD_BLOCK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup ENTITY_IF = new DevInventoryGroup("if_entity", "If Entity", Items.BRICKS.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup ENTITY_ACTION = new DevInventoryGroup("entity_action", "Entity Action", Items.MOSSY_COBBLESTONE.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup SEARCH = new DevInventoryGroup("search", "Search All", Items.COMPASS.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup VAR_SET = new DevInventoryGroup("set_var", "Set Variable", Items.IRON_BLOCK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup VAR_IF = new DevInventoryGroup("if_var", "If Variable", Items.OBSIDIAN.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup GAME_ACTION = new DevInventoryGroup("game_action", "Game Action", Items.NETHERRACK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup GAME_IF = new DevInventoryGroup("if_game", "If Game", Items.RED_NETHER_BRICKS.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup CONTROL = new DevInventoryGroup("control", "Control", Items.COAL_BLOCK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup SELECT_OBJECT = new DevInventoryGroup("select_obj", "Select Object", Items.PURPUR_BLOCK.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup REPEAT = new DevInventoryGroup("repeat", "Repeat", Items.PRISMARINE.getDefaultStack(), true).useCodeBlock(); + public static final DevInventoryGroup SOUNDS = new DevInventoryGroup("sound", "Sounds", Items.NAUTILUS_SHELL.getDefaultStack(), false); + public static final DevInventoryGroup PARTICLES = new DevInventoryGroup("particle", "Particles", Items.WHITE_DYE.getDefaultStack(), false); + public static final DevInventoryGroup POTIONS = new DevInventoryGroup("potion", "Potions", Items.DRAGON_BREATH.getDefaultStack(), false); + public static final DevInventoryGroup GAME_VALUES = new DevInventoryGroup("game_value", "Game Values", Items.NAME_TAG.getDefaultStack(), false); + public static final DevInventoryGroup OTHERS = new DevInventoryGroup("others", "Other Items", Items.IRON_INGOT.getDefaultStack(), false).disableSearch(); + public static final DevInventoryGroup SAVED_TEMPLATES = new DevInventoryGroup("saved_templates", "Saved Templates", Items.ENDER_CHEST.getDefaultStack(), false); + public static final DevInventoryGroup INVENTORY = new DevInventoryGroup("inventory", "Inventory", Items.CHEST.getDefaultStack(), false).disableSearch(); + public static int TOP_HALF = -1; + private static int global = 0; + + static { + OTHERS.setItemsProvider(query -> { + ArrayList items = emptyMenu(); + try { + items.set(0, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:string\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"txt\",\"data\":{\"name\":\"string\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A series of characters which\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"is highly manipulatable.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Recommended for variable\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"operations.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in the chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \\'\"},{\"italic\":false,\"color\":\"white\",\"text\":\"Sample text\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\\'\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"aqua\",\"text\":\"String\"}],\"text\":\"\"}'}}}")))); + items.set(1, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:book\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"comp\",\"data\":{\"name\":\"text\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Text with extra formatting via\"}],\"text\":\"\"}','{\"extra\":[{\"italic\":false,\"color\":\"white\",\"text\":\"MiniMessage\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" tags such as \"},{\"italic\":false,\"color\":\"white\",\"text\":\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\".\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Recommended for text displayed\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"through chat, item names, and others.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in the chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \\'\"},{\"italic\":false,\"color\":\"white\",\"text\":\"Rainbow text!\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\\'\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#7FD42A\",\"text\":\"Styled Text\"}],\"text\":\"\"}'}}}")))); + items.set(2, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:slime_ball\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"num\",\"data\":{\"name\":\"0\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a number of an\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"integer or a decimal. It can\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"have up to 3 decimal places.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type a number in chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \"},{\"italic\":false,\"color\":\"white\",\"text\":\"4\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" or \"},{\"italic\":false,\"color\":\"white\",\"text\":\"1.25\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"red\",\"text\":\"Number\"}],\"text\":\"\"}'}}}")))); + items.set(3, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:paper\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"loc\",\"data\":{\"isBlock\":false,\"loc\":{\"x\":0.0,\"y\":0.0,\"z\":0.0,\"pitch\":0.0,\"yaw\":0.0}}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a location in the plot.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"[0,0,0] points to the north-west\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"bottom corner of the plot.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to set it\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to your current location.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to set it to a block.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift left-click to teleport to it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"green\",\"text\":\"Location\"}],\"text\":\"\"}'}}}")))); + items.set(4, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:prismarine_shard\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"vec\",\"data\":{\"x\":0.0,\"y\":0.0,\"z\":0.0}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A vector consists of X, Y and\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Z values. Used for multiple\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"purposes such as representing\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a direction, motion or an offset.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /vector command or\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"type \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"\\\\\" \\\\\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" to set the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"components. Left-click to\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#2AFFAA\",\"text\":\"Vector\"}],\"text\":\"\"}'}}}")))); + items.set(5, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:nautilus_shell\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"snd\",\"data\":{\"pitch\":1.0,\"vol\":2.0,\"sound\":\"Pling\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a Minecraft sound or a\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"custom sound from resource pack.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a sound effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift right-click to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a variant of the sound.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"To add a pitch & volume, type\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"them in one chat line, in order.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"blue\",\"text\":\"Sound\"}],\"text\":\"\"}'}}}")))); + items.set(6, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:white_dye\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"part\",\"data\":{\"particle\":\"Cloud\",\"cluster\":{\"amount\":1,\"horizontal\":0.0,\"vertical\":0.0},\"data\":{\"x\":1.0,\"y\":0.0,\"z\":0.0,\"motionVariation\":100}}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a particle effect with\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"customizable parameters.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a particle effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /particle command\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to change its parameters.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#AA55FF\",\"text\":\"Particle\"}],\"text\":\"\"}'}}}")))); + + items.set(9, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:dragon_breath\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"pot\",\"data\":{\"pot\":\"Speed\",\"dur\":1000000,\"amp\":0}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a potion effect with\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"custom amplifier and duration.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a potion effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /potion command or\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"type \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"\\\\\" [duration]\\\\\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to set its options. Left-click\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#FF557F\",\"text\":\"Potion Effect\"}],\"text\":\"\"}'}}}")))); + items.set(10, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:magma_cream\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"var\",\"data\":{\"name\":\"&eVariable\",\"scope\":\"unsaved\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Variables can store values inside.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Give a name to your variable, and\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"use \"},{\"italic\":false,\"color\":\"white\",\"text\":\"Set Variable\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" to set its value.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type a variable name in chat\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"while holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift right-click for options.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"yellow\",\"text\":\"Variable\"}],\"text\":\"\"}'}}}")))); + items.set(11, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:name_tag\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"g_val\",\"data\":{\"type\":\"Location\",\"target\":\"Default\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"An automatically set value based\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"on the game\\'s current conditions\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"(e.g. a player\\'s location).\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to select a game\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"value and its target.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#FFD47F\",\"text\":\"Game Value\"}],\"text\":\"\"}'}}}")))); + items.set(12, new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:ender_eye\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"pn_el\",\"data\":{\"name\":\"name\",\"type\":\"any\",\"plural\":false,\"optional\":false}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A parameter to put in the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"code chest of a \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"function\"},{\"italic\":false,\"color\":\"gray\",\"text\":\".\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in chat to edit name.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to open the editor.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#AAFFAA\",\"text\":\"Parameter\"}],\"text\":\"\"}'}}}")))); + + + int i = 0; + for (CodeBlock codeblock : ActionDump.getActionDump().codeblocks) { + items.set(27 + i, codeblock); + i++; + } + + // Items bellow except arrow cannot be normally given since they have an item_instance that changes per node and every restart, + // so unless the player is in dev mode with these items in their inventory already we cannot display the usable items. + // Caching the item_instance for each node can also be a solution. +// items.set(8,ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:written_book\",tag:{CustomModelData:0,HideFlags:127,PublicBukkitValues:{\"hypercube:item_instance\":\"18726d32-57ae-4305-b317-2b084283e704\"},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to open the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"reference menu.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"extra\":[{\"color\":\"gold\",\"text\":\"◆ \"},{\"color\":\"aqua\",\"text\":\"Reference Book \"},{\"color\":\"gold\",\"text\":\"◆\"}],\"text\":\"\"}'}}}"))); +// items.set(17,ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:blaze_rod\",tag:{CustomModelData:0,HideFlags:127,PublicBukkitValues:{\"hypercube:item_instance\":\"de7f011e-8248-40e6-b04f-8315c4c7be4a\"},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shows two corresponding brackets\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"for a short amount of time.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-Click a bracket to highlight\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"both.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"color\":\"gold\",\"text\":\"Bracket Finder\"}'}}}"))); +// items.set(26, ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:arrow\",tag:{CustomModelData:0,HideFlags:127,display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Click on a Condition block with this\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to switch between \\'IF\\' and \\'IF NOT\\'.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"color\":\"red\",\"text\":\"NOT Arrow\"}'}}}"))); + } catch (Exception e) { + e.printStackTrace(); + } + return items; + }); + try { + ActionDump actionDump = ActionDump.getActionDump(); + GAME_VALUES.useCategory(actionDump.gameValues); + SOUNDS.useCategory(actionDump.sounds); + POTIONS.useCategory(actionDump.potions); + PARTICLES.useCategory(actionDump.particles); + + SAVED_TEMPLATES.setItemsProvider(query -> { + ArrayList items = new ArrayList<>(); + if (query == null) query = ""; + query = query.toLowerCase(); + for (Searchable template : readTemplates(FileManager.templatesPath())) { + for (String term : template.getTerms()) + if (term.toLowerCase().contains(query)) { + items.add(template); + break; + } + } + return items; + }); + SEARCH.setItemsProvider(query -> { + ArrayList items = new ArrayList<>(); + if (query == null) query = ""; + else query = query.toLowerCase(); + for (Action action : actionDump.actions) { + if (action.isInvalid()) continue; + for (String term : action.getTerms()) + if (term.toLowerCase().contains(query)) { + items.add(action); + break; + } + } + for (GameValue gameValue : actionDump.gameValues) { + for (String term : gameValue.getTerms()) + if (term.toLowerCase().contains(query)) { + items.add(gameValue); + break; + } + } + for (Sound sound : actionDump.sounds) { + for (String term : sound.getTerms()) + if (term.toLowerCase().contains(query)) { + items.add(sound); + break; + } + } + for (Potion potion : actionDump.potions) { + for (String term : potion.getTerms()) + if (term.toLowerCase().contains(query)) { + items.add(potion); + break; + } + } + return items; + }); + } catch (Exception ignored) { + } + } + private final int index; private final String id; private final ItemStack icon; @@ -25,34 +146,66 @@ public class DevInventoryGroup { private final boolean topHalf; private boolean hasSearchBar = true; private ItemsProvider itemsProvider = null; - - private static int global = 0; public DevInventoryGroup(String id, String name, ItemStack icon, boolean topHalf) { this.index = global; this.id = id; this.icon = icon; this.name = Text.of(name); this.topHalf = topHalf; - if(!topHalf && TOP_HALF == -1) TOP_HALF = global + 1; + if (!topHalf && TOP_HALF == -1) TOP_HALF = global + 1; GROUPS[index] = this; global++; } + + private static ArrayList emptyMenu() { + ArrayList items = new ArrayList<>(); + for (int i = 0; i < 45; i++) { + items.add(new Searchable.StaticSearchable(Items.AIR.getDefaultStack())); + } + return items; + } + + static private ArrayList readTemplates(Path path) { + return readTemplates(path, path); + } + + static private ArrayList readTemplates(Path path, Path root) { + var list = new ArrayList(); + try { + var dir = Files.list(path); + for (var file : dir.toList()) { + if (Files.isDirectory(file)) list.addAll(readTemplates(file, root)); + if (file.getFileName().toString().endsWith(".dft")) { + byte[] data = Files.readAllBytes(file); + ItemStack template = Utility.makeTemplate(new String(Base64.getEncoder().encode(data))); + template.setCustomName(Text.empty().formatted(Formatting.RED).append("Saved Template").append(Text.literal(" » ").formatted(Formatting.DARK_RED, Formatting.BOLD)).append(String.valueOf(root.relativize(file)))); + list.add(new Searchable.StaticSearchable(template)); + } + } + dir.close(); + } catch (IOException ignored) { + } + return list; + } + private DevInventoryGroup disableSearch() { this.itemsProvider = null; this.hasSearchBar = false; return this; } + private DevInventoryGroup setItemsProvider(ItemsProvider itemsProvider) { this.itemsProvider = itemsProvider; return this; } public List searchItems(String query) { - if(this.itemsProvider == null) return null; + if (this.itemsProvider == null) return null; return this.itemsProvider.run(query); } + public Text getName() { return name; } @@ -72,6 +225,7 @@ public boolean hasSearchBar() { public boolean isTopHalf() { return this.topHalf; } + public int getPlace() { return this.index - (isTopHalf() ? 0 : TOP_HALF - 1); } @@ -79,78 +233,41 @@ public int getPlace() { public int getColumn() { return getPlace() % 7; } - public int getRow() { return getPlace() / 7; } - + public int getRow() { + return getPlace() / 7; + } public int getDisplayX(int originX) { return originX + getColumn() * TAB_WIDTH; } + public int getDisplayY(int originY, int menuHeight) { int multiplier = TAB_HEIGHT * (isTopHalf() ? -1 : 1); int y = (getRow() * multiplier) + originY + (isTopHalf() ? (TAB_HEIGHT * -1 - 4) : menuHeight); return y; } - public static final int TAB_WIDTH = 28; - public static final int TAB_HEIGHT = 28; - - - public static int TOP_HALF = -1; - public static final DevInventoryGroup[] GROUPS = new DevInventoryGroup[21]; - - public static final DevInventoryGroup PLAYER_EVENT = new DevInventoryGroup("event", "Player Event", Items.DIAMOND_BLOCK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup PLAYER_IF = new DevInventoryGroup("if_player", "If Player", Items.OAK_PLANKS.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup PLAYER_ACTION = new DevInventoryGroup("player_action", "Player Action", Items.COBBLESTONE.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup ENTITY_EVENT = new DevInventoryGroup("entity_event", "Entity Event", Items.GOLD_BLOCK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup ENTITY_IF = new DevInventoryGroup("if_entity", "If Entity", Items.BRICKS.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup ENTITY_ACTION = new DevInventoryGroup("entity_action", "Entity Action", Items.MOSSY_COBBLESTONE.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup SEARCH = new DevInventoryGroup("search", "Search All", Items.COMPASS.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup VAR_SET = new DevInventoryGroup("set_var", "Set Variable", Items.IRON_BLOCK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup VAR_IF = new DevInventoryGroup("if_var", "If Variable", Items.OBSIDIAN.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup GAME_ACTION = new DevInventoryGroup("game_action", "Game Action", Items.NETHERRACK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup GAME_IF = new DevInventoryGroup("if_game", "If Game", Items.RED_NETHER_BRICKS.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup CONTROL = new DevInventoryGroup("control", "Control", Items.COAL_BLOCK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup SELECT_OBJECT = new DevInventoryGroup("select_obj", "Select Object", Items.PURPUR_BLOCK.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup REPEAT = new DevInventoryGroup("repeat", "Repeat", Items.PRISMARINE.getDefaultStack(), true).useCodeBlock(); - public static final DevInventoryGroup SOUNDS = new DevInventoryGroup("sound", "Sounds", Items.NAUTILUS_SHELL.getDefaultStack(), false); - public static final DevInventoryGroup PARTICLES = new DevInventoryGroup("particle", "Particles", Items.WHITE_DYE.getDefaultStack(), false); - public static final DevInventoryGroup POTIONS = new DevInventoryGroup("potion", "Potions", Items.DRAGON_BREATH.getDefaultStack(), false); - public static final DevInventoryGroup GAME_VALUES = new DevInventoryGroup("game_value", "Game Values", Items.NAME_TAG.getDefaultStack(), false); - public static final DevInventoryGroup OTHERS = new DevInventoryGroup("others", "Other Items", Items.IRON_INGOT.getDefaultStack(), false).disableSearch(); - public static final DevInventoryGroup SAVED_TEMPLATES = new DevInventoryGroup("saved_templates", "Saved Templates", Items.ENDER_CHEST.getDefaultStack(), false); - public static final DevInventoryGroup INVENTORY = new DevInventoryGroup("inventory", "Inventory", Items.CHEST.getDefaultStack(), false).disableSearch(); - - interface ItemsProvider { - List run(String query); - } - - private static ArrayList emptyMenu() { - ArrayList items = new ArrayList<>(); - for (int i = 0; i < 45; i++) { - items.add(new Searchable.StaticSearchable(Items.AIR.getDefaultStack())); - } - return items; - } private DevInventoryGroup useCodeBlock() { this.itemsProvider = query -> { ArrayList items = new ArrayList<>(); try { - if(query == null) for (CodeBlock codeblock: ActionDump.getActionDump().codeblocks) { - if(codeblock.identifier.equals(this.id)) items.add(codeblock); + if (query == null) for (CodeBlock codeblock : ActionDump.getActionDump().codeblocks) { + if (codeblock.identifier.equals(this.id)) items.add(codeblock); } - for (Action action: ActionDump.getActionDump().actions) { - if(action.getCodeBlock().identifier.equals(this.id) && !action.isInvalid()) { - if(query == null) items.add(action); + for (Action action : ActionDump.getActionDump().actions) { + if (action.getCodeBlock().identifier.equals(this.id) && !action.isInvalid()) { + if (query == null) items.add(action); else { - for (String term: action.getTerms()) { - if(term.toLowerCase().contains(query.toLowerCase())) items.add(action); + for (String term : action.getTerms()) { + if (term.toLowerCase().contains(query.toLowerCase())) items.add(action); break; } } } } - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return items; }; return this; @@ -159,11 +276,11 @@ private DevInventoryGroup useCodeBlock() { private DevInventoryGroup useCategory(Searchable[] categoryValues) { this.itemsProvider = query -> { ArrayList items = new ArrayList<>(); - for (Searchable value: categoryValues) { - if(query == null) items.add(value); + for (Searchable value : categoryValues) { + if (query == null) items.add(value); else { - for (String term: value.getTerms()) { - if(term.toLowerCase().replaceAll("[_ ]","").contains(query.toLowerCase())) { + for (String term : value.getTerms()) { + if (term.toLowerCase().replaceAll("[_ ]", "").contains(query.toLowerCase())) { items.add(value); break; } @@ -175,116 +292,7 @@ private DevInventoryGroup useCategory(Searchable[] categoryValues) { return this; } - static { - OTHERS.setItemsProvider(query -> { - ArrayList items = emptyMenu(); - try { - items.set(0,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:string\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"txt\",\"data\":{\"name\":\"string\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A series of characters which\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"is highly manipulatable.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Recommended for variable\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"operations.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in the chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \\'\"},{\"italic\":false,\"color\":\"white\",\"text\":\"Sample text\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\\'\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"aqua\",\"text\":\"String\"}],\"text\":\"\"}'}}}")))); - items.set(1,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:book\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"comp\",\"data\":{\"name\":\"text\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Text with extra formatting via\"}],\"text\":\"\"}','{\"extra\":[{\"italic\":false,\"color\":\"white\",\"text\":\"MiniMessage\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" tags such as \"},{\"italic\":false,\"color\":\"white\",\"text\":\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\".\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Recommended for text displayed\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"through chat, item names, and others.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in the chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \\'\"},{\"italic\":false,\"color\":\"white\",\"text\":\"Rainbow text!\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\\'\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#7FD42A\",\"text\":\"Styled Text\"}],\"text\":\"\"}'}}}")))); - items.set(2,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:slime_ball\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"num\",\"data\":{\"name\":\"0\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a number of an\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"integer or a decimal. It can\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"have up to 3 decimal places.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type a number in chat while\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"E.g. \"},{\"italic\":false,\"color\":\"white\",\"text\":\"4\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" or \"},{\"italic\":false,\"color\":\"white\",\"text\":\"1.25\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"red\",\"text\":\"Number\"}],\"text\":\"\"}'}}}")))); - items.set(3,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:paper\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"loc\",\"data\":{\"isBlock\":false,\"loc\":{\"x\":0.0,\"y\":0.0,\"z\":0.0,\"pitch\":0.0,\"yaw\":0.0}}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a location in the plot.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"[0,0,0] points to the north-west\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"bottom corner of the plot.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to set it\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to your current location.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to set it to a block.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift left-click to teleport to it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"green\",\"text\":\"Location\"}],\"text\":\"\"}'}}}")))); - items.set(4,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:prismarine_shard\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"vec\",\"data\":{\"x\":0.0,\"y\":0.0,\"z\":0.0}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A vector consists of X, Y and\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Z values. Used for multiple\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"purposes such as representing\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a direction, motion or an offset.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /vector command or\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"type \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"\\\\\" \\\\\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" to set the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"components. Left-click to\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#2AFFAA\",\"text\":\"Vector\"}],\"text\":\"\"}'}}}")))); - items.set(5,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:nautilus_shell\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"snd\",\"data\":{\"pitch\":1.0,\"vol\":2.0,\"sound\":\"Pling\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a Minecraft sound or a\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"custom sound from resource pack.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a sound effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift right-click to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a variant of the sound.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"To add a pitch & volume, type\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"them in one chat line, in order.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"blue\",\"text\":\"Sound\"}],\"text\":\"\"}'}}}")))); - items.set(6,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:white_dye\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"part\",\"data\":{\"particle\":\"Cloud\",\"cluster\":{\"amount\":1,\"horizontal\":0.0,\"vertical\":0.0},\"data\":{\"x\":1.0,\"y\":0.0,\"z\":0.0,\"motionVariation\":100}}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a particle effect with\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"customizable parameters.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a particle effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /particle command\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to change its parameters.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Left-click to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#AA55FF\",\"text\":\"Particle\"}],\"text\":\"\"}'}}}")))); - - items.set(9,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:dragon_breath\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"pot\",\"data\":{\"pot\":\"Speed\",\"dur\":1000000,\"amp\":0}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Represents a potion effect with\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"custom amplifier and duration.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click this item to select\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"a potion effect.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Use the /potion command or\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"type \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"\\\\\" [duration]\\\\\"\"},{\"italic\":false,\"color\":\"gray\",\"text\":\"\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to set its options. Left-click\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to preview it.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#FF557F\",\"text\":\"Potion Effect\"}],\"text\":\"\"}'}}}")))); - items.set(10,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:magma_cream\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"var\",\"data\":{\"name\":\"&eVariable\",\"scope\":\"unsaved\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Variables can store values inside.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Give a name to your variable, and\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"use \"},{\"italic\":false,\"color\":\"white\",\"text\":\"Set Variable\"},{\"italic\":false,\"color\":\"gray\",\"text\":\" to set its value.\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type a variable name in chat\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"while holding this item.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shift right-click for options.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"yellow\",\"text\":\"Variable\"}],\"text\":\"\"}'}}}")))); - items.set(11,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:name_tag\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"g_val\",\"data\":{\"type\":\"Location\",\"target\":\"Default\"}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"An automatically set value based\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"on the game\\'s current conditions\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"(e.g. a player\\'s location).\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to select a game\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"value and its target.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#FFD47F\",\"text\":\"Game Value\"}],\"text\":\"\"}'}}}")))); - items.set(12,new Searchable.StaticSearchable(ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:ender_eye\",tag:{CustomModelData:5000,HideFlags:-1,PublicBukkitValues:{\"hypercube:varitem\":'{\"id\":\"pn_el\",\"data\":{\"name\":\"name\",\"type\":\"any\",\"plural\":false,\"optional\":false}}'},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"A parameter to put in the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"code chest of a \"},{\"italic\":false,\"color\":\"aqua\",\"text\":\"function\"},{\"italic\":false,\"color\":\"gray\",\"text\":\".\"}],\"text\":\"\"}','{\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"light_purple\",\"text\":\"How to set:\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Type in chat to edit name.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to open the editor.\"}],\"text\":\"\"}'],Name:'{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"#AAFFAA\",\"text\":\"Parameter\"}],\"text\":\"\"}'}}}")))); - - - int i = 0; - for (CodeBlock codeblock: ActionDump.getActionDump().codeblocks) { - items.set(27 + i, codeblock); - i++; - } - - // Items bellow except arrow cannot be normally given since they have an item_instance that changes per node and every restart, - // so unless the player is in dev mode with these items in their inventory already we cannot display the usable items. - // Caching the item_instance for each node can also be a solution. -// items.set(8,ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:written_book\",tag:{CustomModelData:0,HideFlags:127,PublicBukkitValues:{\"hypercube:item_instance\":\"18726d32-57ae-4305-b317-2b084283e704\"},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-click to open the\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"reference menu.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"extra\":[{\"color\":\"gold\",\"text\":\"◆ \"},{\"color\":\"aqua\",\"text\":\"Reference Book \"},{\"color\":\"gold\",\"text\":\"◆\"}],\"text\":\"\"}'}}}"))); -// items.set(17,ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:blaze_rod\",tag:{CustomModelData:0,HideFlags:127,PublicBukkitValues:{\"hypercube:item_instance\":\"de7f011e-8248-40e6-b04f-8315c4c7be4a\"},display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Shows two corresponding brackets\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"for a short amount of time.\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Right-Click a bracket to highlight\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"both.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"color\":\"gold\",\"text\":\"Bracket Finder\"}'}}}"))); -// items.set(26, ItemStack.fromNbt(NbtHelper.fromNbtProviderString("{Count:1b,id:\"minecraft:arrow\",tag:{CustomModelData:0,HideFlags:127,display:{Lore:['{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"Click on a Condition block with this\"}],\"text\":\"\"}','{\"extra\":[{\"bold\":false,\"italic\":false,\"underlined\":false,\"strikethrough\":false,\"obfuscated\":false,\"color\":\"gray\",\"text\":\"to switch between \\'IF\\' and \\'IF NOT\\'.\"}],\"text\":\"\"}'],Name:'{\"italic\":false,\"color\":\"red\",\"text\":\"NOT Arrow\"}'}}}"))); - } - catch (Exception e) { - e.printStackTrace(); - } - return items; - }); - try { - ActionDump actionDump = ActionDump.getActionDump(); - GAME_VALUES.useCategory(actionDump.gameValues); - SOUNDS.useCategory(actionDump.sounds); - POTIONS.useCategory(actionDump.potions); - PARTICLES.useCategory(actionDump.particles); - - SAVED_TEMPLATES.setItemsProvider(query -> { - ArrayList items = new ArrayList<>(); - if(query == null) query = ""; - query = query.toLowerCase(); - for (Searchable template: readTemplates(FileManager.templatesPath())) { - for (String term : template.getTerms()) if(term.toLowerCase().contains(query)) { - items.add(template); - break; - } - } - return items; - }); - SEARCH.setItemsProvider(query -> { - ArrayList items = new ArrayList<>(); - if(query == null) query = ""; - else query = query.toLowerCase(); - for (Action action: actionDump.actions) { - if(action.isInvalid()) continue; - for (String term : action.getTerms()) if(term.toLowerCase().contains(query)) { - items.add(action); - break; - } - } - for(GameValue gameValue: actionDump.gameValues) { - for (String term : gameValue.getTerms()) if(term.toLowerCase().contains(query)) { - items.add(gameValue); - break; - } - } - for(Sound sound: actionDump.sounds) { - for (String term : sound.getTerms()) if(term.toLowerCase().contains(query)) { - items.add(sound); - break; - } - } - for(Potion potion: actionDump.potions) { - for (String term : potion.getTerms()) if(term.toLowerCase().contains(query)) { - items.add(potion); - break; - } - } - return items; - }); - } - catch (Exception ignored) { - } - } - - static private ArrayList readTemplates(Path path) { - return readTemplates(path,path); - } - static private ArrayList readTemplates(Path path, Path root) { - var list = new ArrayList(); - try { - var dir = Files.list(path); - for (var file : dir.toList()) { - if(Files.isDirectory(file)) list.addAll(readTemplates(file,root)); - if(file.getFileName().toString().endsWith(".dft")) { - byte[] data = Files.readAllBytes(file); - ItemStack template = Utility.makeTemplate(new String(Base64.getEncoder().encode(data))); - template.setCustomName(Text.empty().formatted(Formatting.RED).append("Saved Template").append(Text.literal(" » ").formatted(Formatting.DARK_RED, Formatting.BOLD)).append(String.valueOf(root.relativize(file)))); - list.add(new Searchable.StaticSearchable(template)); - } - } - dir.close(); - } catch (IOException ignored) { - } - return list; + interface ItemsProvider { + List run(String query); } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryScreen.java b/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryScreen.java index 74ec6934..aaeff08d 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryScreen.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/DevInventory/DevInventoryScreen.java @@ -46,9 +46,9 @@ @Environment(EnvType.CLIENT) public class DevInventoryScreen extends AbstractInventoryScreen { - private static final Identifier TEXTURE = new Identifier(CodeClient.MOD_ID,"textures/gui/container/dev_inventory/tabs.png"); - private static final String TAB_TEXTURE_PREFIX = "textures/gui/container/creative_inventory/tab_"; static final SimpleInventory Inventory = new SimpleInventory(45); + private static final Identifier TEXTURE = new Identifier(CodeClient.MOD_ID, "textures/gui/container/dev_inventory/tabs.png"); + private static final String TAB_TEXTURE_PREFIX = "textures/gui/container/creative_inventory/tab_"; private static final Text DELETE_ITEM_SLOT_TEXT = Text.translatable("inventory.binSlot"); private static int selectedTab; private double scrollPosition; @@ -78,45 +78,46 @@ public void handledScreenTick() { } protected void onMouseClick(@Nullable Slot slot, int slotId, int button, SlotActionType actionType) { - if(slot == null) return; + if (slot == null) return; this.searchBox.setCursorToEnd(false); this.searchBox.setSelectionEnd(0); - if(slot == this.deleteItemSlot) { + if (slot == this.deleteItemSlot) { (this.handler).setCursorStack(ItemStack.EMPTY); return; } - if(slot.inventory instanceof SimpleInventory) { - if(actionType == SlotActionType.PICKUP) { - if(this.handler.getCursorStack().getItem().equals(Items.AIR)) this.handler.setCursorStack(slot.getStack()); + if (slot.inventory instanceof SimpleInventory) { + if (actionType == SlotActionType.PICKUP) { + if (this.handler.getCursorStack().getItem().equals(Items.AIR)) + this.handler.setCursorStack(slot.getStack()); else this.handler.setCursorStack(Items.AIR.getDefaultStack()); } } - if(slot.inventory instanceof PlayerInventory) { + if (slot.inventory instanceof PlayerInventory) { ItemStack slotStack = slot.getStack(); ItemStack cursorItem = this.handler.getCursorStack(); slot.setStack(cursorItem); this.handler.setCursorStack(slotStack); this.handler.syncState(); - this.listener.onSlotUpdate(this.handler,slot.id - 9,slot.getStack()); + this.listener.onSlotUpdate(this.handler, slot.id - 9, slot.getStack()); // CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(slot.id,slot.getStack())); } } + protected void init() { super.init(); - if(this.client == null || this.client.player == null) return; + if (this.client == null || this.client.player == null) return; try { ActionDump.getActionDump(); - } - catch (IOException | JsonParseException e) { + } catch (IOException | JsonParseException e) { CodeClient.LOGGER.error(e.getMessage()); Utility.sendMessage( - Text.translatable("codeclient.parse_db",Text.literal("https://github.com/DFOnline/CodeClient/wiki/actiondump").formatted(Formatting.AQUA,Formatting.UNDERLINE)) - .setStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/DFOnline/CodeClient/wiki/actiondump"))), - ChatType.FAIL); + Text.translatable("codeclient.parse_db", Text.literal("https://github.com/DFOnline/CodeClient/wiki/actiondump").formatted(Formatting.AQUA, Formatting.UNDERLINE)) + .setStyle(Style.EMPTY.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://github.com/DFOnline/CodeClient/wiki/actiondump"))), + ChatType.FAIL); } TextRenderer textRenderer = this.textRenderer; @@ -129,8 +130,8 @@ protected void init() { this.addSelectableChild(this.searchBox); // TODO: config for defaults on open setSelectedTab(6); - if(Config.getConfig().FocusSearch) - searchBox.setFocused(true); + if (Config.getConfig().FocusSearch) + searchBox.setFocused(true); searchBox.setCursorToEnd(false); searchBox.setSelectionEnd(0); this.client.player.playerScreenHandler.removeListener(this.listener); @@ -171,13 +172,14 @@ protected void drawForeground(DrawContext context, int mouseX, int mouseY) { context.drawText(textRenderer, itemGroup.getName(), 8, 6, 0x404040, false); } } -// + + // public boolean mouseClicked(double mouseX, double mouseY, int button) { if (button == 0) { - Integer clicked = getGroupFromMouse(mouseX,mouseY); - if(clicked != null && clicked != selectedTab) setSelectedTab(clicked); + Integer clicked = getGroupFromMouse(mouseX, mouseY); + if (clicked != null && clicked != selectedTab) setSelectedTab(clicked); - if(isClickInScrollbar(mouseX,mouseY)) { + if (isClickInScrollbar(mouseX, mouseY)) { this.scrolling = true; } } @@ -185,17 +187,17 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } public boolean mouseReleased(double mouseX, double mouseY, int button) { - if(button == 0) { + if (button == 0) { this.scrolling = false; } - return super.mouseReleased(mouseX,mouseY,button); + return super.mouseReleased(mouseX, mouseY, button); } public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) { - if(this.scrolling) { + if (this.scrolling) { int scrollOriginY = this.y + 18; int scrollEnd = scrollOriginY + 112; - double percentThrough = MathHelper.clamp(((float)mouseY - (float)scrollOriginY - 7.5F) / ((float)(scrollEnd - scrollOriginY) - 15.0F),0,1); + double percentThrough = MathHelper.clamp(((float) mouseY - (float) scrollOriginY - 7.5F) / ((float) (scrollEnd - scrollOriginY) - 15.0F), 0, 1); this.scrollPosition = ((double) this.scrollHeight / 9) * percentThrough; scroll(); } @@ -203,11 +205,11 @@ public boolean mouseDragged(double mouseX, double mouseY, int button, double del } private Integer getGroupFromMouse(double mouseX, double mouseY) { - double x = mouseX - (double)this.x; - double y = mouseY - (double)this.y; + double x = mouseX - (double) this.x; + double y = mouseY - (double) this.y; DevInventoryGroup[] groups = DevInventoryGroup.GROUPS; - for(int i = 0; i < groups.length; ++i) { + for (int i = 0; i < groups.length; ++i) { DevInventoryGroup itemGroup = groups[i]; if (this.isClickInTab(itemGroup, x, y)) { return i; @@ -223,8 +225,8 @@ private void setSelectedTab(int tab) { selectedTab = tab; - if(this.client == null || this.client.player == null) return; - if(group == DevInventoryGroup.INVENTORY && this.survivalInventorySwapList == null) { + if (this.client == null || this.client.player == null) return; + if (group == DevInventoryGroup.INVENTORY && this.survivalInventorySwapList == null) { ScreenHandler playerScreenHandler = this.client.player.playerScreenHandler; this.survivalInventorySwapList = ImmutableList.copyOf((this.handler).slots); this.handler.slots.clear(); @@ -237,7 +239,7 @@ private void setSelectedTab(int tab) { int slotSize = 18; - for(int i = 0; i < 27 && i < playerScreenHandler.slots.size(); ++i) { + for (int i = 0; i < 27 && i < playerScreenHandler.slots.size(); ++i) { int slotIndex = i + 9; int x = 9 + (slotIndex % 9) * slotSize; int y = 36 + slotIndex / 9 * slotSize; @@ -246,8 +248,7 @@ private void setSelectedTab(int tab) { this.handler.slots.add(slot); } return; - } - else if(this.survivalInventorySwapList != null) { + } else if (this.survivalInventorySwapList != null) { this.handler.slots.clear(); this.handler.slots.addAll(this.survivalInventorySwapList); this.survivalInventorySwapList = null; @@ -257,14 +258,15 @@ else if(this.survivalInventorySwapList != null) { } private void scroll() { - if( searchResults == null ) return; - scrollHeight = Math.max(0,(int) Math.ceil((double) (searchResults.size() - 45) / 9) * 9); + if (searchResults == null) return; + scrollHeight = Math.max(0, (int) Math.ceil((double) (searchResults.size() - 45) / 9) * 9); for (int i = 0; i < 45; i++) { int value = i + (int) scrollPosition * 9; - if(value < searchResults.size()) this.handler.slots.get(i).setStack(searchResults.get(value).getItem()); + if (value < searchResults.size()) this.handler.slots.get(i).setStack(searchResults.get(value).getItem()); else this.handler.slots.get(i).setStack(Items.AIR.getDefaultStack()); } } + private void populate() { DevInventoryGroup group = GROUPS[selectedTab]; // if(group == INVENTORY) { @@ -272,17 +274,17 @@ private void populate() { // return; // } String text = searchBox.getText(); - if(text.equals("")) text = null; + if (text.equals("")) text = null; searchResults = group.searchItems(text); - if(searchResults != null) this.scroll(); + if (searchResults != null) this.scroll(); } public void render(DrawContext context, int mouseX, int mouseY, float delta) { this.renderBackground(context, mouseX, mouseY, delta); super.render(context, mouseX, mouseY, delta); - Integer hoveredGroup = getGroupFromMouse(mouseX,mouseY); - if(hoveredGroup != null) { + Integer hoveredGroup = getGroupFromMouse(mouseX, mouseY); + if (hoveredGroup != null) { DevInventoryGroup group = GROUPS[hoveredGroup]; context.drawTooltip(textRenderer, GROUPS[hoveredGroup].getName(), mouseX, mouseY); } @@ -294,12 +296,13 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta) { RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); this.drawMouseoverTooltip(context, mouseX, mouseY); } + public boolean charTyped(char chr, int modifiers) { - if(ignoreNextKey) { + if (ignoreNextKey) { ignoreNextKey = false; return true; } - if(searchBox.charTyped(chr, modifiers)) { + if (searchBox.charTyped(chr, modifiers)) { populate(); return true; } @@ -307,28 +310,28 @@ public boolean charTyped(char chr, int modifiers) { } public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if(keyCode == GLFW.GLFW_KEY_GRAVE_ACCENT) { + if (keyCode == GLFW.GLFW_KEY_GRAVE_ACCENT) { this.close(); } - if(keyCode >= GLFW.GLFW_KEY_0 && keyCode <= GLFW.GLFW_KEY_9) { + if (keyCode >= GLFW.GLFW_KEY_0 && keyCode <= GLFW.GLFW_KEY_9) { int number = keyCode - GLFW.GLFW_KEY_1; - if(number == -1) number = 9; + if (number == -1) number = 9; Slot slot = this.handler.slots.get(number); - if(this.client == null || this.client.player == null) return false; + if (this.client == null || this.client.player == null) return false; this.client.player.setStackInHand(Hand.MAIN_HAND, slot.getStack()); - if(CodeClient.MC.getNetworkHandler() != null) Utility.sendHandItem(slot.getStack()); + if (CodeClient.MC.getNetworkHandler() != null) Utility.sendHandItem(slot.getStack()); this.ignoreNextKey = true; return true; } - if(keyCode == GLFW.GLFW_KEY_UP || keyCode == GLFW.GLFW_KEY_DOWN) { + if (keyCode == GLFW.GLFW_KEY_UP || keyCode == GLFW.GLFW_KEY_DOWN) { selectedTab += 7 * ((keyCode == GLFW.GLFW_KEY_DOWN) ? -1 : 1); selectedTab %= GROUPS.length; - if(selectedTab < 0) selectedTab = GROUPS.length + selectedTab; + if (selectedTab < 0) selectedTab = GROUPS.length + selectedTab; setSelectedTab(selectedTab); return true; } - if(keyCode != GLFW.GLFW_KEY_TAB && searchBox.isFocused()) { - if(keyCode == GLFW.GLFW_KEY_ESCAPE) { + if (keyCode != GLFW.GLFW_KEY_TAB && searchBox.isFocused()) { + if (keyCode == GLFW.GLFW_KEY_ESCAPE) { this.searchBox.setFocused(false); this.setFocused(null); return false; @@ -337,18 +340,17 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { populate(); return true; } - if(keyCode == GLFW.GLFW_KEY_TAB || keyCode == GLFW.GLFW_KEY_RIGHT || keyCode == GLFW.GLFW_KEY_LEFT) { - if((modifiers & GLFW.GLFW_MOD_SHIFT) == 1 || keyCode == GLFW.GLFW_KEY_LEFT) { + if (keyCode == GLFW.GLFW_KEY_TAB || keyCode == GLFW.GLFW_KEY_RIGHT || keyCode == GLFW.GLFW_KEY_LEFT) { + if ((modifiers & GLFW.GLFW_MOD_SHIFT) == 1 || keyCode == GLFW.GLFW_KEY_LEFT) { selectedTab = selectedTab - 1; - if(selectedTab < 0) selectedTab = GROUPS.length + selectedTab; + if (selectedTab < 0) selectedTab = GROUPS.length + selectedTab; setSelectedTab(selectedTab); - } - else setSelectedTab((selectedTab + 1) % GROUPS.length); + } else setSelectedTab((selectedTab + 1) % GROUPS.length); return true; } - if(searchBox.active) { - if(CodeClient.MC.options.chatKey.matchesKey(keyCode,scanCode) || CodeClient.editBind.matchesKey(keyCode,scanCode)) { - if(keyCode == GLFW.GLFW_KEY_Y) setSelectedTab(SEARCH.getIndex()); + if (searchBox.active) { + if (CodeClient.MC.options.chatKey.matchesKey(keyCode, scanCode) || CodeClient.editBind.matchesKey(keyCode, scanCode)) { + if (keyCode == GLFW.GLFW_KEY_Y) setSelectedTab(SEARCH.getIndex()); searchBox.setFocused(true); searchBox.setCursorToEnd(false); searchBox.setSelectionEnd(0); @@ -363,7 +365,7 @@ protected void drawBackground(DrawContext context, float delta, int mouseX, int RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); DevInventoryGroup itemGroup = DevInventoryGroup.GROUPS[selectedTab]; - for(DevInventoryGroup group : DevInventoryGroup.GROUPS) { + for (DevInventoryGroup group : DevInventoryGroup.GROUPS) { RenderSystem.setShader(GameRenderer::getPositionTexProgram); RenderSystem.setShaderTexture(0, TEXTURE); this.renderTabIcon(context, group); @@ -371,23 +373,24 @@ protected void drawBackground(DrawContext context, float delta, int mouseX, int RenderSystem.setShader(GameRenderer::getPositionTexProgram); String texture = "item_search"; - if(!itemGroup.hasSearchBar()) texture = "items"; - if(itemGroup == INVENTORY) texture = "inventory"; + if (!itemGroup.hasSearchBar()) texture = "items"; + if (itemGroup == INVENTORY) texture = "inventory"; context.drawTexture(new Identifier(TAB_TEXTURE_PREFIX + texture + ".png"), this.x, this.y, 0, 0, this.backgroundWidth, this.backgroundHeight); RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F); RenderSystem.setShader(GameRenderer::getPositionTexProgram); RenderSystem.setShaderTexture(0, TEXTURE); this.renderTabIcon(context, itemGroup); - if(itemGroup.hasSearchBar()) this.searchBox.render(context, mouseX, mouseY, delta); + if (itemGroup.hasSearchBar()) this.searchBox.render(context, mouseX, mouseY, delta); if (itemGroup != INVENTORY) { int scrollbarX = this.x + 175; int scrollbarY = this.y + 18; - if(scrollHeight == 0) context.drawTexture(TEXTURE, scrollbarX, scrollbarY, 244, 0, 12, 15); - else context.drawTexture(TEXTURE, scrollbarX, scrollbarY + (95 * (int) (this.scrollPosition * 9) / (scrollHeight)), 232, 0, 12, 15); - } - else { - if(this.client != null && this.client.player != null) InventoryScreen.drawEntity(context, this.x + 73, this.y + 6, this.x + 105, this.y + 49, 20, 0.0625F, (float)mouseX, (float)mouseY, this.client.player); + if (scrollHeight == 0) context.drawTexture(TEXTURE, scrollbarX, scrollbarY, 244, 0, 12, 15); + else + context.drawTexture(TEXTURE, scrollbarX, scrollbarY + (95 * (int) (this.scrollPosition * 9) / (scrollHeight)), 232, 0, 12, 15); + } else { + if (this.client != null && this.client.player != null) + InventoryScreen.drawEntity(context, this.x + 73, this.y + 6, this.x + 105, this.y + 49, 20, 0.0625F, (float) mouseX, (float) mouseY, this.client.player); } } @@ -397,7 +400,7 @@ protected boolean isClickInTab(DevInventoryGroup group, double mouseX, double mo int y = group.getDisplayY(0, this.backgroundHeight); return mouseX >= x && mouseX <= (x + TAB_WIDTH) - && mouseY >= y && mouseY <= (y + TAB_HEIGHT); + && mouseY >= y && mouseY <= (y + TAB_HEIGHT); } protected void renderTabIcon(DrawContext context, DevInventoryGroup group) { @@ -409,7 +412,7 @@ protected void renderTabIcon(DrawContext context, DevInventoryGroup group) { int originX = group.getDisplayX(this.x); int originY = group.getDisplayY(this.y, this.backgroundHeight); if (isSelected) mapY += 32; - if(!isTopRow) mapY += 64; + if (!isTopRow) mapY += 64; context.drawTexture(TEXTURE, originX, originY, mapX, mapY, TAB_WIDTH, 32); // this.itemRenderer.zOffset = 100.0F; @@ -422,23 +425,23 @@ protected void renderTabIcon(DrawContext context, DevInventoryGroup group) { @Override public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { - if(!GROUPS[selectedTab].hasSearchBar()) return false; + if (!GROUPS[selectedTab].hasSearchBar()) return false; this.scrollPosition -= verticalAmount; - if(scrollPosition < 0) scrollPosition = 0; - if((scrollPosition * 9) > scrollHeight) scrollPosition = (double) scrollHeight / 9; + if (scrollPosition < 0) scrollPosition = 0; + if ((scrollPosition * 9) > scrollHeight) scrollPosition = (double) scrollHeight / 9; scroll(); return true; } protected boolean isClickInScrollbar(double mouseX, double mouseY) { - if(!GROUPS[selectedTab].hasSearchBar()) return false; + if (!GROUPS[selectedTab].hasSearchBar()) return false; int windowX = this.x; int windowY = this.y; int scrollOriginX = windowX + 175; int scrollOriginY = windowY + 18; int scrollFarX = scrollOriginX + 14; int scrollFarY = scrollOriginY + 112; - return mouseX >= (double)scrollOriginX && mouseY >= (double)scrollOriginY && mouseX < (double)scrollFarX && mouseY < (double)scrollFarY; + return mouseX >= (double) scrollOriginX && mouseY >= (double) scrollOriginY && mouseX < (double) scrollFarX && mouseY < (double) scrollFarY; } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestField.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestField.java index d8a7dbae..65d3a426 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestField.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestField.java @@ -1,6 +1,5 @@ package dev.dfonline.codeclient.dev.menu.customchest; -import dev.dfonline.codeclient.Utility; import dev.dfonline.codeclient.hypercube.Target; import dev.dfonline.codeclient.hypercube.item.*; import net.minecraft.client.font.TextRenderer; @@ -9,13 +8,15 @@ import net.minecraft.client.gui.navigation.GuiNavigationPath; import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; import net.minecraft.client.gui.screen.narration.NarrationPart; -import net.minecraft.client.gui.widget.*; +import net.minecraft.client.gui.widget.ClickableWidget; +import net.minecraft.client.gui.widget.CyclingButtonWidget; +import net.minecraft.client.gui.widget.TextFieldWidget; +import net.minecraft.client.gui.widget.TextWidget; import net.minecraft.item.ItemStack; import net.minecraft.screen.ScreenHandler; import net.minecraft.screen.ScreenTexts; import net.minecraft.text.Style; import net.minecraft.text.Text; -import net.minecraft.util.Formatting; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; @@ -29,11 +30,11 @@ public CustomChestField(TextRenderer textRender, int x, int y, int width, int he super(x, y, width, height, message); this.item = item; var widgets = new ArrayList(); - if(item instanceof NamedItem named) { + if (item instanceof NamedItem named) { int textboxWidth = width; - if(item instanceof Variable var) { + if (item instanceof Variable var) { textboxWidth = textboxWidth - height; - var scopeWidget = new CyclingButtonWidget.Builder(scope -> Text.literal(scope.getShortName()).setStyle(Style.EMPTY.withColor(scope.color))).values(Scope.unsaved, Scope.saved, Scope.local, Scope.line).omitKeyText().build(x+textboxWidth,y,height,height,Text.literal("")); + var scopeWidget = new CyclingButtonWidget.Builder(scope -> Text.literal(scope.getShortName()).setStyle(Style.EMPTY.withColor(scope.color))).values(Scope.unsaved, Scope.saved, Scope.local, Scope.line).omitKeyText().build(x + textboxWidth, y, height, height, Text.literal("")); scopeWidget.setValue(var.getScope()); widgets.add(scopeWidget); } @@ -42,18 +43,18 @@ public CustomChestField(TextRenderer textRender, int x, int y, int width, int he // // widgets.add(new FakeSlot(x+textboxWidth,y,Text.literal("Paramater Data"), handler)); // } - var text = new TextFieldWidget(textRender,x,y,textboxWidth,height,Text.literal("")); + var text = new TextFieldWidget(textRender, x, y, textboxWidth, height, Text.literal("")); text.setMaxLength(10000); text.setText(named.getName()); text.setFocused(false); text.setCursorToStart(false); - widgets.add(0,text); + widgets.add(0, text); } - if(item instanceof GameValue value) { + if (item instanceof GameValue value) { int targetWidth = 60; int textboxWidth = width - targetWidth; - var text = new TextFieldWidget(textRender,x,y,textboxWidth,height,Text.literal("")); + var text = new TextFieldWidget(textRender, x, y, textboxWidth, height, Text.literal("")); text.setMaxLength(10000); text.setText(value.getType()); widgets.add(text); @@ -67,26 +68,26 @@ public CustomChestField(TextRenderer textRender, int x, int y, int width, int he Target.Shooter, Target.Projectile, Target.LastEntity - ).omitKeyText().build(x+textboxWidth,y,targetWidth,height,Text.literal("")); + ).omitKeyText().build(x + textboxWidth, y, targetWidth, height, Text.literal("")); scopeWidget.setValue(value.getTarget()); widgets.add(scopeWidget); } - if(item instanceof Vector vec) { + if (item instanceof Vector vec) { Double[] values = {vec.getX(), vec.getY(), vec.getZ()}; int textboxWidth = width / 3; for (int i = 0; i < 3; i++) { - var field = new NumberFieldWidget(textRender,x + (textboxWidth * i),y,textboxWidth,height,Text.literal("")); + var field = new NumberFieldWidget(textRender, x + (textboxWidth * i), y, textboxWidth, height, Text.literal("")); field.setMaxLength(10); field.setNumber(values[i]); field.setCursorToStart(false); widgets.add(field); } } - if(item instanceof Location loc) { + if (item instanceof Location loc) { Double[] values = {loc.getX(), loc.getY(), loc.getZ(), loc.getPitch(), loc.getYaw()}; int textboxWidth = width / 5; for (int i = 0; i < 5; i++) { - var field = new NumberFieldWidget(textRender,x + (textboxWidth * i),y,textboxWidth,height,Text.literal("")); + var field = new NumberFieldWidget(textRender, x + (textboxWidth * i), y, textboxWidth, height, Text.literal("")); field.setMaxLength(10); field.setNumber(values[i]); field.setCursorToStart(false); @@ -94,41 +95,41 @@ public CustomChestField(TextRenderer textRender, int x, int y, int width, int he widgets.add(field); } } - if(item instanceof Potion pot) { + if (item instanceof Potion pot) { int durationWidth = 45; int potencyWidth = 32; int textboxWidth = width - durationWidth - potencyWidth; - var text = new TextFieldWidget(textRender,x,y,textboxWidth,height,Text.literal("")); + var text = new TextFieldWidget(textRender, x, y, textboxWidth, height, Text.literal("")); text.setText(pot.getPotion()); text.setCursorToStart(false); widgets.add(text); - var potency = new NumberFieldWidget(textRender,x+textboxWidth,y,potencyWidth,height,Text.empty()).integer().min(-255).max(255); + var potency = new NumberFieldWidget(textRender, x + textboxWidth, y, potencyWidth, height, Text.empty()).integer().min(-255).max(255); potency.setNumber(pot.getAmplifier() + 1); potency.setCursorToStart(false); widgets.add(potency); - var duration = new TextFieldWidget(textRender,x+textboxWidth+potencyWidth,y,durationWidth,height,Text.empty()); - duration.setText(pot.duration().replaceAll(" ticks","")); + var duration = new TextFieldWidget(textRender, x + textboxWidth + potencyWidth, y, durationWidth, height, Text.empty()); + duration.setText(pot.duration().replaceAll(" ticks", "")); duration.setCursorToStart(false); widgets.add(duration); } - if(item instanceof Sound sound) { + if (item instanceof Sound sound) { int volumeWidth = 30; int pitchWidth = 30; int textboxWidth = width - volumeWidth - pitchWidth; - var text = new TextFieldWidget(textRender,x,y,textboxWidth,height,Text.literal("")); + var text = new TextFieldWidget(textRender, x, y, textboxWidth, height, Text.literal("")); text.setText(sound.getSound()); text.setCursorToStart(false); widgets.add(text); - var volume = new NumberFieldWidget(textRender,x+textboxWidth,y,volumeWidth,height,Text.empty()).min(0); + var volume = new NumberFieldWidget(textRender, x + textboxWidth, y, volumeWidth, height, Text.empty()).min(0); volume.setNumber(sound.getVolume()); volume.setCursorToStart(false); widgets.add(volume); - var pitch = new NumberFieldWidget(textRender,x+textboxWidth+volumeWidth,y,pitchWidth,height,Text.empty()).min(0).max(2); + var pitch = new NumberFieldWidget(textRender, x + textboxWidth + volumeWidth, y, pitchWidth, height, Text.empty()).min(0).max(2); pitch.setNumber(sound.getPitch()); pitch.setCursorToStart(false); widgets.add(pitch); } - if(item instanceof BlockTag tag) { + if (item instanceof BlockTag tag) { // int slotSize = 18; // int textboxWidth = width - slotSize; // try { @@ -146,44 +147,44 @@ public CustomChestField(TextRenderer textRender, int x, int y, int width, int he // var varItem = new FakeSlot(x + textboxWidth, y, Text.empty(), handler); // if(tag.getVariable() != null) varItem.item = tag.getVariable().toStack(); // widgets.add(varItem); - widgets.add(new TextWidget(x,y,width,height,ScreenTexts.composeGenericOptionText(Text.literal(tag.getTag()),Text.literal(tag.getOption())),textRender).alignCenter()); + widgets.add(new TextWidget(x, y, width, height, ScreenTexts.composeGenericOptionText(Text.literal(tag.getTag()), Text.literal(tag.getOption())), textRender).alignCenter()); } this.widgets = widgets; } private void updateItem() { - if(item instanceof NamedItem named) { - if(widgets.get(0) instanceof TextFieldWidget text) { + if (item instanceof NamedItem named) { + if (widgets.get(0) instanceof TextFieldWidget text) { named.setName(text.getText()); } - if(named instanceof Variable var) { - if(widgets.get(1) instanceof CyclingButtonWidget cycle) { + if (named instanceof Variable var) { + if (widgets.get(1) instanceof CyclingButtonWidget cycle) { var.setScope((Scope) cycle.getValue()); } } } - if(item instanceof GameValue value) { - if(widgets.get(0) instanceof TextFieldWidget text) { + if (item instanceof GameValue value) { + if (widgets.get(0) instanceof TextFieldWidget text) { value.setType(text.getText()); } - if(widgets.get(1) instanceof CyclingButtonWidget cycle) { + if (widgets.get(1) instanceof CyclingButtonWidget cycle) { value.setTarget((Target) cycle.getValue()); } } - if(item instanceof Vector vec) { + if (item instanceof Vector vec) { if (widgets.get(0) instanceof NumberFieldWidget num1 && widgets.get(1) instanceof NumberFieldWidget num2 && widgets.get(2) instanceof NumberFieldWidget num3) vec.setCoords(num1.getNumber(), num2.getNumber(), num3.getNumber()); this.item = (ItemType) vec; } - if(item instanceof Location loc) { - if( - widgets.get(0) instanceof NumberFieldWidget num0 - && widgets.get(1) instanceof NumberFieldWidget num1 - && widgets.get(2) instanceof NumberFieldWidget num2 - && widgets.get(3) instanceof NumberFieldWidget num3 - && widgets.get(4) instanceof NumberFieldWidget num4 + if (item instanceof Location loc) { + if ( + widgets.get(0) instanceof NumberFieldWidget num0 + && widgets.get(1) instanceof NumberFieldWidget num1 + && widgets.get(2) instanceof NumberFieldWidget num2 + && widgets.get(3) instanceof NumberFieldWidget num3 + && widgets.get(4) instanceof NumberFieldWidget num4 ) { loc.setCoords( num0.getNumber(), @@ -195,15 +196,15 @@ private void updateItem() { this.item = (ItemType) loc; } } - if(item instanceof Sound sound) { - if(widgets.get(0) instanceof TextFieldWidget text) sound.setSound(text.getText()); - if(widgets.get(1) instanceof NumberFieldWidget num) sound.setVolume(num.getNumber()); - if(widgets.get(2) instanceof NumberFieldWidget num) sound.setPitch(num.getNumber()); + if (item instanceof Sound sound) { + if (widgets.get(0) instanceof TextFieldWidget text) sound.setSound(text.getText()); + if (widgets.get(1) instanceof NumberFieldWidget num) sound.setVolume(num.getNumber()); + if (widgets.get(2) instanceof NumberFieldWidget num) sound.setPitch(num.getNumber()); } - if(item instanceof Potion pot) { - if(widgets.get(0) instanceof TextFieldWidget text) pot.setPotion(text.getText()); - if(widgets.get(1) instanceof NumberFieldWidget num) pot.setAmplifier(num.getInt() - 1); - if(widgets.get(2) instanceof TextFieldWidget text) { + if (item instanceof Potion pot) { + if (widgets.get(0) instanceof TextFieldWidget text) pot.setPotion(text.getText()); + if (widgets.get(1) instanceof NumberFieldWidget num) pot.setAmplifier(num.getInt() - 1); + if (widgets.get(2) instanceof TextFieldWidget text) { String value = text.getText(); try { pot.setDuration(Integer.parseInt(value)); @@ -221,28 +222,27 @@ private void updateItem() { @Override public void setFocused(boolean focused) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget click) click.setFocused(focused); + for (var widget : widgets) { + if (widget instanceof ClickableWidget click) click.setFocused(focused); } super.setFocused(focused); } @Override protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) { - for (var widget: widgets) { + for (var widget : widgets) { widget.render(context, mouseX, mouseY, delta); } } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget clickable) { - if(clickable.isMouseOver(mouseX,mouseY)) { + for (var widget : widgets) { + if (widget instanceof ClickableWidget clickable) { + if (clickable.isMouseOver(mouseX, mouseY)) { clickable.setFocused(true); clickable.mouseClicked(mouseX, mouseY, button); - } - else clickable.setFocused(false); + } else clickable.setFocused(false); } } updateItem(); @@ -261,8 +261,8 @@ public void mouseMoved(double mouseX, double mouseY) { @Override public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget click && click.isMouseOver(mouseX,mouseY) && click.mouseScrolled(mouseX,mouseY,horizontalAmount,verticalAmount)) { + for (var widget : widgets) { + if (widget instanceof ClickableWidget click && click.isMouseOver(mouseX, mouseY) && click.mouseScrolled(mouseX, mouseY, horizontalAmount, verticalAmount)) { updateItem(); return true; } @@ -272,9 +272,9 @@ public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmou @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget click && click.isFocused()) { - return click.keyPressed(keyCode,scanCode,modifiers); + for (var widget : widgets) { + if (widget instanceof ClickableWidget click && click.isFocused()) { + return click.keyPressed(keyCode, scanCode, modifiers); } } return super.keyPressed(keyCode, scanCode, modifiers); @@ -282,10 +282,10 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { @Override public boolean keyReleased(int keyCode, int scanCode, int modifiers) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget click && click.isFocused()) { + for (var widget : widgets) { + if (widget instanceof ClickableWidget click && click.isFocused()) { updateItem(); - return click.keyReleased(keyCode,scanCode,modifiers); + return click.keyReleased(keyCode, scanCode, modifiers); } } return super.keyReleased(keyCode, scanCode, modifiers); @@ -293,10 +293,10 @@ public boolean keyReleased(int keyCode, int scanCode, int modifiers) { @Override public boolean charTyped(char chr, int modifiers) { - for (var widget: widgets) { - if(widget instanceof ClickableWidget click && click.isFocused()) { + for (var widget : widgets) { + if (widget instanceof ClickableWidget click && click.isFocused()) { updateItem(); - return click.charTyped(chr,modifiers); + return click.charTyped(chr, modifiers); } } return super.charTyped(chr, modifiers); diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestHandler.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestHandler.java index 86c1752b..7385e0a2 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestHandler.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestHandler.java @@ -13,15 +13,12 @@ import org.jetbrains.annotations.NotNull; public class CustomChestHandler extends ScreenHandler { - private final Inventory inventory; - private static final int Size = 9*3; + private static final int Size = 9 * 3; public final CustomChestNumbers numbers = CustomChestNumbers.getSize(); + private final Inventory inventory; public @NotNull Callback callback = (int slot, int revision, ItemStack stack) -> { }; - public interface Callback { - void run(int slot, int revision, ItemStack stack); - } public CustomChestHandler(int syncId) { this(syncId, CodeClient.MC.player.getInventory(), new SimpleInventory(Size)); @@ -33,8 +30,8 @@ public CustomChestHandler(int syncId, PlayerInventory playerInventory, Inventory checkSize(inventory, Size); inventory.onOpen(playerInventory.player); - for(int i = 0; i < Size; ++i) { - Slot slot = new Slot(inventory,i,-10000,-10000); + for (int i = 0; i < Size; ++i) { + Slot slot = new Slot(inventory, i, -10000, -10000); this.addSlot(slot); } @@ -44,7 +41,7 @@ public CustomChestHandler(int syncId, PlayerInventory playerInventory, Inventory @Override public void setStackInSlot(int slot, int revision, ItemStack stack) { super.setStackInSlot(slot, revision, stack); - this.callback.run(slot,revision,stack); + this.callback.run(slot, revision, stack); } @Override @@ -53,13 +50,13 @@ public Slot getSlot(int index) { } private void addPlayerInventory(PlayerInventory playerInventory) { - for(int row = 0; row < 3; ++row) { - for(int column = 0; column < 9; ++column) { + for (int row = 0; row < 3; ++row) { + for (int column = 0; column < 9; ++column) { this.addSlot(new Slot(playerInventory, column + row * 9 + 9, 1 + numbers.INVENTORY_X + column * 18, 1 + numbers.INVENTORY_Y + row * 18)); } } - for(int slot = 0; slot < 9; ++slot) { + for (int slot = 0; slot < 9; ++slot) { this.addSlot(new Slot(playerInventory, slot, numbers.INVENTORY_X + 1 + slot * 18, numbers.INVENTORY_Y + 59)); } } @@ -93,4 +90,8 @@ public ItemStack quickMove(PlayerEntity player, int slotIndex) { public boolean canUse(PlayerEntity player) { return false; } + + public interface Callback { + void run(int slot, int revision, ItemStack stack); + } } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestMenu.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestMenu.java index 272ecab4..d9503215 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestMenu.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestMenu.java @@ -32,9 +32,9 @@ public class CustomChestMenu extends HandledScreen implements ScreenHandlerProvider { private final CustomChestNumbers Size; - private double scroll = 0; - private final HashMap widgets = new HashMap<>(); + private final HashMap widgets = new HashMap<>(); private final ArrayList varItems = new ArrayList<>(); + private double scroll = 0; private boolean update = true; public CustomChestMenu(CustomChestHandler handler, PlayerInventory inventory, Text title) { @@ -63,7 +63,7 @@ protected void init() { @Override protected void handledScreenTick() { - if(update) { + if (update) { update((int) scroll); update = false; } @@ -85,28 +85,28 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta) { var slot = subList.get(i); final int x = Size.SLOT_X + 1; final int y = i * 18 + Size.SLOT_Y + 1; - if(i + scroll < 27) { - context.drawItem(slot.getStack(),x,y); - context.drawItemInSlot(textRenderer,slot.getStack(),x,y); + if (i + scroll < 27) { + context.drawItem(slot.getStack(), x, y); + context.drawItemInSlot(textRenderer, slot.getStack(), x, y); int relX = mouseX - this.x; int relY = mouseY - this.y; - if( - relX > x - && relX < x+18 - && relY > y - && relY < y+18 + if ( + relX > x + && relX < x + 18 + && relY > y + && relY < y + 18 ) { drawSlotHighlight(context, x, y, -10); focusedSlot = slot; } - } - else { - context.drawTexture(Size.TEXTURE, x-1,y-1,Size.DISABLED_X,0,18,18, Size.TEXTURE_WIDTH, Size.TEXTURE_HEIGHT); + } else { + context.drawTexture(Size.TEXTURE, x - 1, y - 1, Size.DISABLED_X, 0, 18, 18, Size.TEXTURE_WIDTH, Size.TEXTURE_HEIGHT); } } - if(focusedSlot != null) { - if(focusedSlot.hasStack()) context.drawItemTooltip(textRenderer,focusedSlot.getStack(),mouseX - this.x,mouseY - this.y); + if (focusedSlot != null) { + if (focusedSlot.hasStack()) + context.drawItemTooltip(textRenderer, focusedSlot.getStack(), mouseX - this.x, mouseY - this.y); } context.getMatrices().pop(); } @@ -124,31 +124,31 @@ private void update(int previousScroll) { List subList = this.getScreenHandler().slots.subList((int) scroll, (int) scroll + Size.SLOTS); for (int i = 0; i < subList.size(); i++) { Slot slot = subList.get(i); - if(!slot.hasStack()) continue; + if (!slot.hasStack()) continue; ItemStack stack = slot.getStack(); final int x = Size.WIDGET_X; final int y = i * 18 + Size.SLOT_Y; VarItem varItem = (VarItems.parse(stack)); varItems.add(varItem); - if(i >= Size.WIDGETS) continue; - if(varItem != null) { + if (i >= Size.WIDGETS) continue; + if (varItem != null) { // TextFieldWidget widget = new TextFieldWidget(textRenderer,x,y,Size.WIDGET_WIDTH,18,Text.of(named.getName())); // widget.setMaxLength(10_000); // widget.setText(named.getName()); // widget.setFocused(Objects.equals(i,focused)); var widget = new CustomChestField<>(textRenderer, x, y, Size.WIDGET_WIDTH, 18, Text.of(varItem.id), stack, varItem, this.handler); - widgets.put(i,widget); + widgets.put(i, widget); varItems.add(varItem); continue; } - widgets.put(i,new TextWidget(x + 3,y,Size.WIDGET_WIDTH,16,stack.getName(),textRenderer).alignLeft()); + widgets.put(i, new TextWidget(x + 3, y, Size.WIDGET_WIDTH, 16, stack.getName(), textRenderer).alignLeft()); } } @Override - public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { - for (var widget: widgets.entrySet()) { + public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) { + for (var widget : widgets.entrySet()) { if (widget.getValue() instanceof ClickableWidget click && click.isMouseOver(mouseX - this.x, mouseY - this.y) && click.mouseScrolled(mouseX - this.x, mouseY - this.y, horizontalAmount, verticalAmount)) { @@ -164,24 +164,24 @@ public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmou @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { - List subList = this.getScreenHandler().slots.subList((int) scroll, Math.min((int) scroll + Size.SLOTS,27)); + List subList = this.getScreenHandler().slots.subList((int) scroll, Math.min((int) scroll + Size.SLOTS, 27)); for (int i = 0; i < subList.size(); i++) { var slot = subList.get(i); final int x = 8; final int y = i * 18 - 11 + 25; double relX = mouseX - this.x; double relY = mouseY - this.y; - if( + if ( relX > x - && relX < x+18 + && relX < x + 18 && relY > y - && relY < y+18 + && relY < y + 18 ) { - if(button == 2) { + if (button == 2) { this.onMouseClick(slot, slot.id, button, SlotActionType.CLONE); return true; } - if(hasShiftDown()) { + if (hasShiftDown()) { this.onMouseClick(slot, slot.id, button, SlotActionType.QUICK_MOVE); return true; } @@ -194,7 +194,7 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { if (entry.getValue() instanceof ClickableWidget clickable) { boolean mouseOver = clickable.isMouseOver(mouseX - this.x, mouseY - this.y); clickable.setFocused(mouseOver); - if(mouseOver && clickable.mouseClicked(mouseX - this.x,mouseY - this.y,button)) { + if (mouseOver && clickable.mouseClicked(mouseX - this.x, mouseY - this.y, button)) { // updateItem(entry.getKey()); returnValue = true; } @@ -211,28 +211,28 @@ private void updateItems() { } private void updateItem(int scrollRelativeSlot) { - if(CodeClient.MC.getNetworkHandler() == null) return; - if(scrollRelativeSlot + scroll > 27) return; + if (CodeClient.MC.getNetworkHandler() == null) return; + if (scrollRelativeSlot + scroll > 27) return; Slot slot = this.getScreenHandler().slots.subList((int) scroll, (int) scroll + Size.WIDGETS).get(scrollRelativeSlot); - if(scrollRelativeSlot > widgets.size()) return; + if (scrollRelativeSlot > widgets.size()) return; Widget widget = widgets.get(scrollRelativeSlot); - if(widget instanceof CustomChestField field) { + if (widget instanceof CustomChestField field) { VarItem item = field.item; - if(item instanceof BlockTag) { + if (item instanceof BlockTag) { Int2ObjectMap int2ObjectMap = new Int2ObjectOpenHashMap<>(); CodeClient.MC.getNetworkHandler().sendPacket(new ClickSlotC2SPacket(handler.syncId, handler.nextRevision(), slot.getIndex(), 0, SlotActionType.PICKUP, item.toStack(), int2ObjectMap)); } else { - super.onMouseClick(slot,slot.id,0,SlotActionType.SWAP); + super.onMouseClick(slot, slot.id, 0, SlotActionType.SWAP); CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(36, item.toStack())); - super.onMouseClick(slot,slot.id,0,SlotActionType.SWAP); - super.onMouseClick(slot,54,0,SlotActionType.QUICK_CRAFT); + super.onMouseClick(slot, slot.id, 0, SlotActionType.SWAP); + super.onMouseClick(slot, 54, 0, SlotActionType.QUICK_CRAFT); } } } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if(keyCode == GLFW.GLFW_KEY_ESCAPE) { + if (keyCode == GLFW.GLFW_KEY_ESCAPE) { for (int i = 0; i < widgets.size(); i++) { Widget widget = widgets.get(i); if (widget instanceof ClickableWidget clickable) { @@ -244,7 +244,7 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { } } } - if(keyCode <= GLFW.GLFW_KEY_DOWN || keyCode >= GLFW.GLFW_KEY_PAGE_DOWN) { + if (keyCode <= GLFW.GLFW_KEY_DOWN || keyCode >= GLFW.GLFW_KEY_PAGE_DOWN) { for (int i = 0; i < widgets.size(); i++) { Widget widget = widgets.get(i); if (widget instanceof ClickableWidget clickable) { @@ -256,34 +256,34 @@ public boolean keyPressed(int keyCode, int scanCode, int modifiers) { } } } - boolean up = keyCode == GLFW.GLFW_KEY_UP || CodeClient.MC.options.forwardKey.matchesKey(keyCode,scanCode); - boolean down = keyCode == GLFW.GLFW_KEY_DOWN || CodeClient.MC.options.backKey.matchesKey(keyCode,scanCode); + boolean up = keyCode == GLFW.GLFW_KEY_UP || CodeClient.MC.options.forwardKey.matchesKey(keyCode, scanCode); + boolean down = keyCode == GLFW.GLFW_KEY_DOWN || CodeClient.MC.options.backKey.matchesKey(keyCode, scanCode); boolean pageUp = keyCode == GLFW.GLFW_KEY_PAGE_UP || (up && hasShiftDown()); boolean pageDown = keyCode == GLFW.GLFW_KEY_PAGE_DOWN || (down && hasShiftDown()); boolean start = keyCode == GLFW.GLFW_KEY_HOME || (up && hasAltDown() && !pageUp); boolean end = keyCode == GLFW.GLFW_KEY_END || (down && hasAltDown() && !pageDown); int prev = (int) scroll; - if(pageDown) { + if (pageDown) { scroll = Math.min(27 - Size.WIDGETS, scroll + Size.WIDGETS); update(prev); } - if(pageUp) { + if (pageUp) { scroll = Math.max(0, scroll - Size.WIDGETS); update(prev); } - if(start) { + if (start) { scroll = 0; update(prev); } - if(end) { + if (end) { scroll = 27 - Size.WIDGETS; update(prev); } - if(up) { - scroll = Math.max(0,scroll - 1); + if (up) { + scroll = Math.max(0, scroll - 1); update(prev); } - if(down) { + if (down) { scroll = Math.min(27 - Size.WIDGETS, scroll + 1); update(prev); } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestNumbers.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestNumbers.java index f464e0f2..92852862 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestNumbers.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/CustomChestNumbers.java @@ -5,6 +5,46 @@ import net.minecraft.util.Identifier; public class CustomChestNumbers { + public static final CustomChestNumbers SMALL = new CustomChestNumbers( + new Identifier(CodeClient.MOD_ID, "textures/gui/container/custom_chest/background.png"), + 176, + 216, + 202, + 229, + 6, + 6, + 128, + 25, + 12, + 15, + 156, + 13, + 108, + 7, + 13, + 7, + 133, + -1); + public static final CustomChestNumbers LARGE = new CustomChestNumbers( + new Identifier(CodeClient.MOD_ID, "textures/gui/container/custom_chest/background_big.png"), + 198, + 294, + 228, + 294, + 15, + 10, + 156, + 26, + 6, + 27, + 184, + 18, + 178, + 7, + 17, + 29, + 211, + 210); public final Identifier TEXTURE; public final int MENU_WIDTH; public final int MENU_HEIGHT; @@ -62,46 +102,4 @@ private CustomChestNumbers(Identifier texture, int menuWidth, int menuHeight, in public static CustomChestNumbers getSize() { return Config.getConfig().CustomCodeChest.size; } - - public static final CustomChestNumbers SMALL = new CustomChestNumbers( - new Identifier(CodeClient.MOD_ID,"textures/gui/container/custom_chest/background.png"), - 176, - 216, - 202, - 229, - 6, - 6, - 128, - 25, - 12, - 15, - 156, - 13, - 108, - 7, - 13, - 7, - 133, - -1); - - public static final CustomChestNumbers LARGE = new CustomChestNumbers( - new Identifier(CodeClient.MOD_ID,"textures/gui/container/custom_chest/background_big.png"), - 198, - 294, - 228, - 294, - 15, - 10, - 156, - 26, - 6, - 27, - 184, - 18, - 178, - 7, - 17, - 29, - 211, - 210); } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/FakeSlot.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/FakeSlot.java index b09ab77d..96de70db 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/FakeSlot.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/FakeSlot.java @@ -1,15 +1,12 @@ package dev.dfonline.codeclient.dev.menu.customchest; import dev.dfonline.codeclient.CodeClient; -import net.minecraft.client.font.TextRenderer; import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.ingame.HandledScreen; -import net.minecraft.client.gui.screen.ingame.HandledScreens; import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.ClickableWidget; -import net.minecraft.client.item.TooltipContext; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.screen.ScreenHandler; @@ -19,7 +16,7 @@ import org.jetbrains.annotations.Nullable; public class FakeSlot extends ClickableWidget { - public static final Identifier TEXTURE = new Identifier("minecraft","textures/gui/sprites/container/slot.png"); + public static final Identifier TEXTURE = new Identifier("minecraft", "textures/gui/sprites/container/slot.png"); private final ScreenHandler handler; public boolean disabled = false; @NotNull @@ -33,17 +30,17 @@ public FakeSlot(int x, int y, Text message, ScreenHandler handler) { @Override protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) { - context.drawTexture(TEXTURE,this.getX(),this.getY(),0,0,this.width,this.height,18,18); - context.drawItem(item,this.getX() + 1,this.getY() + 1); - if(this.isMouseOver(mouseX,mouseY)) { - HandledScreen.drawSlotHighlight(context,this.getX() + 1,this.getY() + 1,-1000); - context.drawItemTooltip(CodeClient.MC.textRenderer,item,mouseX,mouseY); + context.drawTexture(TEXTURE, this.getX(), this.getY(), 0, 0, this.width, this.height, 18, 18); + context.drawItem(item, this.getX() + 1, this.getY() + 1); + if (this.isMouseOver(mouseX, mouseY)) { + HandledScreen.drawSlotHighlight(context, this.getX() + 1, this.getY() + 1, -1000); + context.drawItemTooltip(CodeClient.MC.textRenderer, item, mouseX, mouseY); } } @Override public boolean mouseClicked(double mouseX, double mouseY, int button) { - if(this.isMouseOver(mouseX,mouseY) && ((!this.item.isEmpty()) || (!this.handler.getCursorStack().isEmpty()))) { + if (this.isMouseOver(mouseX, mouseY) && ((!this.item.isEmpty()) || (!this.handler.getCursorStack().isEmpty()))) { this.handler.disableSyncing(); var swap = this.item.copy(); this.item = this.handler.getCursorStack().copyWithCount(1); @@ -60,8 +57,8 @@ public Tooltip getTooltip() { var data = Screen.getTooltipFromItem(CodeClient.MC, item); var text = Text.empty(); boolean first = true; - for (var line: data) { - if(first) first = false; + for (var line : data) { + if (first) first = false; else text.append(Text.literal("\n")); text.append(line); } diff --git a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/NumberFieldWidget.java b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/NumberFieldWidget.java index 58941ebd..346d1ac2 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/NumberFieldWidget.java +++ b/src/main/java/dev/dfonline/codeclient/dev/menu/customchest/NumberFieldWidget.java @@ -7,37 +7,40 @@ import org.jetbrains.annotations.Nullable; public class NumberFieldWidget extends TextFieldWidget { - private double number = 0; - private @RegExp String regex = "(? 0) { + if (timeOut > 0) { timeOut--; return; } - if(CodeClient.MC.currentScreen != null) return; - if(CodeClient.MC.world == null) return; - if(!Config.getConfig().ChestPeeker) return; - if(CodeClient.location instanceof Dev dev) { - if(CodeClient.MC.crosshairTarget instanceof BlockHitResult block) { + if (CodeClient.MC.currentScreen != null) return; + if (CodeClient.MC.world == null) return; + if (!Config.getConfig().ChestPeeker) return; + if (CodeClient.location instanceof Dev dev) { + if (CodeClient.MC.crosshairTarget instanceof BlockHitResult block) { BlockPos pos = block.getBlockPos(); - if(pos.equals(currentBlock)) return; - if(currentBlock == null && items == null) { + if (pos.equals(currentBlock)) return; + if (currentBlock == null && items == null) { if (!dev.isInDev(pos)) { return; } @@ -69,7 +69,7 @@ public static void tick() { bet.putInt("z", pos.getZ()); item.setSubNbt("BlockEntityTag", bet); item.setCustomName(Text.literal("CodeClient chest peeker internal")); - CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(1,ItemStack.EMPTY)); + CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(1, ItemStack.EMPTY)); CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(1, item)); return; } @@ -83,28 +83,28 @@ public static void tick() { * @return true to cancel packet. */ public static boolean handlePacket(Packet packet) { - if(CodeClient.MC.currentScreen != null) return false; - if(CodeClient.MC.getNetworkHandler() == null) return false; - if(!Config.getConfig().ChestPeeker) return false; - if(CodeClient.location instanceof Dev) { - if(packet instanceof BlockEventS2CPacket block) { - if(!Objects.equals(currentBlock, block.getPos())) return false; - if(block.getType() != 1) return false; - if(block.getData() != 0) return false; + if (CodeClient.MC.currentScreen != null) return false; + if (CodeClient.MC.getNetworkHandler() == null) return false; + if (!Config.getConfig().ChestPeeker) return false; + if (CodeClient.location instanceof Dev) { + if (packet instanceof BlockEventS2CPacket block) { + if (!Objects.equals(currentBlock, block.getPos())) return false; + if (block.getType() != 1) return false; + if (block.getData() != 0) return false; invalidate(); } - if(packet instanceof ScreenHandlerSlotUpdateS2CPacket slot) { + if (packet instanceof ScreenHandlerSlotUpdateS2CPacket slot) { var nbt = slot.getStack().getNbt(); - if(nbt == null) return false; + if (nbt == null) return false; var display = nbt.getCompound("display"); - if(display == null || !display.contains("Name",NbtElement.STRING_TYPE)) return false; + if (display == null || !display.contains("Name", NbtElement.STRING_TYPE)) return false; String name = display.getString("Name"); - if(Objects.equals(name, ") {\"text\":\"CodeClient chest peeker internal\"}")) return false; + if (Objects.equals(name, ") {\"text\":\"CodeClient chest peeker internal\"}")) return false; var bet = nbt.getCompound("BlockEntityTag"); - if(bet == null) return false; - if(!Objects.equals(bet.getString("id"), "minecraft:chest")) return false; - if(currentBlock != null) items = bet.getList("Items", NbtElement.COMPOUND_TYPE); - CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(slot.getSlot(),ItemStack.EMPTY)); + if (bet == null) return false; + if (!Objects.equals(bet.getString("id"), "minecraft:chest")) return false; + if (currentBlock != null) items = bet.getList("Items", NbtElement.COMPOUND_TYPE); + CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(slot.getSlot(), ItemStack.EMPTY)); shouldClearChest = false; return true; } @@ -113,13 +113,12 @@ public static boolean handlePacket(Packet packet) } public static List getOverlayText() { - if(!Config.getConfig().ChestPeeker) return null; + if (!Config.getConfig().ChestPeeker) return null; if (CodeClient.location instanceof Dev && currentBlock != null && items != null) { ArrayList texts = new ArrayList<>(); - if(items.isEmpty()) { + if (items.isEmpty()) { texts.add(Text.translatable("codeclient.peeker.empty").formatted(Formatting.GOLD)); - } - else { + } else { texts.add(Text.translatable("codeclient.peeker.contents").formatted(Formatting.GOLD)); for (NbtElement itemData : items) { if (itemData instanceof NbtCompound compound) { @@ -127,69 +126,70 @@ public static List getOverlayText() { item.setCount(compound.getInt("Count")); NbtCompound tag = compound.getCompound("tag"); item.setNbt(tag); - NbtList lore = tag.getCompound("display").getList("Lore",NbtElement.STRING_TYPE); + NbtList lore = tag.getCompound("display").getList("Lore", NbtElement.STRING_TYPE); MutableText text = Text.empty(); text.append(Text.literal(" • ").formatted(Formatting.DARK_GRAY)); String varItem = tag.getCompound("PublicBukkitValues").getString("hypercube:varitem"); - if(Objects.equals(varItem, "")) { + if (Objects.equals(varItem, "")) { text.append(compound.getInt("Count") + "x "); text.append(item.getName()); - } - else { + } else { try { - JsonObject object = JsonParser.parseString(varItem).getAsJsonObject(); - Type type = Type.valueOf(object.get("id").getAsString()); - JsonObject data = object.get("data").getAsJsonObject(); - // JsonArray lore = data.get("display").getAsJsonObject().get("Lore").getAsJsonArray(); - text.append(Text.literal(type.name.toUpperCase()).fillStyle(Style.EMPTY.withColor(type.color)).append(" ")); - if (type == Type.var) { - Scope scope = Scope.valueOf(data.get("scope").getAsString()); - text.append(scope.getShortName()).fillStyle(Style.EMPTY.withColor(scope.color)).append(" "); - } - if (type == Type.num || type == Type.txt || type == Type.comp || type == Type.var || type == Type.g_val || type == Type.pn_el) { - text.append(item.getName()); - } - if (type == Type.loc) { - JsonObject loc = data.get("loc").getAsJsonObject(); - text.append("[%.2f, %.2f, %.2f, %.2f, %.2f]".formatted( - loc.get("x").getAsFloat(), - loc.get("y").getAsFloat(), - loc.get("z").getAsFloat(), - loc.get("pitch").getAsFloat(), - loc.get("yaw").getAsFloat())); - } - if (type == Type.vec) { - text.append(Text.literal("<%.2f, %.2f, %.2f>".formatted( - data.get("x").getAsFloat(), - data.get("y").getAsFloat(), - data.get("z").getAsFloat()) - ).fillStyle(Style.EMPTY.withColor(Type.vec.color))); - } - if (type == Type.snd) { - text.append(Text.Serialization.fromJson(lore.getString(0))); - text.append(Text.literal(" P: ").formatted(Formatting.GRAY)); - text.append(Text.literal("%.1f".formatted(data.get("pitch").getAsFloat()))); - text.append(Text.literal(" V: ").formatted(Formatting.GRAY)); - text.append(Text.literal("%.1f".formatted(data.get("vol").getAsFloat()))); - } - if (type == Type.part) { - text.append(Text.literal("%dx ".formatted(data.get("cluster").getAsJsonObject().get("amount").getAsInt()))); - text.append(Text.Serialization.fromJson(lore.getString(0))); - } - if (type == Type.pot) { - text.append(Text.Serialization.fromJson(lore.getString(0))); - text.append(Text.literal(" %d ".formatted(data.get("amp").getAsInt() + 1))); - int dur = data.get("dur").getAsInt(); - text.append(dur >= 1000000 ? "Infinite" : dur % 20 == 0 ? "%d:%02d".formatted((dur / 1200), (dur / 20) % 60) : (dur + "ticks")); - } - if (type == Type.bl_tag) { - text.append(Text.literal(data.get("tag").getAsString()).formatted(Formatting.YELLOW)); - text.append(Text.literal(" » ").formatted(Formatting.DARK_AQUA)); - text.append(Text.literal(data.get("option").getAsString()).formatted(Formatting.AQUA)); - } - if (type == Type.hint) continue; - } catch (Exception ignored) {continue;} + JsonObject object = JsonParser.parseString(varItem).getAsJsonObject(); + Type type = Type.valueOf(object.get("id").getAsString()); + JsonObject data = object.get("data").getAsJsonObject(); + // JsonArray lore = data.get("display").getAsJsonObject().get("Lore").getAsJsonArray(); + text.append(Text.literal(type.name.toUpperCase()).fillStyle(Style.EMPTY.withColor(type.color)).append(" ")); + if (type == Type.var) { + Scope scope = Scope.valueOf(data.get("scope").getAsString()); + text.append(scope.getShortName()).fillStyle(Style.EMPTY.withColor(scope.color)).append(" "); + } + if (type == Type.num || type == Type.txt || type == Type.comp || type == Type.var || type == Type.g_val || type == Type.pn_el) { + text.append(item.getName()); + } + if (type == Type.loc) { + JsonObject loc = data.get("loc").getAsJsonObject(); + text.append("[%.2f, %.2f, %.2f, %.2f, %.2f]".formatted( + loc.get("x").getAsFloat(), + loc.get("y").getAsFloat(), + loc.get("z").getAsFloat(), + loc.get("pitch").getAsFloat(), + loc.get("yaw").getAsFloat())); + } + if (type == Type.vec) { + text.append(Text.literal("<%.2f, %.2f, %.2f>".formatted( + data.get("x").getAsFloat(), + data.get("y").getAsFloat(), + data.get("z").getAsFloat()) + ).fillStyle(Style.EMPTY.withColor(Type.vec.color))); + } + if (type == Type.snd) { + text.append(Text.Serialization.fromJson(lore.getString(0))); + text.append(Text.literal(" P: ").formatted(Formatting.GRAY)); + text.append(Text.literal("%.1f".formatted(data.get("pitch").getAsFloat()))); + text.append(Text.literal(" V: ").formatted(Formatting.GRAY)); + text.append(Text.literal("%.1f".formatted(data.get("vol").getAsFloat()))); + } + if (type == Type.part) { + text.append(Text.literal("%dx ".formatted(data.get("cluster").getAsJsonObject().get("amount").getAsInt()))); + text.append(Text.Serialization.fromJson(lore.getString(0))); + } + if (type == Type.pot) { + text.append(Text.Serialization.fromJson(lore.getString(0))); + text.append(Text.literal(" %d ".formatted(data.get("amp").getAsInt() + 1))); + int dur = data.get("dur").getAsInt(); + text.append(dur >= 1000000 ? "Infinite" : dur % 20 == 0 ? "%d:%02d".formatted((dur / 1200), (dur / 20) % 60) : (dur + "ticks")); + } + if (type == Type.bl_tag) { + text.append(Text.literal(data.get("tag").getAsString()).formatted(Formatting.YELLOW)); + text.append(Text.literal(" » ").formatted(Formatting.DARK_AQUA)); + text.append(Text.literal(data.get("option").getAsString()).formatted(Formatting.AQUA)); + } + if (type == Type.hint) continue; + } catch (Exception ignored) { + continue; + } } texts.add(text); } @@ -218,16 +218,18 @@ enum Type { pot("pot", TextColor.fromRgb(0xff557f)), var("var", Formatting.YELLOW), g_val("val", TextColor.fromRgb(0xffd47f)), - pn_el("param",TextColor.fromRgb(0xaaffaa)), + pn_el("param", TextColor.fromRgb(0xaaffaa)), bl_tag("tag", Formatting.YELLOW), hint("hint", TextColor.fromRgb(0xaaff55)); public final String name; public final TextColor color; + Type(String name, TextColor color) { this.name = name; this.color = color; } + Type(String name, Formatting color) { this.name = name; this.color = TextColor.fromFormatting(color); diff --git a/src/main/java/dev/dfonline/codeclient/dev/overlay/SignPeeker.java b/src/main/java/dev/dfonline/codeclient/dev/overlay/SignPeeker.java index 6a191301..6ad13c10 100644 --- a/src/main/java/dev/dfonline/codeclient/dev/overlay/SignPeeker.java +++ b/src/main/java/dev/dfonline/codeclient/dev/overlay/SignPeeker.java @@ -16,7 +16,7 @@ public class SignPeeker { public static List getOverlayText() { if (!Config.getConfig().SignPeeker) return null; - if(CodeClient.location instanceof Dev dev) { + if (CodeClient.location instanceof Dev dev) { if (CodeClient.MC.crosshairTarget instanceof BlockHitResult block) { BlockPos pos = InteractionManager.isBlockBreakable(block.getBlockPos()); if (pos == null || (!dev.isInDev(pos)) || CodeClient.MC.world == null) return null; diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/Target.java b/src/main/java/dev/dfonline/codeclient/hypercube/Target.java index 81293420..2e4c8972 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/Target.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/Target.java @@ -17,6 +17,7 @@ public enum Target { public final TextColor color; public final boolean onActions; public final boolean onGameValue; + Target(Formatting color, boolean onActions, boolean onGameValue) { this.color = TextColor.fromFormatting(color); this.onActions = onActions; diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Action.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Action.java index 9ab25496..a7d0dc27 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Action.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Action.java @@ -10,14 +10,11 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtString; -import net.minecraft.registry.Registries; -import net.minecraft.util.Identifier; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Locale; public class Action implements Searchable { public String name; @@ -29,11 +26,10 @@ public class Action implements Searchable { public CodeBlock getCodeBlock() { try { - for (CodeBlock codeBlock: ActionDump.getActionDump().codeblocks) { - if(codeblockName.equals(codeBlock.name)) return codeBlock; + for (CodeBlock codeBlock : ActionDump.getActionDump().codeblocks) { + if (codeblockName.equals(codeBlock.name)) return codeBlock; } - } - catch (IOException exception) { + } catch (IOException exception) { CodeClient.LOGGER.error(exception.toString()); } return null; @@ -43,7 +39,7 @@ public CodeBlock getCodeBlock() { public List getTerms() { ArrayList terms = new ArrayList<>(Arrays.stream(aliases).toList()); terms.add(name); - terms.add(icon.name.replace("§.","")); + terms.add(icon.name.replace("§.", "")); return terms; } @@ -66,32 +62,33 @@ public ItemStack getItem() { boolean repeat = codeBlock.identifier.equals("repeat"); boolean hasBrackets = codeBlock.identifier.contains("if") || repeat || codeBlock.identifier.equals("else"); JsonObject action = new JsonObject(); - action.addProperty("id","block"); + action.addProperty("id", "block"); action.addProperty("block", codeBlock.identifier); action.addProperty("action", name); JsonObject args = new JsonObject(); var items = new JsonArray(); for (var tag : this.tags) { var defaultOption = Arrays.stream(tag.options).filter(tagOption -> tagOption.name.equals(tag.defaultOption)).findFirst(); - if(defaultOption.isPresent()) { - var blockTag = new BlockTag(defaultOption.get().icon.material.toLowerCase(),tag.defaultOption,tag.name,name,getCodeBlock().identifier); - items.add(new Argument(blockTag,tag.slot).toJsonObject()); + if (defaultOption.isPresent()) { + var blockTag = new BlockTag(defaultOption.get().icon.material.toLowerCase(), tag.defaultOption, tag.name, name, getCodeBlock().identifier); + items.add(new Argument(blockTag, tag.slot).toJsonObject()); } } - args.add("items",items); - action.add("args",args); + args.add("items", items); + action.add("args", args); blocks.add(action); if (hasBrackets) { blocks.add(new Bracket(false, repeat).toJsonObject()); blocks.add(new Bracket(true, repeat).toJsonObject()); } - template.add("blocks",blocks); + template.add("blocks", blocks); try { CodeTemplateData.addProperty("code", Utility.compileTemplate(template.toString())); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } PublicBukkitValues.put("hypercube:codetemplatedata", NbtString.of(String.valueOf(CodeTemplateData))); - nbt.put("PublicBukkitValues",PublicBukkitValues); + nbt.put("PublicBukkitValues", PublicBukkitValues); item.setNbt(nbt); return item; } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/ActionDump.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/ActionDump.java index 0306783f..fa0e2595 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/ActionDump.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/ActionDump.java @@ -17,8 +17,8 @@ public class ActionDump { public static ActionDump getActionDump() throws IOException { - if(instance == null) { - instance = CodeClient.gson.fromJson(FileManager.readFile("actiondump.json"),ActionDump.class); + if (instance == null) { + instance = CodeClient.gson.fromJson(FileManager.readFile("actiondump.json"), ActionDump.class); } return instance; } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Argument.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Argument.java index e9fa6689..2ce1e917 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Argument.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Argument.java @@ -1,9 +1,5 @@ package dev.dfonline.codeclient.hypercube.actiondump; -import net.minecraft.text.Text; -import net.minecraft.text.TextColor; -import net.minecraft.util.Formatting; - public class Argument { public String type; public boolean plural; diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/GameValue.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/GameValue.java index ede91849..d5e68255 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/GameValue.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/GameValue.java @@ -20,8 +20,8 @@ public List getTerms() { public ItemStack getItem() { JsonObject data = new JsonObject(); - data.addProperty("type",icon.getCleanName()); - data.addProperty("target","Default"); + data.addProperty("type", icon.getCleanName()); + data.addProperty("target", "Default"); return super.getItem("g_val", data); } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Icon.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Icon.java index 95962fae..67344f19 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Icon.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Icon.java @@ -2,7 +2,10 @@ import dev.dfonline.codeclient.Utility; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.*; +import net.minecraft.nbt.NbtCompound; +import net.minecraft.nbt.NbtInt; +import net.minecraft.nbt.NbtIntArray; +import net.minecraft.nbt.NbtList; import net.minecraft.registry.Registries; import net.minecraft.text.MutableText; import net.minecraft.text.Style; @@ -14,6 +17,7 @@ import java.util.List; public class Icon { + private static TextColor GOLD = TextColor.fromFormatting(Formatting.GOLD); public String material; public String head; public String name; @@ -36,10 +40,11 @@ public class Icon { /** * Gets the pure name, without any color codes. + * * @return */ public String getCleanName() { - return this.name.replaceAll("§.",""); + return this.name.replaceAll("§.", ""); } public ItemStack getItem() { @@ -49,121 +54,123 @@ public ItemStack getItem() { NbtCompound display = new NbtCompound(); NbtList lore = new NbtList(); - for (String line: description) { + for (String line : description) { addToLore(lore, "§7" + line); } - if(example != null && example.length != 0) { - addToLore(lore,""); - addToLore(lore,"Example:"); - for (String line: example) { + if (example != null && example.length != 0) { + addToLore(lore, ""); + addToLore(lore, "Example:"); + for (String line : example) { addToLore(lore, "§7" + line); } } - if(arguments != null && arguments.length != 0) { - addToLore(lore,""); - addToLore(lore,"Chest Parameters:"); + if (arguments != null && arguments.length != 0) { + addToLore(lore, ""); + addToLore(lore, "Chest Parameters:"); boolean hasOptional = false; - for (Argument arg: arguments) { + for (Argument arg : arguments) { int i = 0; - if(arg.text != null) addToLore(lore, arg.text); - if(arg.description != null && description.length != 0) for (String line: arg.description) { + if (arg.text != null) addToLore(lore, arg.text); + if (arg.description != null && description.length != 0) for (String line : arg.description) { Type type = Type.valueOf(arg.type); - if(i == 0) { + if (i == 0) { MutableText text = Text.empty().formatted(Formatting.GRAY); MutableText typeText = Text.literal(type.display).setStyle(Text.empty().getStyle().withColor(type.color)); - if(arg.plural) typeText.append("(s)"); + if (arg.plural) typeText.append("(s)"); text.append(typeText); - if(arg.optional) { + if (arg.optional) { text.append(Text.literal("*").formatted(Formatting.WHITE)); hasOptional = true; } text.append(Text.literal(" - ").formatted(Formatting.DARK_GRAY)); text.append(Utility.textFromString(line).formatted(Formatting.GRAY)); lore.add(Utility.nbtify(text)); - } - else lore.add(Utility.nbtify(Utility.textFromString(line).formatted(Formatting.GRAY))); + } else lore.add(Utility.nbtify(Utility.textFromString(line).formatted(Formatting.GRAY))); i++; } - if(arg.notes != null) for (String[] lines: arg.notes) { + if (arg.notes != null) for (String[] lines : arg.notes) { i = 0; - if(lines != null) for (String line: lines) { - if(i == 0) addToLore(lore, "§9⏵ §7" + line); + if (lines != null) for (String line : lines) { + if (i == 0) addToLore(lore, "§9⏵ §7" + line); else addToLore(lore, "§7" + line); i++; } } } - if(tags != null && tags != 0) { + if (tags != null && tags != 0) { lore.add(Utility.nbtify(Text.literal("# ").formatted(Formatting.DARK_AQUA).append(Text.literal(tags + " Tag" + (tags != 1 ? "s" : "")).formatted(Formatting.GRAY)))); } - if(hasOptional) { + if (hasOptional) { lore.add(Utility.nbtify(Text.literal(""))); lore.add(Utility.nbtify(Text.literal("*Optional").formatted(Formatting.GRAY))); } } - if(returnValues != null && returnValues.length != 0) { - addToLore(lore,""); - addToLore(lore,"Returns Value:"); - for (ReturnValue returnValue: returnValues) { - if(returnValue.text != null) addToLore(lore,returnValue.text); + if (returnValues != null && returnValues.length != 0) { + addToLore(lore, ""); + addToLore(lore, "Returns Value:"); + for (ReturnValue returnValue : returnValues) { + if (returnValue.text != null) addToLore(lore, returnValue.text); else { lore.add(Utility.nbtify(Text.empty().append(Text.literal(returnValue.type.display).setStyle(Style.EMPTY.withColor(returnValue.type.color))).append(Text.literal(" - ").formatted(Formatting.DARK_GRAY)).append(Text.literal(returnValue.description[0]).formatted(Formatting.GRAY)))); boolean first = true; - for (String description: returnValue.description) { - if(first) { + for (String description : returnValue.description) { + if (first) { first = false; continue; } - addToLore(lore,"§7" + description); + addToLore(lore, "§7" + description); } } } } - if(additionalInfo != null && additionalInfo.length != 0) { - addToLore(lore,""); - addToLore(lore,"§9Additional Info:"); - for(String[] group : additionalInfo) { + if (additionalInfo != null && additionalInfo.length != 0) { + addToLore(lore, ""); + addToLore(lore, "§9Additional Info:"); + for (String[] group : additionalInfo) { int i = 0; - for(String line: group) { - if(i == 0) addToLore(lore, "§b» §7" + line); + for (String line : group) { + if (i == 0) addToLore(lore, "§b» §7" + line); else addToLore(lore, "§7" + line); i++; } } } - if(cancellable != null && cancellable) { - addToLore(lore,""); - if(cancelledAutomatically) addToLore(lore, "§4∅ §cCancelled automatically"); + if (cancellable != null && cancellable) { + addToLore(lore, ""); + if (cancelledAutomatically) addToLore(lore, "§4∅ §cCancelled automatically"); else addToLore(lore, "§4∅ §cCancellable"); } - display.put("Lore",lore); + display.put("Lore", lore); - display.put("Name",Utility.nbtify(Utility.textFromString(name))); + display.put("Name", Utility.nbtify(Utility.textFromString(name))); - nbt.put("display",display); + nbt.put("display", display); nbt.put("HideFlags", NbtInt.of(127)); - if(color != null) nbt.put("CustomPotionColor", NbtInt.of(color.getColor())); + if (color != null) nbt.put("CustomPotionColor", NbtInt.of(color.getColor())); - if(head != null) { + if (head != null) { NbtCompound SkullOwner = new NbtCompound(); - NbtIntArray Id = new NbtIntArray(List.of(0,0,0,0)); - SkullOwner.put("Id",Id); - SkullOwner.putString("Name","DF-HEAD"); + NbtIntArray Id = new NbtIntArray(List.of(0, 0, 0, 0)); + SkullOwner.put("Id", Id); + SkullOwner.putString("Name", "DF-HEAD"); NbtCompound Properties = new NbtCompound(); - NbtList textures = new NbtList(); - NbtCompound texture = new NbtCompound(); - texture.putString("Value",head); - textures.add(texture); - Properties.put("textures",textures); - SkullOwner.put("Properties",Properties); - nbt.put("SkullOwner",SkullOwner); + NbtList textures = new NbtList(); + NbtCompound texture = new NbtCompound(); + texture.putString("Value", head); + textures.add(texture); + Properties.put("textures", textures); + SkullOwner.put("Properties", Properties); + nbt.put("SkullOwner", SkullOwner); } item.setNbt(nbt); return item; } - private static TextColor GOLD = TextColor.fromFormatting(Formatting.GOLD); + private void addToLore(NbtList lore, String text) { + lore.add(Utility.nbtify(Utility.textFromString(text))); + } + public enum Type { TEXT(TextColor.fromFormatting(Formatting.AQUA), "Text"), COMPONENT(TextColor.fromRgb(0x7fd42a), "Rich Text"), @@ -189,16 +196,14 @@ public enum Type { public final TextColor color; public final String display; + Type(TextColor color, String display) { this.color = color; this.display = display; } } - record ReturnValue(Type type, String[] description, String text) {} - - private void addToLore(NbtList lore, String text) { - lore.add(Utility.nbtify(Utility.textFromString(text))); + record ReturnValue(Type type, String[] description, String text) { } public static class Color { diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Particle.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Particle.java index 2c7b74b2..fdd0b63a 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Particle.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Particle.java @@ -29,25 +29,25 @@ public ItemStack getItem() { data.addProperty("particle", icon.getCleanName()); JsonObject cluster = new JsonObject(); - cluster.addProperty("amount",1); - cluster.addProperty("horizontal",0.0); - cluster.addProperty("vertical",0.0); - data.add("cluster",cluster); + cluster.addProperty("amount", 1); + cluster.addProperty("horizontal", 0.0); + cluster.addProperty("vertical", 0.0); + data.add("cluster", cluster); JsonObject particleData = new JsonObject(); List optionFields = Arrays.stream(fields).toList(); - if(optionFields.contains(ParticleField.Motion)) { - particleData.addProperty("x",1); - particleData.addProperty("y",0); - particleData.addProperty("z",0); + if (optionFields.contains(ParticleField.Motion)) { + particleData.addProperty("x", 1); + particleData.addProperty("y", 0); + particleData.addProperty("z", 0); } - if(optionFields.contains(ParticleField.MotionVariation)) particleData.addProperty("motionVariation", 100); - if(optionFields.contains(ParticleField.Color)) particleData.addProperty("rgb",0xFF0000); - if(optionFields.contains(ParticleField.ColorVariation)) particleData.addProperty("colorVariation",0); - if(optionFields.contains(ParticleField.Size)) particleData.addProperty("size",1); - if(optionFields.contains(ParticleField.SizeVariation)) particleData.addProperty("sizeVariation",0); - if(optionFields.contains(ParticleField.Material)) particleData.addProperty("material","STONE"); - data.add("data",particleData); + if (optionFields.contains(ParticleField.MotionVariation)) particleData.addProperty("motionVariation", 100); + if (optionFields.contains(ParticleField.Color)) particleData.addProperty("rgb", 0xFF0000); + if (optionFields.contains(ParticleField.ColorVariation)) particleData.addProperty("colorVariation", 0); + if (optionFields.contains(ParticleField.Size)) particleData.addProperty("size", 1); + if (optionFields.contains(ParticleField.SizeVariation)) particleData.addProperty("sizeVariation", 0); + if (optionFields.contains(ParticleField.Material)) particleData.addProperty("material", "STONE"); + data.add("data", particleData); ItemStack item = super.getItem("part", data); @@ -55,13 +55,13 @@ public ItemStack getItem() { NbtList Lore = (NbtList) display.get("Lore"); Lore.add(nbtify(Text.literal(""))); Lore.add(nbtify(Text.literal("Additional Fields:").formatted(Formatting.GRAY))); - if(optionFields.size() == 0) Lore.add(nbtify(Text.literal("None").formatted(Formatting.DARK_GRAY))); - else for (ParticleField field: optionFields) { - if(field != null) Lore.add(nbtify(Text.literal("• " + field.displayName).formatted(Formatting.WHITE))); + if (optionFields.size() == 0) Lore.add(nbtify(Text.literal("None").formatted(Formatting.DARK_GRAY))); + else for (ParticleField field : optionFields) { + if (field != null) Lore.add(nbtify(Text.literal("• " + field.displayName).formatted(Formatting.WHITE))); else Lore.add(nbtify(Text.of("NULL?"))); } - display.put("Lore",Lore); - item.setSubNbt("display",display); + display.put("Lore", Lore); + item.setSubNbt("display", display); return item; } @@ -83,6 +83,7 @@ enum ParticleField { SizeVariation("Size Variation"); public final String displayName; + ParticleField(String displayName) { this.displayName = displayName; } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Potion.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Potion.java index bafb7bfa..d1e1f7f6 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Potion.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Potion.java @@ -16,9 +16,9 @@ public List getTerms() { @Override public ItemStack getItem() { JsonObject data = new JsonObject(); - data.addProperty("pot",icon.getCleanName()); - data.addProperty("dur",1000000); - data.addProperty("amp",0); - return super.getItem("pot",data); + data.addProperty("pot", icon.getCleanName()); + data.addProperty("dur", 1000000); + data.addProperty("amp", 0); + return super.getItem("pot", data); } } \ No newline at end of file diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Searchable.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Searchable.java index c36996f9..3b2f798c 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Searchable.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Searchable.java @@ -6,6 +6,7 @@ public interface Searchable { List getTerms(); + ItemStack getItem(); class StaticSearchable implements Searchable { diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Sound.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Sound.java index 40c4f26c..9c2cc9ce 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Sound.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/Sound.java @@ -10,14 +10,14 @@ public class Sound extends VarItem implements Searchable { @Override public List getTerms() { - return List.of(sound,icon.name); + return List.of(sound, icon.name); } public ItemStack getItem() { JsonObject data = new JsonObject(); data.addProperty("sound", icon.getCleanName()); - data.addProperty("pitch",1); - data.addProperty("vol",2); - return super.getItem("snd",data); + data.addProperty("pitch", 1); + data.addProperty("vol", 2); + return super.getItem("snd", data); } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/VarItem.java b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/VarItem.java index 2cd92673..745a9fa4 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/VarItem.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/actiondump/VarItem.java @@ -13,8 +13,8 @@ public ItemStack getItem(String id, JsonObject data) { NbtCompound nbt = item.getNbt(); NbtCompound publicBukkitValues = new NbtCompound(); JsonObject varItem = new JsonObject(); - varItem.addProperty("id",id); - varItem.add("data",data); + varItem.addProperty("id", id); + varItem.add("data", data); publicBukkitValues.put("hypercube:varitem", NbtString.of(varItem.toString())); nbt.put("PublicBukkitValues", publicBukkitValues); item.setNbt(nbt); diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/BlockTag.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/BlockTag.java index 4ec16364..cc4bca82 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/BlockTag.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/BlockTag.java @@ -35,20 +35,8 @@ public class BlockTag extends VarItem { @Nullable private Variable variable; - private static JsonObject makeVar(String option, String tag, String action, String block) { - var var = new JsonObject(); - var.addProperty("id","bl_tag"); - var data = new JsonObject(); - data.addProperty("option",option); - data.addProperty("tag",tag); - data.addProperty("action",action); - data.addProperty("block",block); - var.add("data",data); - return var; - } - public BlockTag(String material, String option, String tag, String action, String block) { - this(Registries.ITEM.get(new Identifier("minecraft",material.toLowerCase())),makeVar(option, tag, action, block)); + this(Registries.ITEM.get(new Identifier("minecraft", material.toLowerCase())), makeVar(option, tag, action, block)); } public BlockTag(Item material, JsonObject var) { @@ -57,36 +45,56 @@ public BlockTag(Item material, JsonObject var) { tag = this.data.get("tag").getAsString(); action = this.data.get("action").getAsString(); block = this.data.get("block").getAsString(); - if(this.data.has("variable")) variable = new Variable(Items.MAGMA_CREAM,this.data.get("variable").getAsJsonObject()); + if (this.data.has("variable")) + variable = new Variable(Items.MAGMA_CREAM, this.data.get("variable").getAsJsonObject()); + } + + private static JsonObject makeVar(String option, String tag, String action, String block) { + var var = new JsonObject(); + var.addProperty("id", "bl_tag"); + var data = new JsonObject(); + data.addProperty("option", option); + data.addProperty("tag", tag); + data.addProperty("action", action); + data.addProperty("block", block); + var.add("data", data); + return var; } public @NotNull String getOption() { return this.option; } + public void setOption(@NotNull String option) { this.option = option; - this.data.addProperty("option",option); + this.data.addProperty("option", option); } + public @NotNull String getTag() { return this.tag; } + public void setTag(@NotNull String tag) { this.tag = tag; - this.data.addProperty("tag",tag); + this.data.addProperty("tag", tag); } + public @NotNull String getAction() { return this.action; } + public void setAction(@NotNull String action) { this.action = action; - this.data.addProperty("action",action); + this.data.addProperty("action", action); } + public @NotNull String getBlock() { return this.block; } + public void setBlock(@NotNull String block) { this.block = block; - this.data.addProperty("block",block); + this.data.addProperty("block", block); } public @Nullable Variable getVariable() { @@ -95,6 +103,6 @@ public void setBlock(@NotNull String block) { public void setVariable(@Nullable Variable variable) { this.variable = variable; - this.data.add("variable",variable.getData()); + this.data.add("variable", variable.getData()); } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/GameValue.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/GameValue.java index c0ce0568..88429d80 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/GameValue.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/GameValue.java @@ -10,9 +10,7 @@ import net.minecraft.text.Text; import net.minecraft.util.Formatting; -import java.io.IOException; import java.util.Arrays; -import java.util.Optional; public class GameValue extends VarItem { private String type; @@ -31,7 +29,7 @@ public String getType() { // TODO: allow rejecting nonexistant values if actiondump is loaded public void setType(String type) { this.type = type; - this.data.addProperty("type",type); + this.data.addProperty("type", type); } // public void setData(String type, Target target) { @@ -47,7 +45,7 @@ public Target getTarget() { public void setTarget(Target target) { this.target = target; - this.data.addProperty("target",target.name()); + this.data.addProperty("target", target.name()); } @Override @@ -56,12 +54,12 @@ public ItemStack toStack() { try { ActionDump db = ActionDump.getActionDump(); var value = Arrays.stream(db.gameValues).filter(gv -> gv.icon.getCleanName().equals(type)).findFirst(); - if(value.isEmpty()) throw new Exception(""); + if (value.isEmpty()) throw new Exception(""); stack.setCustomName(Text.literal(value.get().icon.name)); } catch (Exception e) { stack.setCustomName(Text.literal(type).setStyle(Style.EMPTY)); } - Utility.addLore(stack,Text.literal("Target: ").formatted(Formatting.GRAY).append(Text.literal(target.name()).setStyle(Style.EMPTY.withColor(target.color)))); + Utility.addLore(stack, Text.literal("Target: ").formatted(Formatting.GRAY).append(Text.literal(target.name()).setStyle(Style.EMPTY.withColor(target.color)))); return stack; } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Hint.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Hint.java index 317b4ef7..c68a1d6e 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Hint.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Hint.java @@ -8,13 +8,13 @@ import net.minecraft.util.Formatting; public class Hint extends VarItem { + public static final TextColor HintGreen = TextColor.fromRgb(0xAAFF55); + private static final Text Parameter = Text.literal("Parameter").fillStyle(Style.EMPTY.withColor(0xAAFFAA)); + private static final Text Line = Text.literal("LINE"); public Hint(Item material, JsonObject var) { super(material, var); } - private static final Text Parameter = Text.literal("Parameter").fillStyle(Style.EMPTY.withColor(0xAAFFAA)); - private static final Text Line = Text.literal("LINE"); - public static final TextColor HintGreen = TextColor.fromRgb(0xAAFF55); public enum HintType { function("Function Parameters", Text.empty().formatted(Formatting.GRAY) @@ -31,6 +31,7 @@ public enum HintType { public final String name; public final Text text; + HintType(String name, Text text) { this.name = name; this.text = text; diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Location.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Location.java index 71cc37f4..c74ab18c 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Location.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Location.java @@ -6,38 +6,37 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; -import net.minecraft.nbt.NbtList; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.math.Vec3d; -import org.jetbrains.annotations.NotNull; public class Location extends VarItem { - private JsonObject loc; - private double x; - private double y; - private double z; - private double pitch; - private double yaw; - private static final JsonObject defaultObject; + static { var obj = new JsonObject(); - obj.addProperty("id","loc"); + obj.addProperty("id", "loc"); var data = new JsonObject(); - data.addProperty("isBlock",false); + data.addProperty("isBlock", false); var loc = new JsonObject(); - loc.addProperty("x",0); - loc.addProperty("y",0); - loc.addProperty("z",0); - loc.addProperty("pitch",0); - loc.addProperty("yaw",0); - data.add("loc",loc); - obj.add("data",data); + loc.addProperty("x", 0); + loc.addProperty("y", 0); + loc.addProperty("z", 0); + loc.addProperty("pitch", 0); + loc.addProperty("yaw", 0); + data.add("loc", loc); + obj.add("data", data); defaultObject = obj; } + private JsonObject loc; + private double x; + private double y; + private double z; + private double pitch; + private double yaw; + public Location(Item material, JsonObject data) { super(material, data); this.loc = this.data.getAsJsonObject("loc"); @@ -47,6 +46,7 @@ public Location(Item material, JsonObject data) { this.pitch = loc.get("pitch").getAsDouble(); this.yaw = loc.get("yaw").getAsDouble(); } + private Location() { this(Items.PAPER, defaultObject); // Make sure everything is init'd. @@ -65,6 +65,7 @@ public Location(double x, double y, double z, double pitch, double yaw) { setPitch(pitch); setYaw(yaw); } + public Location(Vec3d pos) { this(); setX(pos.x); @@ -72,49 +73,59 @@ public Location(Vec3d pos) { setZ(pos.z); } - public void setX(double x) { - loc.addProperty("x",x); - data.add("loc",loc); - this.x = x; - } public double getX() { return x; } - public void setY(double y) { - loc.addProperty("y",y); - data.add("loc",loc); - this.y = y; + + public void setX(double x) { + loc.addProperty("x", x); + data.add("loc", loc); + this.x = x; } + public double getY() { return y; } - public void setZ(double z) { - loc.addProperty("z",z); - data.add("loc",loc); - this.z = z; + + public void setY(double y) { + loc.addProperty("y", y); + data.add("loc", loc); + this.y = y; } + public double getZ() { return z; } - public void setPitch(double pitch) { - loc.addProperty("pitch",pitch); - data.add("loc",loc); - this.pitch = pitch; + + public void setZ(double z) { + loc.addProperty("z", z); + data.add("loc", loc); + this.z = z; } + public double getPitch() { return pitch; } - public void setYaw(double yaw) { - loc.addProperty("yaw",yaw); - data.add("loc",loc); - this.yaw = yaw; + + public void setPitch(double pitch) { + loc.addProperty("pitch", pitch); + data.add("loc", loc); + this.pitch = pitch; } + public double getYaw() { return yaw; } + public void setYaw(double yaw) { + loc.addProperty("yaw", yaw); + data.add("loc", loc); + this.yaw = yaw; + } + /** * Mutates the location. + * * @return The mutated location with the rotation. */ public Location setRotation(double pitch, double yaw) { @@ -129,12 +140,12 @@ public void setCoords(double x, double y, double z, double pitch, double yaw) { this.z = z; this.pitch = pitch; this.yaw = yaw; - this.loc.addProperty("x",x); - this.loc.addProperty("y",y); - this.loc.addProperty("z",z); - this.loc.addProperty("pitch",pitch); - this.loc.addProperty("yaw",yaw); - data.add("loc",loc); + this.loc.addProperty("x", x); + this.loc.addProperty("y", y); + this.loc.addProperty("z", z); + this.loc.addProperty("pitch", pitch); + this.loc.addProperty("yaw", yaw); + data.add("loc", loc); } @Override @@ -142,12 +153,12 @@ public ItemStack toStack() { ItemStack stack = super.toStack(); stack.setCustomName(Text.literal("Location").setStyle(Style.EMPTY.withItalic(false).withColor(Icon.Type.LOCATION.color))); Utility.addLore( - stack, - Text.empty().append(Text.literal("X: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.x)), - Text.empty().append(Text.literal("Y: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.y)), - Text.empty().append(Text.literal("Z: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)), - Text.empty().append(Text.literal("p: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)), - Text.empty().append(Text.literal("y: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)) + stack, + Text.empty().append(Text.literal("X: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.x)), + Text.empty().append(Text.literal("Y: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.y)), + Text.empty().append(Text.literal("Z: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)), + Text.empty().append(Text.literal("p: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)), + Text.empty().append(Text.literal("y: ").formatted(Formatting.GRAY)).append("%.2f".formatted(this.z)) ); return stack; } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/NamedItem.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/NamedItem.java index 934ee4eb..bc1e1732 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/NamedItem.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/NamedItem.java @@ -20,7 +20,7 @@ public String getName() { public void setName(String name) { this.name = name; - this.data.addProperty("name",name); + this.data.addProperty("name", name); } @Override diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Potion.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Potion.java index 83643938..ead864e8 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Potion.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Potion.java @@ -24,25 +24,37 @@ public Potion(Item material, JsonObject var) { this.amplifier = data.get("amp").getAsInt(); } + public static String durationToString(int duration) { + if (duration >= 1000000) return "Infinite"; + if (duration % 20 != 0) return "%d ticks".formatted(duration); + int seconds = duration / 20; + return "%d:%d".formatted(seconds / 60, seconds % 60); + } + public String getPotion() { return potion; } + public void setPotion(String potion) { - data.addProperty("pot",potion); + data.addProperty("pot", potion); this.potion = potion; } + public int getDuration() { return duration; } + public void setDuration(int duration) { - data.addProperty("dur",duration); + data.addProperty("dur", duration); this.duration = duration; } + public int getAmplifier() { return amplifier; } + public void setAmplifier(int amplifier) { - data.addProperty("amp",amplifier); + data.addProperty("amp", amplifier); this.amplifier = amplifier; } @@ -54,7 +66,7 @@ public ItemStack toStack() { try { ActionDump db = ActionDump.getActionDump(); var value = Arrays.stream(db.potions).filter(gv -> gv.icon.getCleanName().equals(potion)).findFirst(); - if(value.isEmpty()) throw new Exception(""); + if (value.isEmpty()) throw new Exception(""); name = Text.literal(value.get().icon.name); } catch (Exception e) { name = Text.literal(potion).setStyle(Style.EMPTY); @@ -70,11 +82,4 @@ public ItemStack toStack() { public String duration() { return durationToString(duration); } - - public static String durationToString(int duration) { - if(duration >= 1000000) return "Infinite"; - if(duration % 20 != 0) return "%d ticks".formatted(duration); - int seconds = duration / 20; - return "%d:%d".formatted(seconds / 60, seconds % 60); - } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Scope.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Scope.java index 5ebe2184..ab30189d 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Scope.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Scope.java @@ -13,6 +13,7 @@ public enum Scope { public final TextColor color; public final String longName; public final String shortName; + Scope(TextColor color, String longName, String shortName) { this.color = color; this.longName = longName; diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Sound.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Sound.java index 733573fe..c1dcb513 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Sound.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Sound.java @@ -19,9 +19,9 @@ public class Sound extends VarItem { public Sound(Item material, JsonObject var) { super(material, var); - this.sound = data.get("sound").getAsString(); - this.pitch = data.get("pitch").getAsDouble(); - this.volume = data.get("vol" ).getAsDouble(); + this.sound = data.get("sound").getAsString(); + this.pitch = data.get("pitch").getAsDouble(); + this.volume = data.get("vol").getAsDouble(); } public String getSound() { @@ -30,7 +30,7 @@ public String getSound() { public void setSound(String sound) { this.sound = sound; - this.data.addProperty("sound",sound); + this.data.addProperty("sound", sound); } public double getPitch() { @@ -39,7 +39,7 @@ public double getPitch() { public void setPitch(double pitch) { this.pitch = pitch; - this.data.addProperty("pitch",pitch); + this.data.addProperty("pitch", pitch); } public double getVolume() { @@ -48,7 +48,7 @@ public double getVolume() { public void setVolume(double volume) { this.volume = volume; - this.data.addProperty("vol",volume); + this.data.addProperty("vol", volume); } @Override @@ -59,7 +59,7 @@ public ItemStack toStack() { try { ActionDump db = ActionDump.getActionDump(); var value = Arrays.stream(db.sounds).filter(gv -> gv.icon.getCleanName().equals(sound)).findFirst(); - if(value.isEmpty()) throw new Exception(""); + if (value.isEmpty()) throw new Exception(""); name = Text.literal(value.get().icon.name); } catch (Exception e) { name = Text.literal(sound).setStyle(Style.EMPTY); diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItem.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItem.java index 06c63f0c..cdb94673 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItem.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItem.java @@ -18,17 +18,6 @@ protected VarItem(String id) { this.id = id; } - public static JsonObject prefetch(ItemStack item) throws Exception { - if (!item.hasNbt()) throw new Exception("Item has no nbt."); - NbtCompound nbt = item.getNbt(); - if (nbt == null) throw new Exception("NBT is null."); - if (!nbt.contains("PublicBukkitValues",NbtElement.COMPOUND_TYPE)) throw new Exception("Item has no PublicBukkitValues"); - NbtCompound publicBukkit = nbt.getCompound("PublicBukkitValues"); - if (!publicBukkit.contains("hypercube:varitem", NbtElement.STRING_TYPE)) throw new Exception("Item has no hypercube:varitem"); - String varitem = publicBukkit.getString("hypercube:varitem"); - return JsonParser.parseString(varitem).getAsJsonObject(); - - } public VarItem(ItemStack item) throws Exception { this(item.getItem(), prefetch(item)); } @@ -39,15 +28,28 @@ public VarItem(Item material, JsonObject var) { data = var.get("data").getAsJsonObject(); } + public static JsonObject prefetch(ItemStack item) throws Exception { + if (!item.hasNbt()) throw new Exception("Item has no nbt."); + NbtCompound nbt = item.getNbt(); + if (nbt == null) throw new Exception("NBT is null."); + if (!nbt.contains("PublicBukkitValues", NbtElement.COMPOUND_TYPE)) + throw new Exception("Item has no PublicBukkitValues"); + NbtCompound publicBukkit = nbt.getCompound("PublicBukkitValues"); + if (!publicBukkit.contains("hypercube:varitem", NbtElement.STRING_TYPE)) + throw new Exception("Item has no hypercube:varitem"); + String varitem = publicBukkit.getString("hypercube:varitem"); + return JsonParser.parseString(varitem).getAsJsonObject(); + + } public ItemStack toStack() { var pbv = new NbtCompound(); var varItem = new JsonObject(); - varItem.addProperty("id",id); - varItem.add("data",data); + varItem.addProperty("id", id); + varItem.add("data", data); pbv.put("hypercube:varitem", NbtString.of(varItem.toString())); ItemStack item = material.getDefaultStack(); - item.setSubNbt("PublicBukkitValues",pbv); + item.setSubNbt("PublicBukkitValues", pbv); return item; } @@ -58,8 +60,8 @@ public JsonObject getData() { public JsonObject getVar() { // This is probably the best approach tbh instead of updating data constantly var var = new JsonObject(); - var.addProperty("id",id); - var.add("data",getData()); + var.addProperty("id", id); + var.add("data", getData()); return var; } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItems.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItems.java index bf4916c2..38e473d9 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItems.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/VarItems.java @@ -21,13 +21,13 @@ public static VarItem parse(ItemStack item) { case "pot" -> new Potion(material, var); case "snd" -> new Sound(material, var); case "g_val" -> new GameValue(material, var); - case "pn_el" -> new Parameter(material, var); // Short for `pattern_element`. Parameters, each bullet in a actions Chest Parameters is a pattern internally. Apparently. + case "pn_el" -> + new Parameter(material, var); // Short for `pattern_element`. Parameters, each bullet in a actions Chest Parameters is a pattern internally. Apparently. case "bl_tag" -> new BlockTag(material, var); case "hint" -> new Hint(material, var); // we're so funny default -> null; }; - } - catch (Exception e) { + } catch (Exception e) { return null; } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Variable.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Variable.java index 03880b13..09e86680 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Variable.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Variable.java @@ -16,15 +16,15 @@ public Variable(Item material, JsonObject var) { this.scope = Scope.valueOf(data.get("scope").getAsString()); } - public void setScope(Scope scope) { - this.scope = scope; - data.addProperty("scope",scope.name()); - } - public Scope getScope() { return scope; } + public void setScope(Scope scope) { + this.scope = scope; + data.addProperty("scope", scope.name()); + } + @Override public ItemStack toStack() { var stack = super.toStack(); diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/item/Vector.java b/src/main/java/dev/dfonline/codeclient/hypercube/item/Vector.java index 87a2db6b..cf3dd9ca 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/item/Vector.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/item/Vector.java @@ -6,8 +6,6 @@ import dev.dfonline.codeclient.hypercube.actiondump.Icon; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -import net.minecraft.nbt.NbtElement; -import net.minecraft.nbt.NbtList; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.Formatting; @@ -27,35 +25,38 @@ public Vector(Item material, JsonObject var) { public double getX() { return this.x; } + public void setX(Double x) { this.x = x; CodeClient.LOGGER.info(String.valueOf(x)); - this.data.addProperty("x",x); + this.data.addProperty("x", x); } public double getY() { return this.y; } + public void setY(Double y) { this.y = y; - this.data.addProperty("x",y); + this.data.addProperty("x", y); } public double getZ() { return this.z; } + public void setZ(Double z) { this.z = z; - this.data.addProperty("x",z); + this.data.addProperty("x", z); } public void setCoords(Double x, Double y, Double z) { this.x = x; this.y = y; this.z = z; - this.data.addProperty("x",x); - this.data.addProperty("y",y); - this.data.addProperty("z",z); + this.data.addProperty("x", x); + this.data.addProperty("y", y); + this.data.addProperty("z", z); } @Override diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/template/Argument.java b/src/main/java/dev/dfonline/codeclient/hypercube/template/Argument.java index a0937f01..db5c2394 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/template/Argument.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/template/Argument.java @@ -9,19 +9,14 @@ public class Argument { public int slot; - @NotNull public VarItem item; + @NotNull + public VarItem item; + public Argument(@NotNull VarItem item, int slot) { this.item = item; this.slot = slot; } - public JsonObject toJsonObject() { - var object = new JsonObject(); - object.add("item",item.getVar()); - object.addProperty("slot",slot); - return object; - } - /** * Parse from a real in-game item. */ @@ -31,12 +26,20 @@ public Argument(@NotNull ItemStack item, int slot) { public static VarItem getVarItem(@NotNull ItemStack stack) { var parsed = VarItems.parse(stack); - if(parsed != null) return parsed; + if (parsed != null) return parsed; return new MinecraftItem(stack); } + public JsonObject toJsonObject() { + var object = new JsonObject(); + object.add("item", item.getVar()); + object.addProperty("slot", slot); + return object; + } + public static class MinecraftItem extends VarItem { public @NotNull ItemStack stack; + public MinecraftItem(@NotNull ItemStack item) { super("item"); stack = item; @@ -47,9 +50,10 @@ public JsonObject getData() { var data = new JsonObject(); var item = new NbtCompound(); stack.writeNbt(item); - data.addProperty("item",item.toString()); + data.addProperty("item", item.toString()); return data; } + public void setStack(ItemStack stack) { this.stack = stack; } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/template/Bracket.java b/src/main/java/dev/dfonline/codeclient/hypercube/template/Bracket.java index 838dc58d..25dc00c8 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/template/Bracket.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/template/Bracket.java @@ -4,12 +4,13 @@ public class Bracket extends TemplateBlock { public Bracket() { - this(false,false); + this(false, false); } public Bracket(boolean closing) { - this(closing,false); + this(closing, false); } + public Bracket(boolean closing, boolean sticky) { this.id = "bracket"; this.block = null; @@ -21,8 +22,8 @@ public Bracket(boolean closing, boolean sticky) { @Override public JsonObject toJsonObject() { var obj = super.toJsonObject(); - obj.addProperty("direct",direct); - obj.addProperty("type",type); + obj.addProperty("direct", direct); + obj.addProperty("type", type); return obj; } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/template/Template.java b/src/main/java/dev/dfonline/codeclient/hypercube/template/Template.java index 663b6704..e0b304a2 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/template/Template.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/template/Template.java @@ -8,17 +8,10 @@ import java.util.ArrayList; import java.util.Base64; import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; public class Template { public ArrayList blocks; - public int getLength() { - int length = 0; - for (var block: blocks) length += block.getLength(); - return length; - } - /** * Parse base64+gzip data */ @@ -58,4 +51,10 @@ private static byte[] decompress(byte[] compressedData) throws IOException { return bos.toByteArray(); } } + + public int getLength() { + int length = 0; + for (var block : blocks) length += block.getLength(); + return length; + } } diff --git a/src/main/java/dev/dfonline/codeclient/hypercube/template/TemplateBlock.java b/src/main/java/dev/dfonline/codeclient/hypercube/template/TemplateBlock.java index 5e40c9b0..70292b74 100644 --- a/src/main/java/dev/dfonline/codeclient/hypercube/template/TemplateBlock.java +++ b/src/main/java/dev/dfonline/codeclient/hypercube/template/TemplateBlock.java @@ -13,34 +13,51 @@ public class TemplateBlock { /** * "open" | "close" */ - @Nullable public String direct; + @Nullable + public String direct; /** * "norm" | "repeat" */ - @Nullable public String type; - @Nullable public String block; - @Nullable public String data; - @Nullable public String action; + @Nullable + public String type; + @Nullable + public String block; + @Nullable + public String data; + @Nullable + public String action; + + public int getLength() { + return id.equals("block") + ? Block.valueOf(block.toUpperCase()).hasStone ? 2 : 1 + : Objects.equals(direct, "open") ? 1 : 2; + } + + public JsonObject toJsonObject() { + var obj = new JsonObject(); + obj.addProperty("id", id); + return obj; + } public enum Block { - CALL_FUNC("CALL FUNCTION",true), - CONTROL("CONTROL",true), - ELSE("ELSE",false), - ENTITY_ACTION("ENTITY ACTION",true), - ENTITY_EVENT("ENTITY EVENT",true), - EVENT("PLAYER EVENT",true), - FUNC("FUNCTION",true), - GAME_ACTION("GAME ACTION",true), - IF_ENTITY("IF PLAYER",false), - IF_GAME("IF GAME",false), - IF_PLAYER("IF PLAYER",false), - IF_VAR("IF VARIABLE",false), - PLAYER_ACTION("PLAYER ACTION",true), - PROCESS("PROCESS",true), - REPEAT("REPEAT",false), - SELECT_OBJ("SELECT OBJECT",true), - SET_VAR("SET VARIABLE",true), - START_PROCESS("START PROCESS",true); + CALL_FUNC("CALL FUNCTION", true), + CONTROL("CONTROL", true), + ELSE("ELSE", false), + ENTITY_ACTION("ENTITY ACTION", true), + ENTITY_EVENT("ENTITY EVENT", true), + EVENT("PLAYER EVENT", true), + FUNC("FUNCTION", true), + GAME_ACTION("GAME ACTION", true), + IF_ENTITY("IF PLAYER", false), + IF_GAME("IF GAME", false), + IF_PLAYER("IF PLAYER", false), + IF_VAR("IF VARIABLE", false), + PLAYER_ACTION("PLAYER ACTION", true), + PROCESS("PROCESS", true), + REPEAT("REPEAT", false), + SELECT_OBJ("SELECT OBJECT", true), + SET_VAR("SET VARIABLE", true), + START_PROCESS("START PROCESS", true); public final String name; // TODO: check I got all these names right. public final boolean hasStone; @@ -51,15 +68,4 @@ public enum Block { } } - public int getLength() { - return id.equals("block") - ? Block.valueOf(block.toUpperCase()).hasStone ? 2 : 1 - : Objects.equals(direct, "open") ? 1 : 2; - } - - public JsonObject toJsonObject() { - var obj = new JsonObject(); - obj.addProperty("id",id); - return obj; - } } diff --git a/src/main/java/dev/dfonline/codeclient/location/Dev.java b/src/main/java/dev/dfonline/codeclient/location/Dev.java index 8a11851c..64baa6cd 100644 --- a/src/main/java/dev/dfonline/codeclient/location/Dev.java +++ b/src/main/java/dev/dfonline/codeclient/location/Dev.java @@ -3,7 +3,7 @@ public class Dev extends Creator { public Dev(double x, double z) { this.hasDev = true; - setDevSpawn(x,z); + setDevSpawn(x, z); } public void setDevSpawn(double x, double z) { diff --git a/src/main/java/dev/dfonline/codeclient/location/Play.java b/src/main/java/dev/dfonline/codeclient/location/Play.java index 1d6f6e78..d6e19987 100644 --- a/src/main/java/dev/dfonline/codeclient/location/Play.java +++ b/src/main/java/dev/dfonline/codeclient/location/Play.java @@ -1,7 +1,8 @@ package dev.dfonline.codeclient.location; public class Play extends Plot { - public Play() {} + public Play() { + } @Override public String name() { diff --git a/src/main/java/dev/dfonline/codeclient/location/Plot.java b/src/main/java/dev/dfonline/codeclient/location/Plot.java index 7bedaecb..d028d7f9 100644 --- a/src/main/java/dev/dfonline/codeclient/location/Plot.java +++ b/src/main/java/dev/dfonline/codeclient/location/Plot.java @@ -1,64 +1,51 @@ package dev.dfonline.codeclient.location; import dev.dfonline.codeclient.CodeClient; -import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.SignBlockEntity; import net.minecraft.block.entity.SignText; -import net.minecraft.registry.Registries; -import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public abstract class Plot extends Location { + /** + * The position the player was at before they were teleported, in any scenario but plot borders. + */ + public Vec3d devPos; protected Integer id; protected String name; protected String owner; - protected Integer originX; protected Integer originZ; - protected boolean hasUnderground = false; - protected Boolean hasBuild; protected Boolean hasDev; - protected Size size; - /** - * The position the player was at before they were teleported, in any scenario but plot borders. - */ - public Vec3d devPos; - public void setOrigin(int x, int z) { this.originX = x; this.originZ = z; } + public Vec3d getPos() { - return new Vec3d(originX,0,originZ); + return new Vec3d(originX, 0, originZ); } public void copyValuesFrom(Plot plot) { - if(plot.id != null) this.id = plot.id; - if(plot.name != null) this.name = plot.name; - if(plot.owner != null) this.owner = plot.owner; - if(plot.originX != null) this.originX = plot.originX; - if(plot.originZ != null) this.originZ = plot.originZ; - if(plot.hasBuild != null) this.hasBuild = plot.hasBuild; - if(plot.hasDev != null) this.hasDev = plot.hasDev; - if(plot.size != null) this.size = plot.size; - if(plot.devPos != null) this.devPos = plot.devPos; - } - - public void setSize(Size size) { - this.size = size; + if (plot.id != null) this.id = plot.id; + if (plot.name != null) this.name = plot.name; + if (plot.owner != null) this.owner = plot.owner; + if (plot.originX != null) this.originX = plot.originX; + if (plot.originZ != null) this.originZ = plot.originZ; + if (plot.hasBuild != null) this.hasBuild = plot.hasBuild; + if (plot.hasDev != null) this.hasDev = plot.hasDev; + if (plot.size != null) this.size = plot.size; + if (plot.devPos != null) this.devPos = plot.devPos; } public void setHasUnderground(boolean hasUnderground) { @@ -68,8 +55,13 @@ public void setHasUnderground(boolean hasUnderground) { public Size getSize() { return size; } + + public void setSize(Size size) { + this.size = size; + } + public Size assumeSize() { - if(size == null) return Size.MASSIVE; + if (size == null) return Size.MASSIVE; else return size; } @@ -80,6 +72,7 @@ public Integer getX() { public Integer getZ() { return originZ; } + public int getFloorY() { return hasUnderground ? 5 : 50; } @@ -106,6 +99,7 @@ public Boolean isInArea(Vec3d pos) { public Boolean isInDev(BlockPos pos) { return isInDev(new Vec3d(pos.getX() + 1, pos.getY(), pos.getZ())); } + public Boolean isInDev(Vec3d pos) { Size size = assumeSize(); @@ -124,48 +118,50 @@ public Boolean isInDev(Vec3d pos) { * Returns null if the plot origin is unknown or world is null. */ @Nullable - public HashMap scanForSigns(Pattern name, Pattern scan) { - if (CodeClient.MC.world == null || originX == null || originZ == null || !(CodeClient.location instanceof Plot)) return null; - HashMap signs = new HashMap<>(); - for (int y = ((Plot) CodeClient.location).getFloorY(); y < 255; y+=5) { + public HashMap scanForSigns(Pattern name, Pattern scan) { + if (CodeClient.MC.world == null || originX == null || originZ == null || !(CodeClient.location instanceof Plot)) + return null; + HashMap signs = new HashMap<>(); + for (int y = ((Plot) CodeClient.location).getFloorY(); y < 255; y += 5) { int xEnd = originX + 1; for (int x = originX - 20; x < xEnd; x++) { int zEnd = originZ + assumeSize().size; - for(int z = originZ; z < zEnd; z++) { - BlockPos pos = new BlockPos(x,y,z); + for (int z = originZ; z < zEnd; z++) { + BlockPos pos = new BlockPos(x, y, z); BlockEntity block = CodeClient.MC.world.getBlockEntity(pos); if (block instanceof SignBlockEntity sign) { SignText text = sign.getFrontText(); - Matcher nameMatch = name.matcher(text.getMessage(0,false).getString()); - if(!nameMatch.matches()) continue; - Matcher scanMatch = scan.matcher(text.getMessage(1,false).getString()); - if(scanMatch.matches()) signs.put(pos,text); + Matcher nameMatch = name.matcher(text.getMessage(0, false).getString()); + if (!nameMatch.matches()) continue; + Matcher scanMatch = scan.matcher(text.getMessage(1, false).getString()); + if (scanMatch.matches()) signs.put(pos, text); } } } } return signs; } - public HashMap scanForSigns(Pattern scan) { - return scanForSigns(Pattern.compile("(PLAYER|ENTITY) EVENT|FUNCTION|PROCESS"),scan); + + public HashMap scanForSigns(Pattern scan) { + return scanForSigns(Pattern.compile("(PLAYER|ENTITY) EVENT|FUNCTION|PROCESS"), scan); } public BlockPos findFreePlacePos() { - return findFreePlacePos(new BlockPos(originX-1,5,originZ)); + return findFreePlacePos(new BlockPos(originX - 1, 5, originZ)); } public BlockPos findFreePlacePos(BlockPos origin) { - if(originX == null || CodeClient.MC.world == null) return null; + if (originX == null || CodeClient.MC.world == null) return null; var world = CodeClient.MC.world; - int y = Math.max(origin.getY(),5); + int y = Math.max(origin.getY(), 5); int x = origin.getX(); while (y < 255) { while (originX - x <= 18) { x--; - BlockPos pos = new BlockPos(x,y,originZ); - if(world.getBlockState(pos.east()).isAir() && world.getBlockState(pos.west()).isAir()) return pos; + BlockPos pos = new BlockPos(x, y, originZ); + if (world.getBlockState(pos.east()).isAir() && world.getBlockState(pos.west()).isAir()) return pos; } - y+=5; + y += 5; x = originX - 1; } return null; @@ -177,6 +173,7 @@ public enum Size { MASSIVE(300); public final int size; + Size(int size) { this.size = size; } diff --git a/src/main/java/dev/dfonline/codeclient/location/Spawn.java b/src/main/java/dev/dfonline/codeclient/location/Spawn.java index 537ac297..c9705559 100644 --- a/src/main/java/dev/dfonline/codeclient/location/Spawn.java +++ b/src/main/java/dev/dfonline/codeclient/location/Spawn.java @@ -1,8 +1,5 @@ package dev.dfonline.codeclient.location; -import dev.dfonline.codeclient.CodeClient; -import dev.dfonline.codeclient.config.Config; - public class Spawn extends Location { private boolean hasJustJoined = false; diff --git a/src/main/java/dev/dfonline/codeclient/mixin/MHandledScreens.java b/src/main/java/dev/dfonline/codeclient/mixin/MHandledScreens.java index 7ae68546..5b5723ce 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/MHandledScreens.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/MHandledScreens.java @@ -19,15 +19,17 @@ @Mixin(HandledScreens.class) public class MHandledScreens { - @Shadow @Final private static Map, HandledScreens.Provider> PROVIDERS; + @Shadow + @Final + private static Map, HandledScreens.Provider> PROVIDERS; @Redirect(method = "open", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screen/ingame/HandledScreens;getProvider(Lnet/minecraft/screen/ScreenHandlerType;)Lnet/minecraft/client/gui/screen/ingame/HandledScreens$Provider;")) private static Provider overrideProvider(ScreenHandlerType type) { boolean open = InteractionManager.isOpeningCodeChest; InteractionManager.isOpeningCodeChest = false; - if(open && Config.getConfig().CustomCodeChest != Config.CustomChestMenuType.OFF && type == ScreenHandlerType.GENERIC_9X3) { + if (open && Config.getConfig().CustomCodeChest != Config.CustomChestMenuType.OFF && type == ScreenHandlerType.GENERIC_9X3) { //noinspection rawtypes - return (Provider) (handler, playerInventory, title) -> new CustomChestMenu(new CustomChestHandler(handler.syncId),playerInventory,title); + return (Provider) (handler, playerInventory, title) -> new CustomChestMenu(new CustomChestHandler(handler.syncId), playerInventory, title); } return PROVIDERS.get(type); } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/MKeyboard.java b/src/main/java/dev/dfonline/codeclient/mixin/MKeyboard.java index 0e9d0d0b..3c9302a1 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/MKeyboard.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/MKeyboard.java @@ -24,14 +24,14 @@ public class MKeyboard { @Inject(method = "processF3", at = @At("HEAD"), cancellable = true) private void handleF3(int key, CallbackInfoReturnable cir) { - if(key == stateSwitcherKey) { - if(CodeClient.location instanceof Plot) { + if (key == stateSwitcherKey) { + if (CodeClient.location instanceof Plot) { CodeClient.MC.setScreen(new StateSwitcher()); cir.setReturnValue(true); } } - if(key == speedSwitcherKey) { - if(CodeClient.location instanceof Creator) { + if (key == speedSwitcherKey) { + if (CodeClient.location instanceof Creator) { CodeClient.MC.setScreen(new SpeedSwitcher()); cir.setReturnValue(true); } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/MEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/MEntity.java index 81ad40dd..448d9009 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/MEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/MEntity.java @@ -3,7 +3,6 @@ import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.dev.NoClip; import net.minecraft.entity.Entity; -import net.minecraft.entity.EntityPose; import net.minecraft.entity.MovementType; import net.minecraft.util.math.Vec3d; import org.spongepowered.asm.mixin.Mixin; @@ -15,23 +14,27 @@ @Mixin(Entity.class) public abstract class MEntity { - @Shadow public abstract boolean equals(Object o); - @Shadow public abstract int getId(); + @Shadow + public abstract boolean equals(Object o); - @Shadow public abstract void setPosition(Vec3d pos); + @Shadow + public abstract int getId(); + + @Shadow + public abstract void setPosition(Vec3d pos); @Inject(method = "isInsideWall", at = @At("HEAD"), cancellable = true) private void insideWall(CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls()) cir.setReturnValue(false); + if (NoClip.isIgnoringWalls()) cir.setReturnValue(false); } @Inject(method = "move", at = @At("HEAD"), cancellable = true) private void onMove(MovementType movementType, Vec3d movement, CallbackInfo ci) { - if(!NoClip.isIgnoringWalls()) return; - if(CodeClient.MC.player == null) return; - if(this.getId() != CodeClient.MC.player.getId()) return; + if (!NoClip.isIgnoringWalls()) return; + if (CodeClient.MC.player == null) return; + if (this.getId() != CodeClient.MC.player.getId()) return; Vec3d pos = NoClip.handleClientPosition(movement); - if(pos != null) { + if (pos != null) { this.setPosition(pos); ci.cancel(); } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/MLivingEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/MLivingEntity.java index ec107592..be022339 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/MLivingEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/MLivingEntity.java @@ -13,7 +13,7 @@ public class MLivingEntity { @Inject(method = "getJumpVelocity", at = @At("RETURN"), cancellable = true) private void jumpVelocity(CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls() && CodeClient.MC.player.getPitch() <= Config.getConfig().UpAngle - 90) { + if (NoClip.isIgnoringWalls() && CodeClient.MC.player.getPitch() <= Config.getConfig().UpAngle - 90) { cir.setReturnValue(NoClip.getJumpHeight()); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MAbstractClientPlayerEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MAbstractClientPlayerEntity.java index 783842f8..b31cd320 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MAbstractClientPlayerEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MAbstractClientPlayerEntity.java @@ -11,6 +11,6 @@ public class MAbstractClientPlayerEntity { @Inject(method = "isSpectator", at = @At("HEAD"), cancellable = true) public void isSpectator(CallbackInfoReturnable cir) { - if(BuildPhaser.isClipping()) cir.setReturnValue(true); + if (BuildPhaser.isClipping()) cir.setReturnValue(true); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerEntity.java index ad1fba2a..5f7c7766 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerEntity.java @@ -12,7 +12,6 @@ import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket; import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; import net.minecraft.util.math.Vec3d; -import org.java_websocket.enums.Opcode; import org.objectweb.asm.Opcodes; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; @@ -27,9 +26,12 @@ @Mixin(ClientPlayerEntity.class) public abstract class MClientPlayerEntity { - @Shadow @Final public ClientPlayNetworkHandler networkHandler; + @Shadow + @Final + public ClientPlayNetworkHandler networkHandler; - @Shadow private boolean inSneakingPose; + @Shadow + private boolean inSneakingPose; private boolean lastSneaking = false; @Inject(method = "tick", at = @At("HEAD")) @@ -39,35 +41,33 @@ private void tick(CallbackInfo ci) { @Inject(method = "sendMovementPackets", at = @At("HEAD"), cancellable = true) private void sendMovementPackets(CallbackInfo ci) { - if(CodeClient.location instanceof Dev plot) { + if (CodeClient.location instanceof Dev plot) { if (CodeClient.currentAction instanceof MoveToSpawn mts) if (mts.moveModifier()) ci.cancel(); ClientPlayerEntity player = MC.player; if (NoClip.isIgnoringWalls()) { - if(Config.getConfig().TeleportDown && player.getY() % 5 == 0 && !lastSneaking && player.isSneaking() && (player.getPitch() >= 90 - Config.getConfig().DownAngle)) { + if (Config.getConfig().TeleportDown && player.getY() % 5 == 0 && !lastSneaking && player.isSneaking() && (player.getPitch() >= 90 - Config.getConfig().DownAngle)) { Vec3d move = CodeClient.MC.player.getPos().add(0, -5, 0); - if(move.y < plot.getFloorY()) move = new Vec3d(move.x,plot.getFloorY(),move.z); + if (move.y < plot.getFloorY()) move = new Vec3d(move.x, plot.getFloorY(), move.z); if ((!NoClip.isIgnoringWalls()) && NoClip.isInsideWall(move)) move = move.add(0, 2, 0); CodeClient.MC.player.setPosition(move); } ci.cancel(); Vec3d pos = NoClip.handleSeverPosition(); boolean idle = NoClip.timesSinceMoved++ > 40; - if(idle) NoClip.timesSinceMoved = 0; + if (idle) NoClip.timesSinceMoved = 0; float yaw = player.getYaw(); float pitch = player.getPitch(); boolean rotation = pitch != NoClip.lastPitch || yaw != NoClip.lastYaw; boolean position = !pos.equals(NoClip.lastPos) || idle; - if(position || rotation) { - if(position) { + if (position || rotation) { + if (position) { NoClip.timesSinceMoved = 0; - if(rotation) { + if (rotation) { this.networkHandler.sendPacket(new PlayerMoveC2SPacket.Full(pos.x, pos.y, pos.z, yaw, pitch, false)); - } - else { + } else { this.networkHandler.sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(pos.x, pos.y, pos.z, false)); } - } - else { + } else { this.networkHandler.sendPacket(new PlayerMoveC2SPacket.LookAndOnGround(yaw, pitch, false)); } } @@ -86,22 +86,22 @@ private void sendMovementPackets(CallbackInfo ci) { @Inject(method = "pushOutOfBlocks", at = @At("HEAD"), cancellable = true) private void onPushOutOfBlocks(double x, double z, CallbackInfo ci) { - if(NoClip.isIgnoringWalls()) ci.cancel(); + if (NoClip.isIgnoringWalls()) ci.cancel(); } @Inject(method = "shouldSlowDown", at = @At("HEAD"), cancellable = true) private void slowDown(CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls()) cir.setReturnValue(false); + if (NoClip.isIgnoringWalls()) cir.setReturnValue(false); } @Inject(method = "shouldAutoJump", at = @At("HEAD"), cancellable = true) private void autoJump(CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls()) cir.setReturnValue(false); + if (NoClip.isIgnoringWalls()) cir.setReturnValue(false); } @Redirect(method = "tickMovement", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/player/PlayerAbilities;allowFlying:Z", opcode = Opcodes.GETFIELD)) private boolean canFly(PlayerAbilities instance) { - if(InteractionManager.shouldTeleportUp()) return false; + if (InteractionManager.shouldTeleportUp()) return false; return instance.allowFlying; } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerInteractionManager.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerInteractionManager.java index bf90c9b8..4153ef9c 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerInteractionManager.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MClientPlayerInteractionManager.java @@ -41,43 +41,54 @@ @Mixin(ClientPlayerInteractionManager.class) public abstract class MClientPlayerInteractionManager { - @Shadow protected abstract void sendSequencedPacket(ClientWorld world, SequencedPacketCreator packetCreator); - - @Shadow private boolean breakingBlock; - @Shadow private BlockPos currentBreakingPos; - @Shadow private float currentBreakingProgress; - @Shadow private float blockBreakingSoundCooldown; - @Shadow @Final private MinecraftClient client; - - @Shadow public abstract int getBlockBreakingProgress(); - - @Shadow public abstract boolean breakBlock(BlockPos pos); - - @Shadow private int blockBreakingCooldown; - - @Shadow private int lastSelectedSlot; - - @Shadow public abstract void cancelBlockBreaking(); - private static ItemStack item = null; + @Shadow + private boolean breakingBlock; + @Shadow + private BlockPos currentBreakingPos; + @Shadow + private float currentBreakingProgress; + @Shadow + private float blockBreakingSoundCooldown; + @Shadow + @Final + private MinecraftClient client; + @Shadow + private int blockBreakingCooldown; + @Shadow + private int lastSelectedSlot; + + @Shadow + protected abstract void sendSequencedPacket(ClientWorld world, SequencedPacketCreator packetCreator); + + @Shadow + public abstract int getBlockBreakingProgress(); + + @Shadow + public abstract boolean breakBlock(BlockPos pos); + + @Shadow + public abstract void cancelBlockBreaking(); @Inject(method = "breakBlock", at = @At("HEAD"), cancellable = true) public void onBreakBlock(BlockPos pos, CallbackInfoReturnable cir) { - if(InteractionManager.onBreakBlock(pos)) cir.setReturnValue(false); + if (InteractionManager.onBreakBlock(pos)) cir.setReturnValue(false); } @Inject(method = "interactBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;sendSequencedPacket(Lnet/minecraft/client/world/ClientWorld;Lnet/minecraft/client/network/SequencedPacketCreator;)V")) public void beforeSendPlace(ClientPlayerEntity player, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) { ItemStack handItem = player.getStackInHand(hand); boolean isTemplate = handItem.hasNbt() && handItem.getNbt() != null && handItem.getNbt().contains("PublicBukkitValues", NbtElement.COMPOUND_TYPE) && handItem.getNbt().getCompound("PublicBukkitValues").contains("hypercube:codetemplatedata", NbtElement.STRING_TYPE); - if(!isTemplate) return; + if (!isTemplate) return; BlockPos place = InteractionManager.getPlacePos(hitResult); - if(place != null && CodeClient.MC.world.getBlockState(place).isSolidBlock(CodeClient.MC.world, place)) { + if (place != null && CodeClient.MC.world.getBlockState(place).isSolidBlock(CodeClient.MC.world, place)) { ClientPlayNetworkHandler net = CodeClient.MC.getNetworkHandler(); - if(!player.isSneaking()) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); + if (!player.isSneaking()) + net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.PRESS_SHIFT_KEY)); this.sendSequencedPacket(CodeClient.MC.world, sequence -> new PlayerInteractBlockC2SPacket(Hand.MAIN_HAND, hitResult, sequence)); - if(!player.isSneaking()) net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); - if(!player.isSneaking()) { + if (!player.isSneaking()) + net.sendPacket(new ClientCommandC2SPacket(player, ClientCommandC2SPacket.Mode.RELEASE_SHIFT_KEY)); + if (!player.isSneaking()) { this.sendSequencedPacket(CodeClient.MC.world, sequence -> new PlayerInteractBlockC2SPacket(Hand.MAIN_HAND, new BlockHitResult(place.toCenterPos(), Direction.UP, place, hitResult.isInsideBlock()), sequence)); } } @@ -89,7 +100,7 @@ public void beforeSendPlace(ClientPlayerEntity player, Hand hand, BlockHitResult @ModifyVariable(method = "interactBlock", at = @At("HEAD"), argsOnly = true) private BlockHitResult onBlockInteract(BlockHitResult hitResult) { - if(CodeClient.location instanceof Dev plot && plot.isInCodeSpace(hitResult.getBlockPos().getX(), hitResult.getPos().getZ())) { + if (CodeClient.location instanceof Dev plot && plot.isInCodeSpace(hitResult.getBlockPos().getX(), hitResult.getPos().getZ())) { return InteractionManager.onBlockInteract(hitResult); } return hitResult; @@ -97,7 +108,7 @@ private BlockHitResult onBlockInteract(BlockHitResult hitResult) { @Inject(method = "interactBlock", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayerInteractionManager;sendSequencedPacket(Lnet/minecraft/client/world/ClientWorld;Lnet/minecraft/client/network/SequencedPacketCreator;)V", shift = At.Shift.AFTER)) public void afterSendPlace(ClientPlayerEntity player, Hand hand, BlockHitResult hitResult, CallbackInfoReturnable cir) { - if(item != null) { + if (item != null) { Utility.sendHandItem(item); item = null; } @@ -105,43 +116,44 @@ public void afterSendPlace(ClientPlayerEntity player, Hand hand, BlockHitResult @Redirect(method = "interactItem", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayNetworkHandler;sendPacket(Lnet/minecraft/network/packet/Packet;)V")) public void interactItemMovement(ClientPlayNetworkHandler instance, Packet packet) { - if(!NoClip.isIgnoringWalls()) { + if (!NoClip.isIgnoringWalls()) { instance.sendPacket(packet); } } @Inject(method = "interactItem", at = @At("HEAD"), cancellable = true) public void interactItem(PlayerEntity player, Hand hand, CallbackInfoReturnable cir) { - if(InteractionManager.onItemInteract(player, hand)) { + if (InteractionManager.onItemInteract(player, hand)) { cir.setReturnValue(ActionResult.PASS); } } @Inject(method = "clickSlot", at = @At("HEAD"), cancellable = true) private void clickSlot(int syncId, int slotId, int button, SlotActionType actionType, PlayerEntity player, CallbackInfo ci) { - if(slotId < 0) return; - if(!player.isMainPlayer()) return; + if (slotId < 0) return; + if (!player.isMainPlayer()) return; ScreenHandler screenHandler = player.currentScreenHandler; - if(InteractionManager.onClickSlot(screenHandler.slots.get(slotId),button,actionType,syncId,screenHandler.getRevision())) ci.cancel(); + if (InteractionManager.onClickSlot(screenHandler.slots.get(slotId), button, actionType, syncId, screenHandler.getRevision())) + ci.cancel(); } @Inject(method = "getReachDistance", at = @At("HEAD"), cancellable = true) private void reachDistance(CallbackInfoReturnable cir) { - if(CodeClient.location instanceof Dev) { + if (CodeClient.location instanceof Dev) { cir.setReturnValue(Config.getConfig().ReachDistance); } } @Inject(method = "attackBlock", at = @At("HEAD"), cancellable = true) private void attackBlock(BlockPos pos, Direction direction, CallbackInfoReturnable cir) { - if(!Config.getConfig().CustomBlockBreaking) return; - if(CodeClient.location instanceof Dev dev) { - if(Utility.isGlitchStick(CodeClient.MC.player.getMainHandStack())) return; - if(!dev.isInDev(pos)) return; - if(CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) return; + if (!Config.getConfig().CustomBlockBreaking) return; + if (CodeClient.location instanceof Dev dev) { + if (Utility.isGlitchStick(CodeClient.MC.player.getMainHandStack())) return; + if (!dev.isInDev(pos)) return; + if (CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) return; BlockPos breakPos = InteractionManager.isBlockBreakable(pos); - if(breakPos == null) { + if (breakPos == null) { return; } this.breakingBlock = true; @@ -152,18 +164,19 @@ private void attackBlock(BlockPos pos, Direction direction, CallbackInfoReturnab cir.setReturnValue(true); } } + @Inject(method = "updateBlockBreakingProgress", at = @At("HEAD"), cancellable = true) private void updateBlockBreakingProgress(BlockPos pos, Direction direction, CallbackInfoReturnable cir) { - if(!Config.getConfig().CustomBlockBreaking) return; + if (!Config.getConfig().CustomBlockBreaking) return; if (CodeClient.location instanceof Dev dev) { - if(Utility.isGlitchStick(CodeClient.MC.player.getMainHandStack())) return; + if (Utility.isGlitchStick(CodeClient.MC.player.getMainHandStack())) return; if (!dev.isInDev(pos)) return; - if(CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) return; + if (CodeClient.MC.world.getBlockState(pos).getBlock() == Blocks.CHEST) return; cir.cancel(); BlockPos breakPos = InteractionManager.isBlockBreakable(pos); - if(breakPos == null || !breakPos.equals(currentBreakingPos) || !breakingBlock) { + if (breakPos == null || !breakPos.equals(currentBreakingPos) || !breakingBlock) { cancelBlockBreaking(); - CodeClient.MC.interactionManager.attackBlock(pos,direction); + CodeClient.MC.interactionManager.attackBlock(pos, direction); return; } this.currentBreakingProgress += BlockBreakDeltaCalculator.calculateBlockDelta(breakPos); diff --git a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MPlayerEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MPlayerEntity.java index 7922488b..6614e9bf 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MPlayerEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/entity/player/MPlayerEntity.java @@ -8,7 +8,6 @@ import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.Vec3d; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @@ -18,14 +17,14 @@ public abstract class MPlayerEntity { @Inject(method = "getOffGroundSpeed", at = @At("HEAD"), cancellable = true) private void getAirSpeed(CallbackInfoReturnable cir) { - if(NoClip.isInDevSpace() && !CodeClient.MC.player.getAbilities().flying) { + if (NoClip.isInDevSpace() && !CodeClient.MC.player.getAbilities().flying) { cir.setReturnValue(0.026F * (CodeClient.MC.player.getMovementSpeed() * Config.getConfig().AirSpeed)); } } - @Inject(method = "jump",at = @At("HEAD"), cancellable = true) + @Inject(method = "jump", at = @At("HEAD"), cancellable = true) private void jump(CallbackInfo ci) { - if(InteractionManager.shouldTeleportUp()) { + if (InteractionManager.shouldTeleportUp()) { Vec3d move = CodeClient.MC.player.getPos().add(0, 5, 0); if ((!NoClip.isIgnoringWalls()) && NoClip.isInsideWall(move)) move = move.add(0, 2, 0); CodeClient.MC.player.setPosition(move); @@ -35,6 +34,6 @@ private void jump(CallbackInfo ci) { @Inject(method = "canChangeIntoPose", at = @At("HEAD"), cancellable = true) private void canChangeIntoPose(EntityPose pose, CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls()) cir.setReturnValue(true); + if (NoClip.isIgnoringWalls()) cir.setReturnValue(true); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/network/MClientCommonPlayNetworkHandler.java b/src/main/java/dev/dfonline/codeclient/mixin/network/MClientCommonPlayNetworkHandler.java index 23b5d32e..49347f0a 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/network/MClientCommonPlayNetworkHandler.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/network/MClientCommonPlayNetworkHandler.java @@ -12,6 +12,6 @@ public abstract class MClientCommonPlayNetworkHandler { @Inject(method = "sendPacket", at = @At("HEAD"), cancellable = true) private void sendPacket(Packet packet, CallbackInfo ci) { - if(CodeClient.onSendPacket(packet)) ci.cancel(); + if (CodeClient.onSendPacket(packet)) ci.cancel(); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/network/MClientConnection.java b/src/main/java/dev/dfonline/codeclient/mixin/network/MClientConnection.java index cd22b2b3..ac4ea791 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/network/MClientConnection.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/network/MClientConnection.java @@ -1,11 +1,9 @@ package dev.dfonline.codeclient.mixin.network; import dev.dfonline.codeclient.CodeClient; -import dev.dfonline.codeclient.Event; -import dev.dfonline.codeclient.dev.Debug.Debug; import net.minecraft.network.ClientConnection; -import net.minecraft.network.packet.Packet; import net.minecraft.network.listener.PacketListener; +import net.minecraft.network.packet.Packet; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; @@ -15,6 +13,6 @@ public class MClientConnection { @Inject(method = "handlePacket", at = @At("HEAD"), cancellable = true) private static void handlePacket(Packet packet, net.minecraft.network.listener.PacketListener listener, CallbackInfo ci) { - if(CodeClient.handlePacket(packet)) ci.cancel(); + if (CodeClient.handlePacket(packet)) ci.cancel(); } } \ No newline at end of file diff --git a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MDrawContext.java b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MDrawContext.java index 9b01c566..3592a7ed 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MDrawContext.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MDrawContext.java @@ -22,18 +22,21 @@ @Mixin(DrawContext.class) public abstract class MDrawContext { - @Shadow @Final private MatrixStack matrices; + @Shadow + @Final + private MatrixStack matrices; - @Shadow public abstract int drawText(TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow); + @Shadow + public abstract int drawText(TextRenderer textRenderer, Text text, int x, int y, int color, boolean shadow); @Inject(method = "drawItemInSlot(Lnet/minecraft/client/font/TextRenderer;Lnet/minecraft/item/ItemStack;IILjava/lang/String;)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/util/math/MatrixStack;push()V", shift = At.Shift.AFTER)) private void additionalItemRendering(TextRenderer textRenderer, ItemStack stack, int x, int y, String countOverride, CallbackInfo ci) { NbtCompound nbt = stack.getNbt(); - if(nbt == null) return; + if (nbt == null) return; NbtCompound pbv = (NbtCompound) nbt.get("PublicBukkitValues"); - if(pbv == null) return; + if (pbv == null) return; NbtString varItem = (NbtString) pbv.get("hypercube:varitem"); - if(varItem == null) return; + if (varItem == null) return; JsonObject var = JsonParser.parseString(varItem.asString()).getAsJsonObject(); JsonObject data = var.get("data").getAsJsonObject(); Text text = null; @@ -42,28 +45,26 @@ private void additionalItemRendering(TextRenderer textRenderer, ItemStack stack, try { Scope scope = Scope.valueOf(data.get("scope").getAsString()); text = Text.literal((Config.getConfig().UseIForLineScope && scope == Scope.line) ? "I" : scope.shortName).setStyle(Style.EMPTY.withColor(scope.color)); - } - catch (Exception ignored) { + } catch (Exception ignored) { text = Text.literal("?").formatted(Formatting.DARK_RED); } break; } case "num": { String name = data.get("name").getAsString(); - if(textRenderer.getWidth(Text.of(name)) > 16) { - var avail = textRenderer.trimToWidth(name,16-2); - text = Text.literal(avail).formatted(Formatting.RED).append(Text.literal(".".repeat((16-textRenderer.getWidth(Text.of(avail))) / 2)).formatted(Formatting.WHITE)); - } - else text = Text.literal(name).formatted(Formatting.RED); + if (textRenderer.getWidth(Text.of(name)) > 16) { + var avail = textRenderer.trimToWidth(name, 16 - 2); + text = Text.literal(avail).formatted(Formatting.RED).append(Text.literal(".".repeat((16 - textRenderer.getWidth(Text.of(avail))) / 2)).formatted(Formatting.WHITE)); + } else text = Text.literal(name).formatted(Formatting.RED); break; } default: { return; } } - if(text == null) return; + if (text == null) return; this.matrices.translate(0.0F, 0.0F, 200.0F); - this.drawText(textRenderer,text,x,y,0xFFFFFF,true); + this.drawText(textRenderer, text, x, y, 0xFFFFFF, true); matrices.translate(0.0F, 0.0F, -200.0F); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameHud.java b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameHud.java index 3426f4e7..692ffd69 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameHud.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameHud.java @@ -19,18 +19,20 @@ @Mixin(InGameHud.class) public abstract class MInGameHud { - @Shadow public abstract TextRenderer getTextRenderer(); + @Shadow + private int scaledHeight; + @Shadow + private int scaledWidth; - @Shadow private int scaledHeight; - - @Shadow private int scaledWidth; + @Shadow + public abstract TextRenderer getTextRenderer(); @Inject(method = "render", at = @At("HEAD")) private void onRender(DrawContext context, float tickDelta, CallbackInfo ci) { TextRenderer textRenderer = getTextRenderer(); List overlay = List.copyOf(OverlayManager.getOverlayText()); - if(!overlay.isEmpty()) { + if (!overlay.isEmpty()) { int index = 0; for (Text text : overlay) { context.drawTextWithShadow(textRenderer, Objects.requireNonNullElseGet(text, () -> Text.literal("NULL")), 30, 30 + (index * 9), -1); @@ -41,13 +43,13 @@ private void onRender(DrawContext context, float tickDelta, CallbackInfo ci) { int yOrig = (scaledHeight / 2) + Config.getConfig().ChestPeekerY; try { List peeker = ChestPeeker.getOverlayText(); - if(peeker == null) peeker = SignPeeker.getOverlayText(); - if(peeker != null && !peeker.isEmpty()) { - context.drawTooltip(textRenderer,peeker,x,yOrig); + if (peeker == null) peeker = SignPeeker.getOverlayText(); + if (peeker != null && !peeker.isEmpty()) { + context.drawTooltip(textRenderer, peeker, x, yOrig); } } catch (Exception ignored) { - context.drawTooltip(textRenderer,Text.literal("An error occurred"),x,yOrig); + context.drawTooltip(textRenderer, Text.literal("An error occurred"), x, yOrig); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameOverlayRenderer.java b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameOverlayRenderer.java index c89e4098..495321f8 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameOverlayRenderer.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MInGameOverlayRenderer.java @@ -13,6 +13,6 @@ public class MInGameOverlayRenderer { @Inject(method = "getInWallBlockState", at = @At("HEAD"), cancellable = true) private static void inWall(PlayerEntity player, CallbackInfoReturnable cir) { - if(NoClip.isIgnoringWalls()) cir.setReturnValue(null); + if (NoClip.isIgnoringWalls()) cir.setReturnValue(null); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MTitleScreen.java b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MTitleScreen.java index 6d946b52..d367ca6c 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MTitleScreen.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/render/hud/MTitleScreen.java @@ -15,11 +15,11 @@ public class MTitleScreen { @Inject(method = "init", at = @At("RETURN")) public void onInit(CallbackInfo ci) { - if(CodeClient.autoJoin == CodeClient.AutoJoin.GAME) { + if (CodeClient.autoJoin == CodeClient.AutoJoin.GAME) { ServerInfo info = new ServerInfo("DiamondFire", Config.getConfig().AutoNode.prepend + "mcdiamondfire.com", ServerInfo.ServerType.OTHER); - ConnectScreen.connect((TitleScreen)(Object)this, CodeClient.MC, ServerAddress.parse(info.address), info, true); + ConnectScreen.connect((TitleScreen) (Object) this, CodeClient.MC, ServerAddress.parse(info.address), info, true); - CodeClient.autoJoin =Config.getConfig().AutoJoinPlot ? CodeClient.AutoJoin.PLOT : CodeClient.AutoJoin.NONE; + CodeClient.autoJoin = Config.getConfig().AutoJoinPlot ? CodeClient.AutoJoin.PLOT : CodeClient.AutoJoin.NONE; } } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/MWorldRenderer.java b/src/main/java/dev/dfonline/codeclient/mixin/world/MWorldRenderer.java index 247a0d2f..86b9dd9a 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/MWorldRenderer.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/MWorldRenderer.java @@ -15,14 +15,18 @@ @Mixin(WorldRenderer.class) public class MWorldRenderer { - @Shadow @Final private MinecraftClient client; + @Shadow + @Final + private MinecraftClient client; - @Shadow @Nullable private ClientWorld world; + @Shadow + @Nullable + private ClientWorld world; @Redirect(method = "render", at = @At(value = "INVOKE", target = "Lnet/minecraft/block/BlockState;isAir()Z")) private boolean isAir(BlockState instance) { - if(client.crosshairTarget instanceof BlockHitResult hitResult) { - if(InteractionManager.customVoxelShape(world, hitResult.getBlockPos()) != null) return false; + if (client.crosshairTarget instanceof BlockHitResult hitResult) { + if (InteractionManager.customVoxelShape(world, hitResult.getBlockPos()) != null) return false; } return instance.isAir(); } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MAbstractBlockState.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MAbstractBlockState.java index 195cf64a..655d42c0 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MAbstractBlockState.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MAbstractBlockState.java @@ -15,11 +15,12 @@ @Mixin(AbstractBlockState.class) public abstract class MAbstractBlockState { - @Shadow public abstract Block getBlock(); + @Shadow + public abstract Block getBlock(); @Inject(method = "getOutlineShape(Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/ShapeContext;)Lnet/minecraft/util/shape/VoxelShape;", at = @At("HEAD"), cancellable = true) private void onGetOutlineShape(BlockView world, BlockPos pos, ShapeContext context, CallbackInfoReturnable cir) { VoxelShape shape = InteractionManager.customVoxelShape(world, pos); - if(shape != null) cir.setReturnValue(shape); + if (shape != null) cir.setReturnValue(shape); } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBarrierBlock.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBarrierBlock.java index 40aadad0..6af98f84 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBarrierBlock.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBarrierBlock.java @@ -2,9 +2,7 @@ import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.config.Config; -import dev.dfonline.codeclient.location.Build; import dev.dfonline.codeclient.location.Creator; -import dev.dfonline.codeclient.location.Dev; import net.minecraft.block.BarrierBlock; import net.minecraft.block.BlockRenderType; import net.minecraft.block.BlockState; diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlock.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlock.java index 1a236813..e94c3617 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlock.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlock.java @@ -11,7 +11,6 @@ import net.minecraft.block.entity.SignText; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; -import net.minecraft.world.BlockView; import net.minecraft.world.WorldView; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; @@ -24,23 +23,23 @@ public class MBlock { @Inject(method = "getPickStack", at = @At("HEAD"), cancellable = true) private void getPickStack(WorldView world, BlockPos pos, BlockState state, CallbackInfoReturnable cir) { - if(!Config.getConfig().PickAction) return; - if(CodeClient.location instanceof Dev dev) { - if(!dev.isInDev(pos)) return; + if (!Config.getConfig().PickAction) return; + if (CodeClient.location instanceof Dev dev) { + if (!dev.isInDev(pos)) return; var breakable = InteractionManager.isBlockBreakable(pos); - if(breakable == null) return; + if (breakable == null) return; var sign = breakable.west(1); - if(CodeClient.MC.world.getBlockEntity(sign) instanceof SignBlockEntity signBlock) + if (CodeClient.MC.world.getBlockEntity(sign) instanceof SignBlockEntity signBlock) try { SignText text = signBlock.getFrontText(); var actiondump = ActionDump.getActionDump(); var action = Arrays.stream(actiondump.actions).filter(a -> a.codeblockName.equals(text.getMessage(0, false).getString()) && - a.name.equals(text.getMessage(1, false).getString())).findFirst(); - if(action.isEmpty()) return; + a.name.equals(text.getMessage(1, false).getString())).findFirst(); + if (action.isEmpty()) return; cir.setReturnValue(action.get().getItem()); + } catch (Exception ignored) { } - catch (Exception ignored) {} } } } \ No newline at end of file diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlockItem.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlockItem.java index 7d91d2c9..f5c2e651 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlockItem.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MBlockItem.java @@ -2,7 +2,6 @@ import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.config.Config; -import dev.dfonline.codeclient.dev.NoClip; import dev.dfonline.codeclient.location.Dev; import net.minecraft.block.BlockState; import net.minecraft.item.BlockItem; @@ -17,9 +16,9 @@ public class MBlockItem { @Inject(method = "place(Lnet/minecraft/item/ItemPlacementContext;Lnet/minecraft/block/BlockState;)Z", at = @At("HEAD"), cancellable = true) private void onPlace(ItemPlacementContext context, BlockState state, CallbackInfoReturnable cir) { - if(CodeClient.location instanceof Dev dev && Config.getConfig().CustomBlockInteractions) { + if (CodeClient.location instanceof Dev dev && Config.getConfig().CustomBlockInteractions) { BlockPos pos = context.getBlockPos(); - if(dev.isInCodeSpace(pos.getX(), pos.getZ())) cir.setReturnValue(true); + if (dev.isInCodeSpace(pos.getX(), pos.getZ())) cir.setReturnValue(true); } } } diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MLightBlock.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MLightBlock.java index 46580a95..4825cebd 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MLightBlock.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MLightBlock.java @@ -2,9 +2,7 @@ import dev.dfonline.codeclient.CodeClient; import dev.dfonline.codeclient.config.Config; -import dev.dfonline.codeclient.location.Build; import dev.dfonline.codeclient.location.Creator; -import dev.dfonline.codeclient.location.Dev; import net.minecraft.block.BlockRenderType; import net.minecraft.block.BlockState; import net.minecraft.block.LightBlock; diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MSignBlockEntity.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MSignBlockEntity.java index 6efe69f8..8d36580a 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MSignBlockEntity.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MSignBlockEntity.java @@ -18,27 +18,33 @@ @Mixin(SignBlockEntity.class) public abstract class MSignBlockEntity { - @Shadow private SignText frontText; + @Shadow + private SignText frontText; @Inject(method = "getFrontText", at = @At("HEAD"), cancellable = true) public void getFrontText(CallbackInfoReturnable cir) { - if(CodeClient.location instanceof Dev plot) { - if(plot.isInDev(((BlockEntity)(Object)this).getPos())) { + if (CodeClient.location instanceof Dev plot) { + if (plot.isInDev(((BlockEntity) (Object) this).getPos())) { SignText orig = this.frontText; - Text line1 = orig.getMessage(0,false); - Text line2 = orig.getMessage(1,false); - Text line3 = orig.getMessage(2,false); - Text line4 = orig.getMessage(3,false); + Text line1 = orig.getMessage(0, false); + Text line2 = orig.getMessage(1, false); + Text line3 = orig.getMessage(2, false); + Text line4 = orig.getMessage(3, false); Config config = Config.getConfig(); TextColor color3 = null; - if(Config.getConfig().UseSelectionColor) try {color3 = Target.valueOf(line3.getString()).color;} catch (Exception ignored) {} - if(color3 == null && config.Line3Color != 0) color3 = TextColor.fromRgb(config.Line3Color); - if(config.Line1Color != 0) line1 = Text.empty().append(line1).setStyle(Style.EMPTY.withColor(config.Line1Color)); - if(config.Line2Color != 0) line2 = Text.empty().append(line2).setStyle(Style.EMPTY.withColor(config.Line2Color)); - if(color3 != null) line3 = Text.empty().append(line3).setStyle(Style.EMPTY.withColor(color3 )); - if(config.Line4Color != 0) line4 = Text.empty().append(line4).setStyle(Style.EMPTY.withColor(config.Line4Color)); - + if (Config.getConfig().UseSelectionColor) try { + color3 = Target.valueOf(line3.getString()).color; + } catch (Exception ignored) { + } + if (color3 == null && config.Line3Color != 0) color3 = TextColor.fromRgb(config.Line3Color); + if (config.Line1Color != 0) + line1 = Text.empty().append(line1).setStyle(Style.EMPTY.withColor(config.Line1Color)); + if (config.Line2Color != 0) + line2 = Text.empty().append(line2).setStyle(Style.EMPTY.withColor(config.Line2Color)); + if (color3 != null) line3 = Text.empty().append(line3).setStyle(Style.EMPTY.withColor(color3)); + if (config.Line4Color != 0) + line4 = Text.empty().append(line4).setStyle(Style.EMPTY.withColor(config.Line4Color)); cir.setReturnValue( diff --git a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MStructureVoidBlock.java b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MStructureVoidBlock.java index f626882c..d3ed54aa 100644 --- a/src/main/java/dev/dfonline/codeclient/mixin/world/block/MStructureVoidBlock.java +++ b/src/main/java/dev/dfonline/codeclient/mixin/world/block/MStructureVoidBlock.java @@ -5,7 +5,6 @@ import dev.dfonline.codeclient.location.Creator; import net.minecraft.block.BlockRenderType; import net.minecraft.block.BlockState; -import net.minecraft.block.LightBlock; import net.minecraft.block.StructureVoidBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; diff --git a/src/main/java/dev/dfonline/codeclient/switcher/GenericSwitcher.java b/src/main/java/dev/dfonline/codeclient/switcher/GenericSwitcher.java index 48ccd052..060fe5c0 100644 --- a/src/main/java/dev/dfonline/codeclient/switcher/GenericSwitcher.java +++ b/src/main/java/dev/dfonline/codeclient/switcher/GenericSwitcher.java @@ -24,14 +24,6 @@ public abstract class GenericSwitcher extends Screen { private static final Identifier TEXTURE = new Identifier("textures/gui/container/gamemode_switcher.png"); private static final Identifier SLOT_TEXTURE = new Identifier("gamemode_switcher/slot"); private static final Identifier SELECTED_TEXTURE = new Identifier("gamemode_switcher/selection"); - private final List buttons = new ArrayList<>(); - private boolean usingMouseToSelect = false; - protected boolean hasClicked = false; - private Integer lastMouseX; - private Integer lastMouseY; - protected Integer selected; - protected Text footer = Text.translatable("codeclient.switcher.footer"); - /** * Key to hold down, generally F3. * The selected option will be run when this is released. @@ -41,6 +33,13 @@ public abstract class GenericSwitcher extends Screen { * The key to open and select the next option. */ public final int PRESS_KEY; + private final List buttons = new ArrayList<>(); + protected boolean hasClicked = false; + protected Integer selected; + protected Text footer = Text.translatable("codeclient.switcher.footer"); + private boolean usingMouseToSelect = false; + private Integer lastMouseX; + private Integer lastMouseY; protected GenericSwitcher(Text title, int holdKey, int pressKey) { super(title); @@ -59,14 +58,14 @@ protected void init() { int width = options.size() * 31 - 5; int i = 0; for (Option option : options) { - this.buttons.add(new SelectableButtonWidget(option,this.width / 2 - width / 2 + i * 31, this.height / 2 - 31)); + this.buttons.add(new SelectableButtonWidget(option, this.width / 2 - width / 2 + i * 31, this.height / 2 - 31)); ++i; } } @Override public void render(DrawContext context, int mouseX, int mouseY, float delta) { - if(checkFinished()) return; + if (checkFinished()) return; context.getMatrices().push(); RenderSystem.enableBlend(); int centerX = this.width / 2 - 62; @@ -75,11 +74,11 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta) { context.getMatrices().pop(); super.render(context, mouseX, mouseY, delta); - if(lastMouseX == null) lastMouseX = mouseX; - if(lastMouseY == null) lastMouseY = mouseY; + if (lastMouseX == null) lastMouseX = mouseX; + if (lastMouseY == null) lastMouseY = mouseY; - if(!usingMouseToSelect) { - if(this.lastMouseX != mouseX || this.lastMouseY != mouseY) this.usingMouseToSelect = true; + if (!usingMouseToSelect) { + if (this.lastMouseX != mouseX || this.lastMouseY != mouseY) this.usingMouseToSelect = true; lastMouseX = mouseX; lastMouseY = mouseY; } @@ -93,12 +92,12 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta) { int i = 0; for (SelectableButtonWidget button : buttons) { - if(usingMouseToSelect) { - if(button.getX() < mouseX && button.getX() + 31 > mouseX) this.selected = i; + if (usingMouseToSelect) { + if (button.getX() < mouseX && button.getX() + 31 > mouseX) this.selected = i; } button.selected = this.selected == i; context.drawGuiTexture(SLOT_TEXTURE, button.getX(), button.getY(), 26, 26); - if(button.selected) context.drawGuiTexture(SELECTED_TEXTURE, button.getX(), button.getY(), 26, 26); + if (button.selected) context.drawGuiTexture(SELECTED_TEXTURE, button.getX(), button.getY(), 26, 26); button.render(context, mouseX, mouseY, delta); ++i; } @@ -109,13 +108,13 @@ public void renderBackground(DrawContext context, int mouseX, int mouseY, float @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { - if(keyCode == PRESS_KEY) { + if (keyCode == PRESS_KEY) { this.usingMouseToSelect = false; - this.selected ++; + this.selected++; this.selected %= getOptions().size(); return true; } - if(keyCode == GLFW.GLFW_KEY_ESCAPE) { + if (keyCode == GLFW.GLFW_KEY_ESCAPE) { this.close(); } return super.keyPressed(keyCode, scanCode, modifiers); @@ -126,10 +125,10 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { int i = 0; for (SelectableButtonWidget widget : buttons) { - if(widget.getX() < mouseX && widget.getX() + 31 > mouseX + if (widget.getX() < mouseX && widget.getX() + 31 > mouseX && widget.getY() < mouseY && widget.getY() + 31 > mouseY) this.selected = i; widget.selected = this.selected == i; - if(widget.selected) { + if (widget.selected) { hasClicked = true; return true; } @@ -139,10 +138,10 @@ public boolean mouseClicked(double mouseX, double mouseY, int button) { } protected boolean checkFinished() { - if(this.client == null) return false; - if(hasClicked || !InputUtil.isKeyPressed(this.client.getWindow().getHandle(), HOLD_KEY)) { + if (this.client == null) return false; + if (hasClicked || !InputUtil.isKeyPressed(this.client.getWindow().getHandle(), HOLD_KEY)) { Option selected = getSelected(); - if(selected != null) selected.run(); + if (selected != null) selected.run(); this.client.setScreen(null); return true; } @@ -151,15 +150,25 @@ protected boolean checkFinished() { protected Option getSelected() { List