package com.dairymoose.modernlife.core;

import com.dairymoose.entity.BicycleEntity;
import com.dairymoose.entity.BicycleModel;
import com.dairymoose.entity.BicycleRenderer;
import com.dairymoose.entity.DummyEntity;
import com.dairymoose.entity.DummyRenderer;
import com.dairymoose.entity.MotorboatEntity;
import com.dairymoose.entity.MotorboatModel;
import com.dairymoose.entity.MotorboatRenderer;
import com.dairymoose.entity.projectile.ThrownSeedEntity;
import com.dairymoose.inventory.container.TrashCanContainer;
import com.dairymoose.modernlife.blocks.CCTVCameraBlock;
import com.dairymoose.modernlife.blocks.MirrorBlock;
import com.dairymoose.modernlife.blocks.ModernBookshelfBlock;
import com.dairymoose.modernlife.blocks.gui.EaselScreen;
import com.dairymoose.modernlife.blocks.gui.TrashCanScreen;
import com.dairymoose.modernlife.items.CameraItem;
import com.dairymoose.modernlife.items.ChainsawItem;
import com.dairymoose.modernlife.items.FlashlightItem;
import com.dairymoose.modernlife.items.HandgunItem;
import com.dairymoose.modernlife.items.SpeedometerItem;
import com.dairymoose.modernlife.network.play.client.ServerboundCanvasChecksumPacket;
import com.dairymoose.modernlife.network.play.client.ServerboundMultipartCameraPacket;
import com.dairymoose.modernlife.network.play.client.ServerboundRequestCanvasPacket;
import com.dairymoose.modernlife.network.play.client.ServerboundStopUsingCameraPacket;
import com.dairymoose.modernlife.renderer.tileentity.AlarmClockBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.CanvasBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.ChessBoardBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.MicrowaveBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.MirrorBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.ModernBookshelfBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.StoveBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.WallShelfBlockEntityRenderer;
import com.dairymoose.modernlife.renderer.tileentity.WinchBlockEntityRenderer;
import com.dairymoose.modernlife.tileentities.AlarmClockBlockEntity;
import com.dairymoose.modernlife.tileentities.CCTVCameraBlockEntity;
import com.dairymoose.modernlife.tileentities.CanvasBlockEntity;
import com.dairymoose.modernlife.tileentities.ChessBoardBlockEntity;
import com.dairymoose.modernlife.tileentities.MicrowaveBlockEntity;
import com.dairymoose.modernlife.tileentities.MirrorBlockEntity;
import com.dairymoose.modernlife.tileentities.ModernBookshelfBlockEntity;
import com.dairymoose.modernlife.tileentities.PowerReceiverBlockEntity;
import com.dairymoose.modernlife.tileentities.PowerTransmitterBlockEntity;
import com.dairymoose.modernlife.tileentities.StoveBlockEntity;
import com.dairymoose.modernlife.tileentities.WallShelfBlockEntity;
import com.dairymoose.modernlife.tileentities.WinchBlockEntity;
import com.dairymoose.modernlife.util.CanvasData;
import com.mojang.blaze3d.pipeline.RenderTarget;
import com.mojang.blaze3d.pipeline.TextureTarget;
import com.mojang.blaze3d.platform.Window;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.datafixers.util.Either;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectListIterator;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import net.minecraft.Util;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColor;
import net.minecraft.client.color.item.ItemColor;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.model.HumanoidModel;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.chunk.ChunkRenderDispatcher;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.client.renderer.entity.ItemRenderer;
import net.minecraft.client.renderer.entity.ThrownItemRenderer;
import net.minecraft.client.renderer.item.ItemProperties;
import net.minecraft.client.renderer.item.ItemPropertyFunction;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.core.Vec3i;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.event.ClientPlayerNetworkEvent;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.client.event.DrawSelectionEvent;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.InputEvent;
import net.minecraftforge.client.event.MovementInputUpdateEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderLevelLastEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderTooltipEvent;
import net.minecraftforge.client.gui.ForgeIngameGui;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraftforge.forgespi.locating.IModFile;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.lwjgl.opengl.GL30;

@OnlyIn(Dist.CLIENT)
/* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient.class */
public class ModernLifeClient {
    public static final String MODID = "modernlife";
    private static final boolean ON_OSX;
    public static CCTVCameraBlockEntity cctvCurrentCamera;
    public static List<BulletHoleInfo> bulletHoles;
    private static Boolean originalFastRender;
    static float cameraZoomFactor;
    private static final int CANVAS_CACHE_EXPIRY_MINUTES = 30;
    private static Map<Long, CachedCanvasData> cachedData;
    private static Map<Long, Long> uniqueIdToTimestampMap;
    private static Map<Long, Long> uniqueIdToTimestampChecksumMap;
    static double originalFov;
    private static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, "modernlife");
    private static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "modernlife");
    private static final DeferredRegister<BlockEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, "modernlife");
    private static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, "modernlife");
    private static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, "modernlife");
    private static final DeferredRegister<MenuType<?>> CONTAINERS = DeferredRegister.create(ForgeRegistries.CONTAINERS, "modernlife");
    private static final Logger LOGGER = LogManager.getLogger();
    private ResourceLocation CAMERA_VIEWFINDER_LOCATION = new ResourceLocation("modernlife", "textures/item/camera_viewfinder.png");
    private int CAMERA_VIEWFINDER_WIDTH = 256;
    private int CAMERA_VIEWFINDER_HEIGHT = 256;
    private ResourceLocation GUI_MOTORBOAT_LOCATION = new ResourceLocation("modernlife", "textures/gui/gui_motorboat.png");
    private int GUI_MOTORBOAT_TEX_SIZE = 32;
    private int GUI_MOTORBOAT_BORDER_HEIGHT = 8;
    private ResourceLocation BULLET_HOLE_1_TEX = new ResourceLocation("modernlife", "textures/item/bullet_hole_1.png");
    private ResourceLocation BULLET_HOLE_2_TEX = new ResourceLocation("modernlife", "textures/item/bullet_hole_2.png");
    private ResourceLocation BULLET_HOLE_3_TEX = new ResourceLocation("modernlife", "textures/item/bullet_hole_3.png");
    private int BULLET_HOLE_TEX_SIZE = 32;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Queue<BlockEvent.NeighborNotifyEvent> snowEvents = new LinkedList();
    int capturedWidth = 0;
    int capturedHeight = 0;
    private boolean isMirrorRendering = false;
    DummyEntity currentMirrorCamera = null;
    private int renderTicker = 0;
    private boolean foundMirror = false;

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$BulletHoleInfo.class */
    public static class BulletHoleInfo {
        public BlockPos pos;
        public Vec3 loc;
        public int holeNo;
        public String dim;
        public Direction facing;
        public long timestamp;
        public Double randomDepth;
    }

    static {
        ON_OSX = Util.getPlatform() == Util.OS.OSX;
        cctvCurrentCamera = null;
        bulletHoles = new ArrayList();
        originalFastRender = null;
        cameraZoomFactor = 1.0f;
        cachedData = new ConcurrentHashMap();
        uniqueIdToTimestampMap = new ConcurrentHashMap();
        uniqueIdToTimestampChecksumMap = new ConcurrentHashMap();
        originalFov = -1.0d;
    }

    public ModernLifeClient() {
        new ModernLifeCommon();
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerBlockColors);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::registerItemColors);
        MinecraftForge.EVENT_BUS.register(this);
    }

    @OnlyIn(Dist.CLIENT)
    private void registerBlockEntityRenderers() {
        BlockEntityRenderers.register(CanvasBlockEntity.CANVAS, CanvasBlockEntityRenderer::new);
        BlockEntityRenderers.register(MicrowaveBlockEntity.MICROWAVE, MicrowaveBlockEntityRenderer::new);
        BlockEntityRenderers.register(StoveBlockEntity.STOVE, StoveBlockEntityRenderer::new);
        BlockEntityRenderers.register(ChessBoardBlockEntity.CHESS_BOARD, ChessBoardBlockEntityRenderer::new);
        BlockEntityRenderers.register(MirrorBlockEntity.MIRROR, MirrorBlockEntityRenderer::new);
        BlockEntityRenderers.register(AlarmClockBlockEntity.ALARM_CLOCK, AlarmClockBlockEntityRenderer::new);
        BlockEntityRenderers.register(WallShelfBlockEntity.WALL_SHELF, WallShelfBlockEntityRenderer::new);
        BlockEntityRenderers.register(WallShelfBlockEntity.DOUBLE_WALL_SHELF, WallShelfBlockEntityRenderer::new);
        BlockEntityRenderers.register(WinchBlockEntity.WINCH, WinchBlockEntityRenderer::new);
        BlockEntityRenderers.register(ModernBookshelfBlockEntity.MODERN_BOOKSHELF, ModernBookshelfBlockEntityRenderer::new);
    }

    private void doClientStuff(FMLClientSetupEvent event) {
        AutoRegisterProcessor.processAnnotations(BLOCKS, ITEMS, CustomBlocks.class);
        MenuScreens.register(TrashCanContainer.TRASH_CAN_CONTAINER_TYPE, TrashCanScreen::new);
        MinecraftForgeClient.registerTooltipComponentFactory(CanvasPreviewComponent.class, x -> {
            return x;
        });
        ForgeHooksClient.registerLayerDefinition(BicycleModel.BICYCLE, BicycleModel::createBodyLayer);
        ForgeHooksClient.registerLayerDefinition(MotorboatModel.MOTORBOAT, MotorboatModel::createBodyLayer);
        registerBlockEntityRenderers();
        AutoRegisterProcessor.processRenderTypes(CustomBlocks.class);
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_BIRCH_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_CRIMSON_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_DARK_OAK_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_IRON_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_JUNGLE_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_OAK_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_SPRUCE_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_WARPED_GLASS_DOOR.get(), RenderType.translucent());
        ItemBlockRenderTypes.setRenderLayer(CustomBlocks.BLOCK_EXTRACTOR.get(), RenderType.translucent());
        EntityRenderers.register(ThrownSeedEntity.THROWN_SEED_ENTITY, context -> {
            return new ThrownItemRenderer(context);
        });
        EntityRenderers.register(BicycleEntity.BICYCLE_ENTITY, context2 -> {
            return new BicycleRenderer(context2);
        });
        EntityRenderers.register(MotorboatEntity.MOTORBOAT_ENTITY, context3 -> {
            return new MotorboatRenderer(context3);
        });
        EntityRenderers.register(DummyEntity.DUMMY_ENTITY, context4 -> {
            return new DummyRenderer(context4);
        });
        ItemProperties.register(CustomBlocks.ITEM_CHAINSAW.get(), new ResourceLocation("modernlife", "running"), new ItemPropertyFunction() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.1
            C01181() {
            }

            public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
                if ((paramItemStack.getItem() instanceof ChainsawItem) && paramLivingEntity != null && paramLivingEntity.isUsingItem() && paramLivingEntity.getUseItem() == paramItemStack) {
                    return 1.0f;
                }
                return 0.0f;
            }
        });
        ItemProperties.register(CustomBlocks.ITEM_HANDGUN.get(), new ResourceLocation("modernlife", "running"), new ItemPropertyFunction() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.2
            C01212() {
            }

            public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
                Integer tickValue;
                if ((paramItemStack.getItem() instanceof HandgunItem) && paramLivingEntity != null && (tickValue = HandgunItem.firingTickMap.get(paramLivingEntity)) != null && tickValue.intValue() >= 4) {
                    return 1.0f;
                }
                return 0.0f;
            }
        });
        ItemProperties.register(CustomBlocks.ITEM_FLASHLIGHT.get(), new ResourceLocation("modernlife", "on"), new ItemPropertyFunction() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.3
            C01223() {
            }

            public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
                Boolean usingFlashlight;
                if (!(paramItemStack.getItem() instanceof FlashlightItem) || paramLivingEntity == null || (usingFlashlight = FlashlightItem.usingFlashlight.get(paramLivingEntity)) == null || !usingFlashlight.booleanValue()) {
                    return 0.0f;
                }
                if (paramItemStack.equals(paramLivingEntity.getMainHandItem()) || paramItemStack.equals(paramLivingEntity.getOffhandItem())) {
                    return 1.0f;
                }
                return 0.0f;
            }
        });
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$1 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$1.class */
    public class C01181 implements ItemPropertyFunction {
        C01181() {
        }

        public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
            if ((paramItemStack.getItem() instanceof ChainsawItem) && paramLivingEntity != null && paramLivingEntity.isUsingItem() && paramLivingEntity.getUseItem() == paramItemStack) {
                return 1.0f;
            }
            return 0.0f;
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$2 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$2.class */
    public class C01212 implements ItemPropertyFunction {
        C01212() {
        }

        public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
            Integer tickValue;
            if ((paramItemStack.getItem() instanceof HandgunItem) && paramLivingEntity != null && (tickValue = HandgunItem.firingTickMap.get(paramLivingEntity)) != null && tickValue.intValue() >= 4) {
                return 1.0f;
            }
            return 0.0f;
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$3 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$3.class */
    public class C01223 implements ItemPropertyFunction {
        C01223() {
        }

        public float call(ItemStack paramItemStack, ClientLevel paramClientLevel, LivingEntity paramLivingEntity, int var4) {
            Boolean usingFlashlight;
            if (!(paramItemStack.getItem() instanceof FlashlightItem) || paramLivingEntity == null || (usingFlashlight = FlashlightItem.usingFlashlight.get(paramLivingEntity)) == null || !usingFlashlight.booleanValue()) {
                return 0.0f;
            }
            if (paramItemStack.equals(paramLivingEntity.getMainHandItem()) || paramItemStack.equals(paramLivingEntity.getOffhandItem())) {
                return 1.0f;
            }
            return 0.0f;
        }
    }

    public static MirrorBlockEntity getChosenMirror() {
        MirrorBlockEntity chosenMirror = null;
        double leastDistance = -1.0d;
        List<BlockPos> posToRemove = new ArrayList<>();
        for (Map.Entry<BlockPos, MirrorBlockEntity> entry : MirrorBlockEntityRenderer.mirrorMap.entrySet()) {
            BlockPos pos = entry.getKey();
            if (entry.getValue().isRemoved()) {
                posToRemove.add(pos);
            }
        }
        Iterator<BlockPos> it = posToRemove.iterator();
        while (it.hasNext()) {
            MirrorBlockEntityRenderer.mirrorMap.remove(it.next());
        }
        LocalPlayer localPlayer = Minecraft.getInstance().player;
        HitResult picked = null;
        if (localPlayer != null) {
            picked = localPlayer.pick(100.0d, 1.0f, false);
        }
        for (Map.Entry<BlockPos, MirrorBlockEntity> entry2 : MirrorBlockEntityRenderer.mirrorMap.entrySet()) {
            BlockPos pos2 = entry2.getKey();
            MirrorBlockEntity mirror = entry2.getValue();
            if (localPlayer != null && picked != null) {
                Vec3 pickedLocation = picked.getLocation();
                double distSqr = pickedLocation.distanceToSqr(pos2.getX() + 0.5d, pos2.getY() + 0.5d, pos2.getZ() + 0.5d);
                double playerDistSqr = localPlayer.distanceToSqr(pos2.getX() + 0.5d, pos2.getY() + 0.5d, pos2.getZ() + 0.5d);
                if (distSqr < 225.0d && playerDistSqr < 225.0d) {
                    if (leastDistance < 0.0d) {
                        chosenMirror = mirror;
                        leastDistance = distSqr;
                    } else if (distSqr < leastDistance) {
                        chosenMirror = mirror;
                        leastDistance = distSqr;
                    }
                }
            }
        }
        return chosenMirror;
    }

    float fixYaw(float yaw) {
        float yaw2 = yaw % 360.0f;
        if (yaw2 > 180.0f) {
            yaw2 -= 360.0f;
        }
        if (yaw2 < -180.0f) {
            yaw2 += 360.0f;
        }
        return yaw2;
    }

    private double getAngularDifferenceTo(Player player, double mirrorX, double mirrorZ) {
        double playerX = player.getX();
        double playerZ = player.getZ();
        double xDiff = playerX - mirrorX;
        double zDiff = playerZ - mirrorZ;
        double angleOfIncidence = Math.toDegrees(Math.atan2(zDiff, xDiff));
        return angleOfIncidence;
    }

    private float getMirrorReflectedYaw(Player player, double mirrorX, double mirrorZ) {
        double angleOfIncidence = getAngularDifferenceTo(player, mirrorX, mirrorZ);
        float reflectedYaw = (float) angleOfIncidence;
        return fixYaw(reflectedYaw + 90.0f);
    }

    public static List<CCTVCameraBlockEntity> eligibleCameras(Player player, BlockPos screenPos) {
        List<CCTVCameraBlockEntity> eligible = new ArrayList<>();
        if (CCTVCameraBlockEntity.cctvCameras.size() > 0) {
            for (CCTVCameraBlockEntity cctvCamera : CCTVCameraBlockEntity.cctvCameras) {
                BlockPos camPos = cctvCamera.getBlockPos();
                Vec3i camVec = new Vec3i(camPos.getX(), camPos.getY(), camPos.getZ());
                double blockRange = 50.0d;
                Double configRange = (Double) ModernLifeConfig.CLIENT.cctvCameraRange.get();
                if (configRange != null && configRange.doubleValue() >= 0.0d) {
                    blockRange = configRange.doubleValue();
                }
                if (player.level.getBlockState(cctvCamera.getBlockPos()).is(CustomBlocks.BLOCK_CCTV_CAMERA.get()) && screenPos.distSqr(camVec) <= blockRange * blockRange) {
                    eligible.add(cctvCamera);
                }
            }
            if (eligible.size() > 1) {
                eligible.sort(new Comparator<CCTVCameraBlockEntity>() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.4
                    C01234() {
                    }

                    @Override // java.util.Comparator
                    public int compare(CCTVCameraBlockEntity var1, CCTVCameraBlockEntity var2) {
                        return var1.getInternalId() - var2.getInternalId();
                    }
                });
            }
        }
        return eligible;
    }

    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$4 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$4.class */
    public class C01234 implements Comparator<CCTVCameraBlockEntity> {
        C01234() {
        }

        @Override // java.util.Comparator
        public int compare(CCTVCameraBlockEntity var1, CCTVCameraBlockEntity var2) {
            return var1.getInternalId() - var2.getInternalId();
        }
    }

    private void setupNewCamera(Player player, MirrorBlockEntity chosenMirror, Camera Camera, EntityViewRenderEvent.CameraSetup event) {
        BlockPos camPos;
        if (this.currentMirrorCamera != null) {
            this.currentMirrorCamera.discard();
        }
        DummyEntity mirrorCamera = new DummyEntity(DummyEntity.DUMMY_ENTITY, Minecraft.getInstance().level);
        this.currentMirrorCamera = mirrorCamera;
        float yaw = 0.0f;
        if (chosenMirror.getBlockState().getBlock() == CustomBlocks.BLOCK_CCTV_SCREEN.get()) {
            cctvCurrentCamera = null;
            if (CCTVCameraBlockEntity.cctvCameras.size() > 0) {
                List<CCTVCameraBlockEntity> cameras = eligibleCameras(player, chosenMirror.getBlockPos());
                if (cameras.size() > 0) {
                    int camNo = chosenMirror.cctvScreenCurrentCamera % cameras.size();
                    if (camNo < 0) {
                        camNo = cameras.size() + camNo;
                    }
                    chosenMirror.cctvScreenCurrentCameraDisplayValue = camNo;
                    cctvCurrentCamera = cameras.get(camNo);
                    BlockState state = cctvCurrentCamera.getBlockState();
                    if (state.is(CustomBlocks.BLOCK_CCTV_CAMERA.get()) && (camPos = cctvCurrentCamera.getBlockPos()) != null) {
                        double camX = camPos.getX() + 0.5d;
                        double camY = camPos.getY() - 1.0d;
                        double camZ = camPos.getZ() + 0.5d;
                        Direction facing = state.getValue(CCTVCameraBlock.FACING);
                        float yaw2 = facing.toYRot();
                        switch (C012011.$SwitchMap$net$minecraft$core$Direction[facing.ordinal()]) {
                            case 1:
                                camX += 0.08d;
                                break;
                            case 2:
                                camZ += 0.08d;
                                break;
                            case 3:
                                camX -= 0.08d;
                                break;
                            case 4:
                                camZ -= 0.08d;
                                break;
                        }
                        yaw = fixYaw(yaw2);
                        mirrorCamera.setPos(camX, camY, camZ);
                        mirrorCamera.setYRot(yaw);
                        mirrorCamera.setXRot(0.0f);
                        mirrorCamera.setOldPosAndRot();
                    }
                }
            }
            if (cctvCurrentCamera == null) {
                MirrorBlockEntityRenderer.mirrorFramebuffer.unbindWrite();
                return;
            }
        } else {
            BlockPos mirrorPos = chosenMirror.getBlockPos();
            double mirrorX = mirrorPos.getX() + 0.5d;
            double mirrorY = mirrorPos.getY() - 1.0d;
            double mirrorZ = mirrorPos.getZ() + 0.5d;
            if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.NORTH) {
                mirrorZ += 0.4375d;
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.EAST) {
                mirrorX -= 0.4375d;
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.SOUTH) {
                mirrorZ -= 0.4375d;
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.WEST) {
                mirrorX += 0.4375d;
            }
            float reflectedYaw = getMirrorReflectedYaw(player, mirrorX, mirrorZ);
            if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.NORTH) {
                yaw = 180.0f - reflectedYaw;
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.EAST) {
                yaw = (-90.0f) - (reflectedYaw - 90.0f);
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.SOUTH) {
                yaw = 0.0f - (reflectedYaw - 180.0f);
            } else if (chosenMirror.getBlockState().getValue(BlockStateProperties.HORIZONTAL_FACING) == Direction.WEST) {
                yaw = 90.0f - (reflectedYaw + 90.0f);
            }
            yaw = fixYaw(yaw);
            float yBoost = 0.0f;
            if (chosenMirror.getBlockState().getBlock() != CustomBlocks.BLOCK_MIRROR.get() && chosenMirror.getBlockState().getBlock() != CustomBlocks.BLOCK_CCTV_SCREEN.get()) {
                yBoost = 0.25f;
            }
            mirrorCamera.setPos(mirrorX, mirrorY + yBoost, mirrorZ);
            mirrorCamera.setYRot(yaw);
            mirrorCamera.setXRot(0.0f);
            mirrorCamera.setOldPosAndRot();
        }
        Camera.setup(Minecraft.getInstance().level, mirrorCamera, false, false, 1.0f);
        if (event != null) {
            event.setYaw(yaw);
            event.setPitch(0.0f);
        }
    }

    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$11 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$11.class */
    public static /* synthetic */ class C012011 {
        static final /* synthetic */ int[] $SwitchMap$net$minecraft$core$Direction = new int[Direction.values().length];

        static {
            try {
                $SwitchMap$net$minecraft$core$Direction[Direction.EAST.ordinal()] = 1;
            } catch (NoSuchFieldError e) {
            }
            try {
                $SwitchMap$net$minecraft$core$Direction[Direction.SOUTH.ordinal()] = 2;
            } catch (NoSuchFieldError e2) {
            }
            try {
                $SwitchMap$net$minecraft$core$Direction[Direction.WEST.ordinal()] = 3;
            } catch (NoSuchFieldError e3) {
            }
            try {
                $SwitchMap$net$minecraft$core$Direction[Direction.NORTH.ordinal()] = 4;
            } catch (NoSuchFieldError e4) {
            }
        }
    }

    @SubscribeEvent
    public void onCameraSetup(EntityViewRenderEvent.CameraSetup event) {
        if (this.isMirrorRendering) {
            LocalPlayer localPlayer = Minecraft.getInstance().player;
            MirrorBlockEntity chosenMirror = getChosenMirror();
            if (localPlayer != null && chosenMirror != null) {
                Camera Camera = event.getCamera();
                setupNewCamera(localPlayer, chosenMirror, Camera, event);
            }
        }
    }

    @SubscribeEvent
    public void onRenderLevel(RenderLevelLastEvent renderLevelLastEvent) {
        PoseStack matrixStack = renderLevelLastEvent.getPoseStack();
        matrixStack.pushPose();
        List<BulletHoleInfo> bulletHolesToRemove = new ArrayList<>();
        try {
            Vec3 cam = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition();
            matrixStack.translate(-cam.x, -cam.y, -cam.z);
            for (int i = 0; i < bulletHoles.size(); i++) {
                BulletHoleInfo bulletHole = bulletHoles.get(i);
                if (Minecraft.getInstance().player.level.dimension().location().toString().equals(bulletHole.dim) && Minecraft.getInstance().player.level.isLoaded(bulletHole.pos)) {
                    long timeDiff = System.currentTimeMillis() - bulletHole.timestamp;
                    boolean timestampExpired = timeDiff > 60000;
                    if (!Minecraft.getInstance().player.level.getBlockState(bulletHole.pos).isAir() && !timestampExpired) {
                        matrixStack.pushPose();
                        matrixStack.translate(bulletHole.loc.x, bulletHole.loc.y + 0.0d, bulletHole.loc.z);
                        RenderSystem.setShader(GameRenderer::getPositionTexShader);
                        if (bulletHole.holeNo == 0) {
                            RenderSystem.setShaderTexture(0, this.BULLET_HOLE_1_TEX);
                        } else if (bulletHole.holeNo == 1) {
                            RenderSystem.setShaderTexture(0, this.BULLET_HOLE_2_TEX);
                        } else {
                            RenderSystem.setShaderTexture(0, this.BULLET_HOLE_3_TEX);
                        }
                        if (bulletHole.facing == Direction.EAST) {
                            matrixStack.mulPose(Vector3f.YP.rotationDegrees(270.0f));
                        } else if (bulletHole.facing == Direction.SOUTH) {
                            matrixStack.mulPose(Vector3f.YP.rotationDegrees(180.0f));
                        } else if (bulletHole.facing == Direction.WEST) {
                            matrixStack.mulPose(Vector3f.YP.rotationDegrees(90.0f));
                        } else if (bulletHole.facing == Direction.UP) {
                            matrixStack.mulPose(Vector3f.XP.rotationDegrees(90.0f));
                        } else if (bulletHole.facing == Direction.DOWN) {
                            matrixStack.mulPose(Vector3f.XP.rotationDegrees(-90.0f));
                        }
                        matrixStack.translate(0.0d, 0.0d, -0.001d);
                        if (bulletHole.randomDepth == null) {
                            double randomAvoidCollision = Math.random() * 0.001d;
                            bulletHole.randomDepth = Double.valueOf(randomAvoidCollision);
                        }
                        matrixStack.translate(0.0d, 0.0d, -bulletHole.randomDepth.doubleValue());
                        matrixStack.translate(-0.08d, -0.08d, 0.0d);
                        matrixStack.scale(0.005f, 0.005f, 0.005f);
                        int brightness = Minecraft.getInstance().player.level.getMaxLocalRawBrightness(bulletHole.pos.relative(bulletHole.facing)) - 1;
                        if (brightness < 1) {
                            brightness = 1;
                        }
                        if (brightness > 8) {
                            brightness = 8;
                        }
                        float bright = brightness / 15.0f;
                        RenderSystem.setShader(GameRenderer::getPositionTexShader);
                        RenderSystem.setShaderColor(bright, bright, bright, 1.0f);
                        GuiComponent.blit(matrixStack, 0, 0, 0.0f, 0.0f, this.BULLET_HOLE_TEX_SIZE, this.BULLET_HOLE_TEX_SIZE, this.BULLET_HOLE_TEX_SIZE, this.BULLET_HOLE_TEX_SIZE);
                        matrixStack.popPose();
                    } else {
                        bulletHolesToRemove.add(bulletHole);
                    }
                }
            }
        } catch (Exception e) {
        }
        if (bulletHolesToRemove.size() > 0) {
            bulletHoles.removeAll(bulletHolesToRemove);
        }
        matrixStack.popPose();
    }

    @SubscribeEvent
    public void onClientTick(TickEvent.ClientTickEvent e) {
        if (e.phase == TickEvent.Phase.START && e.side == LogicalSide.CLIENT) {
            List<Player> toRemove = new ArrayList<>();
            for (Map.Entry<Player, Integer> entry : HandgunItem.firingTickMap.entrySet()) {
                Player player = entry.getKey();
                Integer tickValue = entry.getValue();
                if (player.isRemoved()) {
                    toRemove.add(player);
                } else if (tickValue != null && tickValue.intValue() > 0) {
                    if (player.getId() == Minecraft.getInstance().player.getId()) {
                        float progress = (6 - tickValue.intValue()) / 6.0f;
                        if (progress < 0.4f) {
                            player.setXRot(player.getXRot() - 0.5f);
                        }
                    }
                    entry.setValue(Integer.valueOf(tickValue.intValue() - 1));
                }
            }
            if (toRemove.size() > 0) {
                for (int i = 0; i < toRemove.size(); i++) {
                    HandgunItem.firingTickMap.remove(toRemove.get(i));
                }
            }
            if (HandgunItem.reloadingTick > 0) {
                if (HandgunItem.reloadingTick == 26) {
                    Minecraft.getInstance().level.playSound(Minecraft.getInstance().player, Minecraft.getInstance().player.blockPosition(), CustomBlocks.SOUND_GUN_RELOAD.get(), SoundSource.BLOCKS, 1.5f, 1.0f);
                }
                HandgunItem.reloadingTick--;
            }
        }
    }

    public void copyFramebufferTexture(int width, int height, int fboIn, int fboOut) {
        RenderSystem.clearColor(0.0f, 0.0f, 0.0f, 0.0f);
        RenderSystem.clear(16640, false);
        int drawBufferConfigValue = 0;
        Integer drawBufferConfigOption = (Integer) ModernLifeConfig.CLIENT.cctvOptifineDrawbuffer.get();
        if (drawBufferConfigOption != null) {
            drawBufferConfigValue = drawBufferConfigOption.intValue();
        }
        GL30.glBindFramebuffer(36009, fboOut);
        GL30.glDrawBuffer(36064 + drawBufferConfigValue);
        GL30.glBindFramebuffer(36008, fboIn);
        GL30.glReadBuffer(36065);
        GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, 16384, 9728);
    }

    public Frustum prepareCaptureFrustum(PoseStack poseStack, Vec3 pos, Matrix4f fovMatrix) {
        Matrix4f matrix4f = poseStack.last().pose();
        double d0 = pos.x();
        double d1 = pos.y();
        double d2 = pos.z();
        Frustum cullingFrustum = new Frustum(matrix4f, fovMatrix);
        cullingFrustum.prepare(d0, d1, d2);
        return cullingFrustum;
    }

    public LinkedHashSet<Object> getRenderChunks(Object in) {
        Field f = null;
        try {
            f = Class.forName("net.minecraft.client.renderer.LevelRenderer$RenderChunkStorage").getDeclaredField(McpConstants.LEVEL_RENDERER_entityTarget);
        } catch (Exception e) {
        }
        LinkedHashSet<Object> result = null;
        if (f == null) {
            try {
                f = Class.forName("net.minecraft.client.renderer.LevelRenderer$RenderChunkStorage").getDeclaredField("renderChunks");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        f.setAccessible(true);
        result = (LinkedHashSet) f.get(in);
        return result;
    }

    public ChunkRenderDispatcher.RenderChunk getRenderChunk(Object renderChunkInfo) {
        Field f = null;
        try {
            f = Class.forName("net.minecraft.client.renderer.LevelRenderer$RenderChunkInfo").getDeclaredField(McpConstants.LEVEL_RENDERER_entityTarget);
        } catch (Exception e) {
        }
        ChunkRenderDispatcher.RenderChunk result = null;
        if (f == null) {
            try {
                f = Class.forName("net.minecraft.client.renderer.LevelRenderer$RenderChunkInfo").getDeclaredField("chunk");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        f.setAccessible(true);
        result = (ChunkRenderDispatcher.RenderChunk) f.get(renderChunkInfo);
        return result;
    }

    public void appendFrustum(Frustum frustum, ObjectArrayList<Object> renderChunksInFrustum, AtomicReference<Object> renderChunkStorage) {
        renderChunksInFrustum.clear();
        HashSet<Object> existingRenderChunks = new HashSet<>();
        ObjectListIterator it = renderChunksInFrustum.iterator();
        while (it.hasNext()) {
            Object renderChunk = it.next();
            existingRenderChunks.add(renderChunk);
        }
        Iterator<Object> it2 = getRenderChunks(renderChunkStorage.get()).iterator();
        while (it2.hasNext()) {
            Object levelrenderer$renderchunkinfo = it2.next();
            if (!existingRenderChunks.contains(levelrenderer$renderchunkinfo) && frustum.isVisible(getRenderChunk(levelrenderer$renderchunkinfo).getBoundingBox())) {
                renderChunksInFrustum.add(levelrenderer$renderchunkinfo);
            }
        }
    }

    @SubscribeEvent
    public void prerenderEvent(TickEvent.RenderTickEvent e) {
        Field fDFB;
        if (e.phase == TickEvent.Phase.START) {
            int i = this.renderTicker;
            this.renderTicker = i + 1;
            if (i % 3 == 0) {
                this.foundMirror = false;
                Boolean disableMirrorRender = (Boolean) ModernLifeConfig.CLIENT.disableMirrorRendering.get();
                Boolean disableCCTVRender = (Boolean) ModernLifeConfig.CLIENT.disableCCTVRendering.get();
                if (disableMirrorRender != null && disableMirrorRender.booleanValue() && disableCCTVRender != null && disableCCTVRender.booleanValue()) {
                    return;
                }
                Boolean configSpectatorMirror = (Boolean) ModernLifeConfig.CLIENT.mirrorRendersInSpectatorMode.get();
                if (configSpectatorMirror != null && !configSpectatorMirror.booleanValue() && Minecraft.getInstance() != null && Minecraft.getInstance().player != null && Minecraft.getInstance().player.isSpectator()) {
                    return;
                }
                MirrorBlockEntity chosenMirror = getChosenMirror();
                if (chosenMirror != null) {
                    if (chosenMirror.getBlockState().getBlock() == CustomBlocks.BLOCK_CCTV_SCREEN.get() && disableCCTVRender != null && disableCCTVRender.booleanValue()) {
                        return;
                    }
                    if (chosenMirror.getBlockState().getBlock() != CustomBlocks.BLOCK_CCTV_SCREEN.get() && disableMirrorRender != null && disableMirrorRender.booleanValue()) {
                        return;
                    } else {
                        this.foundMirror = true;
                    }
                }
                RenderTarget mirrorFramebuffer = MirrorBlockEntityRenderer.mirrorFramebuffer;
                int newWidth = Minecraft.getInstance().getWindow().getWidth();
                int newHeight = Minecraft.getInstance().getWindow().getHeight();
                if (mirrorFramebuffer == null) {
                    this.capturedWidth = newWidth;
                    this.capturedHeight = newHeight;
                    MirrorBlockEntityRenderer.mirrorFramebuffer = new TextureTarget(newWidth, newHeight, true, ON_OSX);
                    mirrorFramebuffer = MirrorBlockEntityRenderer.mirrorFramebuffer;
                } else if (this.capturedWidth != newWidth || this.capturedHeight != newHeight) {
                    this.capturedWidth = newWidth;
                    this.capturedHeight = newHeight;
                    mirrorFramebuffer.resize(this.capturedWidth, this.capturedHeight, ON_OSX);
                }
                if (chosenMirror != null) {
                    switch (C012011.$SwitchMap$net$minecraft$core$Direction[chosenMirror.getBlockState().getValue(MirrorBlock.FACING).ordinal()]) {
                        case 1:
                            if (Minecraft.getInstance().player.blockPosition().getX() < chosenMirror.getBlockPos().getX()) {
                                return;
                            }
                            break;
                        case 2:
                            if (Minecraft.getInstance().player.blockPosition().getZ() < chosenMirror.getBlockPos().getZ()) {
                                return;
                            }
                            break;
                        case 3:
                            if (Minecraft.getInstance().player.blockPosition().getX() > chosenMirror.getBlockPos().getX()) {
                                return;
                            }
                            break;
                        case 4:
                            if (Minecraft.getInstance().player.blockPosition().getZ() > chosenMirror.getBlockPos().getZ()) {
                                return;
                            }
                            break;
                    }
                    Minecraft.getInstance().getMainRenderTarget().unbindWrite();
                    PoseStack posestack = RenderSystem.getModelViewStack();
                    posestack.pushPose();
                    mirrorFramebuffer.bindWrite(true);
                    long nanos = Util.getNanos();
                    LocalPlayer localPlayer = Minecraft.getInstance().player;
                    if (localPlayer != null) {
                        BlockPos mirrorPos = chosenMirror.getBlockPos();
                        float mirrorX = mirrorPos.getX() + 0.5f;
                        float mirrorY = mirrorPos.getY() + 0.5f;
                        float mirrorZ = mirrorPos.getZ() + 0.5f;
                        Entity camera = Minecraft.getInstance().getCameraEntity();
                        if (camera != null) {
                        }
                        this.isMirrorRendering = true;
                    }
                    boolean bobViewOriginal = Minecraft.getInstance().options.bobView;
                    Minecraft.getInstance().options.bobView = false;
                    Double xTransparentOld = Double.valueOf(0.0d);
                    Double yTransparentOld = Double.valueOf(0.0d);
                    Double zTransparentOld = Double.valueOf(0.0d);
                    Minecraft.getInstance().getCameraEntity();
                    try {
                        Class optShaders = Class.forName("net.optifine.shaders.Shaders");
                        if (this.currentMirrorCamera != null) {
                            Field previousCameraPositionX = optShaders.getDeclaredField("previousCameraPositionX");
                            if (previousCameraPositionX != null) {
                                previousCameraPositionX.setAccessible(true);
                                previousCameraPositionX.setDouble(null, this.currentMirrorCamera.getX());
                            }
                            Field previousCameraPositionY = optShaders.getDeclaredField("previousCameraPositionY");
                            if (previousCameraPositionY != null) {
                                previousCameraPositionY.setAccessible(true);
                                double newY = this.currentMirrorCamera.getY() + Minecraft.getInstance().player.getEyeHeight();
                                previousCameraPositionY.setDouble(null, newY);
                            }
                            Field previousCameraPositionZ = optShaders.getDeclaredField("previousCameraPositionZ");
                            if (previousCameraPositionZ != null) {
                                previousCameraPositionZ.setAccessible(true);
                                previousCameraPositionZ.setDouble(null, this.currentMirrorCamera.getZ());
                            }
                        }
                        optifineDisableFastRender();
                    } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e2) {
                    }
                    Field f = null;
                    try {
                        try {
                            f = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_entityTarget);
                        } catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e1) {
                            e1.printStackTrace();
                        }
                    } catch (Exception e3) {
                    }
                    if (f == null) {
                        f = LevelRenderer.class.getDeclaredField("entityTarget");
                    }
                    f.setAccessible(true);
                    f.set(Minecraft.getInstance().levelRenderer, null);
                    Field f2 = null;
                    try {
                        f2 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_xTransparentOld);
                    } catch (Exception e4) {
                    }
                    if (f2 == null) {
                        f2 = LevelRenderer.class.getDeclaredField("xTransparentOld");
                    }
                    f2.setAccessible(true);
                    xTransparentOld = (Double) f2.get(Minecraft.getInstance().levelRenderer);
                    Field f3 = null;
                    try {
                        f3 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_yTransparentOld);
                    } catch (Exception e5) {
                    }
                    if (f3 == null) {
                        f3 = LevelRenderer.class.getDeclaredField("yTransparentOld");
                    }
                    f3.setAccessible(true);
                    yTransparentOld = (Double) f3.get(Minecraft.getInstance().levelRenderer);
                    Field f4 = null;
                    try {
                        f4 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_zTransparentOld);
                    } catch (Exception e6) {
                    }
                    if (f4 == null) {
                        f4 = LevelRenderer.class.getDeclaredField("zTransparentOld");
                    }
                    f4.setAccessible(true);
                    zTransparentOld = (Double) f4.get(Minecraft.getInstance().levelRenderer);
                    try {
                        Minecraft.getInstance().gameRenderer.render(e.renderTickTime, nanos, true);
                    } catch (Exception e7) {
                    }
                    Minecraft.getInstance().options.bobView = bobViewOriginal;
                    this.isMirrorRendering = false;
                    try {
                        Class optShaders2 = Class.forName("net.optifine.shaders.Shaders");
                        if (optShaders2 != null && (fDFB = optShaders2.getDeclaredField("dfb")) != null) {
                            fDFB.setAccessible(true);
                            Object dfb = fDFB.get(null);
                            if (dfb != null) {
                                Field fGLFB = dfb.getClass().getDeclaredField("glFramebuffer");
                                if (dfb != null && fGLFB != null) {
                                    fGLFB.setAccessible(true);
                                    int inputFramebuffer = fGLFB.getInt(dfb);
                                    copyFramebufferTexture(mirrorFramebuffer.width, mirrorFramebuffer.height, inputFramebuffer, mirrorFramebuffer.frameBufferId);
                                }
                            }
                        }
                    } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e8) {
                    }
                    mirrorFramebuffer.unbindWrite();
                    posestack.popPose();
                    RenderSystem.applyModelViewMatrix();
                    if (xTransparentOld != null && yTransparentOld != null && zTransparentOld != null) {
                        Field f5 = null;
                        try {
                            try {
                                f5 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_xTransparentOld);
                            } catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e12) {
                                e12.printStackTrace();
                            }
                        } catch (Exception e9) {
                        }
                        if (f5 == null) {
                            f5 = LevelRenderer.class.getDeclaredField("xTransparentOld");
                        }
                        f5.setAccessible(true);
                        f5.set(Minecraft.getInstance().levelRenderer, xTransparentOld);
                        Field f6 = null;
                        try {
                            f6 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_yTransparentOld);
                        } catch (Exception e10) {
                        }
                        if (f6 == null) {
                            f6 = LevelRenderer.class.getDeclaredField("yTransparentOld");
                        }
                        f6.setAccessible(true);
                        f6.set(Minecraft.getInstance().levelRenderer, yTransparentOld);
                        Field f7 = null;
                        try {
                            f7 = LevelRenderer.class.getDeclaredField(McpConstants.LEVEL_RENDERER_zTransparentOld);
                        } catch (Exception e11) {
                        }
                        if (f7 == null) {
                            f7 = LevelRenderer.class.getDeclaredField("zTransparentOld");
                        }
                        f7.setAccessible(true);
                        f7.set(Minecraft.getInstance().levelRenderer, zTransparentOld);
                    }
                    Minecraft.getInstance().getMainRenderTarget().bindWrite(true);
                    return;
                }
                return;
            }
        }
        if (e.phase == TickEvent.Phase.END && !this.foundMirror) {
            optifineResetFastRenderToNormal();
        }
    }

    public static void optifineDisableFastRender() {
        try {
            Class optConfig = Class.forName("net.optifine.Config");
            if (optConfig != null) {
                Field fGameSettings = optConfig.getDeclaredField("gameSettings");
                fGameSettings.setAccessible(true);
                Object gameSettingsObject = fGameSettings.get(null);
                if (gameSettingsObject != null) {
                    Field fFastRender = gameSettingsObject.getClass().getDeclaredField("ofFastRender");
                    if (originalFastRender == null) {
                        originalFastRender = Boolean.valueOf(fFastRender.getBoolean(gameSettingsObject));
                    }
                    fFastRender.setBoolean(gameSettingsObject, false);
                }
            }
        } catch (Exception e) {
        }
    }

    public static void optifineResetFastRenderToNormal() {
        try {
            Class optConfig = Class.forName("net.optifine.Config");
            if (optConfig != null && originalFastRender != null) {
                Field fGameSettings = optConfig.getDeclaredField("gameSettings");
                fGameSettings.setAccessible(true);
                Object gameSettingsObject = fGameSettings.get(null);
                if (gameSettingsObject != null) {
                    Field fFastRender = gameSettingsObject.getClass().getDeclaredField("ofFastRender");
                    ModernLifeCommon.LOGGER.info("reset FR to: " + originalFastRender);
                    fFastRender.setBoolean(gameSettingsObject, originalFastRender.booleanValue());
                    originalFastRender = null;
                }
            }
        } catch (Exception e) {
        }
    }

    public int materialColorToTintColor(int materialColorRgb) {
        int r = materialColorRgb & 255;
        int g = (materialColorRgb & 65280) >> 8;
        int b = (materialColorRgb & 16711680) >> 16;
        return (materialColorRgb & (-16777216)) | (r << 16) | (g << 8) | b;
    }

    public int colorWithAlpha(int materialColorRgb, int alpha) {
        int a = alpha << 24;
        return (materialColorRgb & 16777215) | a;
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$5 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$5.class */
    public class C01245 implements BlockColor {
        C01245() {
        }

        public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
            return ModernLifeClient.this.materialColorToTintColor(MaterialColor.PLANT.calculateRGBColor(MaterialColor.Brightness.NORMAL));
        }
    }

    @OnlyIn(Dist.CLIENT)
    public void registerBlockColors(ColorHandlerEvent.Block event) {
        event.getBlockColors().register(new BlockColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.5
            C01245() {
            }

            public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
                return ModernLifeClient.this.materialColorToTintColor(MaterialColor.PLANT.calculateRGBColor(MaterialColor.Brightness.NORMAL));
            }
        }, new Block[]{(Block) CustomBlocks.BLOCK_HEDGE.get()});
        event.getBlockColors().register(new BlockColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.6
            C01256() {
            }

            public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
                return ModernLifeClient.this.colorWithAlpha(ModernLifeClient.this.materialColorToTintColor(MaterialColor.WATER.calculateRGBColor(MaterialColor.Brightness.NORMAL)), 127);
            }
        }, new Block[]{(Block) CustomBlocks.BLOCK_TOILET.get(), (Block) CustomBlocks.BLOCK_BATHTUB.get()});
        event.getBlockColors().register(new BlockColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.7
            C01267() {
            }

            public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
                return ModernBookshelfBlockEntityRenderer.renderRgb0;
            }
        }, new Block[]{(Block) CustomBlocks.BLOCK_MODERN_BOOK.get()});
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$6 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$6.class */
    public class C01256 implements BlockColor {
        C01256() {
        }

        public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
            return ModernLifeClient.this.colorWithAlpha(ModernLifeClient.this.materialColorToTintColor(MaterialColor.WATER.calculateRGBColor(MaterialColor.Brightness.NORMAL)), 127);
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$7 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$7.class */
    public class C01267 implements BlockColor {
        C01267() {
        }

        public int getColor(BlockState paramBlockState, BlockAndTintGetter paramBlockAndTintGetter, BlockPos paramBlockPos, int paramInt) {
            return ModernBookshelfBlockEntityRenderer.renderRgb0;
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$8 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$8.class */
    public class C01278 implements ItemColor {
        C01278() {
        }

        public int getColor(ItemStack paramItemStack, int paramInt) {
            return ModernLifeClient.this.materialColorToTintColor(MaterialColor.PLANT.calculateRGBColor(MaterialColor.Brightness.NORMAL));
        }
    }

    @OnlyIn(Dist.CLIENT)
    public void registerItemColors(ColorHandlerEvent.Item event) {
        event.getItemColors().register(new ItemColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.8
            C01278() {
            }

            public int getColor(ItemStack paramItemStack, int paramInt) {
                return ModernLifeClient.this.materialColorToTintColor(MaterialColor.PLANT.calculateRGBColor(MaterialColor.Brightness.NORMAL));
            }
        }, new ItemLike[]{(ItemLike) CustomBlocks.ITEM_HEDGE.get()});
        event.getItemColors().register(new ItemColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.9
            C01289() {
            }

            public int getColor(ItemStack paramItemStack, int paramInt) {
                return ModernLifeClient.this.materialColorToTintColor(MaterialColor.WATER.calculateRGBColor(MaterialColor.Brightness.NORMAL));
            }
        }, new ItemLike[]{(ItemLike) CustomBlocks.ITEM_TOILET.get()});
        event.getItemColors().register(new ItemColor() { // from class: com.dairymoose.modernlife.core.ModernLifeClient.10
            C011910() {
            }

            public int getColor(ItemStack paramItemStack, int paramInt) {
                if (paramInt == 0) {
                    return ModernBookshelfBlockEntityRenderer.renderRgb0;
                }
                return ModernBookshelfBlockEntityRenderer.renderRgb1;
            }
        }, new ItemLike[]{(ItemLike) CustomBlocks.ITEM_MODERN_BOOK.get()});
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$9 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$9.class */
    public class C01289 implements ItemColor {
        C01289() {
        }

        public int getColor(ItemStack paramItemStack, int paramInt) {
            return ModernLifeClient.this.materialColorToTintColor(MaterialColor.WATER.calculateRGBColor(MaterialColor.Brightness.NORMAL));
        }
    }

    /* JADX INFO: Access modifiers changed from: package-private */
    /* renamed from: com.dairymoose.modernlife.core.ModernLifeClient$10 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$10.class */
    public class C011910 implements ItemColor {
        C011910() {
        }

        public int getColor(ItemStack paramItemStack, int paramInt) {
            if (paramInt == 0) {
                return ModernBookshelfBlockEntityRenderer.renderRgb0;
            }
            return ModernBookshelfBlockEntityRenderer.renderRgb1;
        }
    }

    @SubscribeEvent
    public void onClientLogin(ClientPlayerNetworkEvent.LoggedInEvent e) {
        ModernLifeCommon.LOGGER.info("Client login");
        if (cachedData != null) {
            cachedData.clear();
        }
    }

    @SubscribeEvent
    public void fovModifierEvent(EntityViewRenderEvent.FieldOfView fovEvent) {
        if (HandgunItem.originalFov > 0.0d) {
            fovEvent.setFOV(fovEvent.getFOV() / 1.2d);
        }
    }

    @SubscribeEvent
    public void onClientLogout(ClientPlayerNetworkEvent.LoggedOutEvent e) {
        ModernLifeCommon.LOGGER.info("Client logout");
        if (MirrorBlockEntityRenderer.mirrorMap != null) {
            MirrorBlockEntityRenderer.mirrorMap.clear();
        }
        if (PowerReceiverBlockEntity.perChannelPowerReceivers.size() > 0) {
            ModernLifeCommon.LOGGER.debug("Clearing power receivers: size = " + PowerReceiverBlockEntity.perChannelPowerReceivers.size());
            PowerReceiverBlockEntity.perChannelPowerReceivers.clear();
        }
        if (PowerTransmitterBlockEntity.perChannelPowerTransmitters.size() > 0) {
            ModernLifeCommon.LOGGER.debug("Clearing power transmitters: size = " + PowerTransmitterBlockEntity.perChannelPowerTransmitters.size());
            PowerTransmitterBlockEntity.perChannelPowerTransmitters.clear();
        }
        HandgunItem.resetFov();
        bulletHoles.clear();
        HandgunItem.firingTickMap.clear();
        optifineResetFastRenderToNormal();
    }

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$CachedCanvasData.class */
    public static class CachedCanvasData {
        long timestamp;
        byte[] data;
        int hashCode;
        int texWidth;
        int texHeight;

        private CachedCanvasData() {
        }
    }

    private static void purgeOldCanvasData() {
        long currentTimestamp = System.currentTimeMillis();
        for (Map.Entry<Long, CachedCanvasData> entry : cachedData.entrySet()) {
            CachedCanvasData ccd = entry.getValue();
            long timeDiff = currentTimestamp - ccd.timestamp;
            if (timeDiff >= 1800000) {
                cachedData.remove(entry.getKey());
            }
        }
    }

    public static void requestUpdateForCanvas(long currentTime, long uniqueId) {
        ModernLifeCommon.LOGGER.info("Request update for canvas: " + uniqueId);
        long timestamp = 0;
        Long timestampData = uniqueIdToTimestampMap.get(Long.valueOf(uniqueId));
        if (timestampData != null) {
            timestamp = timestampData.longValue();
        }
        long timeDiff = currentTime - timestamp;
        if (timeDiff >= 3000) {
            uniqueIdToTimestampMap.put(Long.valueOf(uniqueId), Long.valueOf(currentTime));
            ModernLifeNetwork.INSTANCE.sendToServer(new ServerboundRequestCanvasPacket(uniqueId));
        }
    }

    public static void requestCanvasChecksumValidation(long currentTime, long uniqueId, int checksum) {
        long timestamp = 0;
        Long timestampData = uniqueIdToTimestampChecksumMap.get(Long.valueOf(uniqueId));
        if (timestampData != null) {
            timestamp = timestampData.longValue();
        }
        long timeDiff = currentTime - timestamp;
        if (timeDiff >= 3000) {
            uniqueIdToTimestampChecksumMap.put(Long.valueOf(uniqueId), Long.valueOf(currentTime));
            ModernLifeNetwork.INSTANCE.sendToServer(new ServerboundCanvasChecksumPacket(uniqueId, checksum));
        }
    }

    public static byte[] getCanvasData(long uniqueId) {
        purgeOldCanvasData();
        long currentTime = System.currentTimeMillis();
        CachedCanvasData ccd = cachedData.get(Long.valueOf(uniqueId));
        if (ccd != null) {
            return ccd.data;
        }
        ServerboundMultipartCameraPacket.PngSizeHolder sizeHolder = new ServerboundMultipartCameraPacket.PngSizeHolder();
        try {
            byte[] data = ServerboundMultipartCameraPacket.loadPng(uniqueId, sizeHolder);
            if (data == null) {
                requestUpdateForCanvas(currentTime, uniqueId);
                return null;
            }
            CachedCanvasData ccd2 = putCachedData(currentTime, uniqueId, data, sizeHolder.width, sizeHolder.height);
            if (ccd2 != null) {
                requestCanvasChecksumValidation(currentTime, uniqueId, ccd2.hashCode);
            }
            return data;
        } catch (Exception e) {
            ModernLifeCommon.LOGGER.error("Exception while loading canvas data", e);
            return null;
        }
    }

    public static CachedCanvasData putCachedData(long currentTime, long uniqueId, byte[] data, int width, int height) {
        CachedCanvasData ccd = new CachedCanvasData();
        ccd.data = data;
        ccd.timestamp = currentTime;
        ccd.hashCode = ModernLifeCommon.getHashCodeForBytes(data);
        ccd.texWidth = width;
        ccd.texHeight = height;
        cachedData.put(Long.valueOf(uniqueId), ccd);
        return ccd;
    }

    public static int getCanvasWidth(long uniqueId) {
        CachedCanvasData ccd = cachedData.get(Long.valueOf(uniqueId));
        if (ccd != null) {
            return ccd.texWidth;
        }
        return 0;
    }

    public static int getCanvasHeight(long uniqueId) {
        CachedCanvasData ccd = cachedData.get(Long.valueOf(uniqueId));
        if (ccd != null) {
            return ccd.texHeight;
        }
        return 0;
    }

    public static void removeCachedCanvasData(long uniqueId) {
        cachedData.remove(Long.valueOf(uniqueId));
    }

    public static long getCanvasHashCode(long uniqueId) {
        CachedCanvasData ccd = cachedData.get(Long.valueOf(uniqueId));
        if (ccd != null) {
            return ccd.hashCode;
        }
        return 0L;
    }

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/core/ModernLifeClient$CanvasPreviewComponent.class */
    public static class CanvasPreviewComponent implements ClientTooltipComponent, TooltipComponent {
        private static DynamicTexture canvasTexture;
        private static ResourceLocation dynamicTextureLocation;
        private ItemStack stack;
        private static ResourceLocation CANVAS_TOOLTIP_LOCATION = new ResourceLocation("modernlife", "textures/gui/canvas_tooltip.png");
        private static int CANVAS_TOOLTIP_SIZE = 96;
        private static CanvasData canvasTooltipData = new CanvasData();
        private static int lastCanvasHashCode = 0;
        private static long lastUniqueId = 0;
        private static int CANVAS_TOOLTIP_DYN_TEX_SIZE = CANVAS_TOOLTIP_SIZE - 2;

        CanvasPreviewComponent(ItemStack stack) {
            this.stack = stack;
        }

        public void renderImage(Font font, int x, int y, PoseStack pose, ItemRenderer itemRenderer, int xTextureStart) {
            boolean shouldDrawImage = true;
            ItemStack itemStack = this.stack;
            if (itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_CANVAS.get() && itemStack.getTag() != null && itemStack.getTag().contains("UniqueId")) {
                long uniqueId = itemStack.getTag().getLong("UniqueId");
                byte[] compressed = ModernLifeClient.getCanvasData(uniqueId);
                int newHashCode = ModernLifeCommon.getHashCodeForBytes(compressed);
                if (uniqueId != lastUniqueId || (compressed != null && newHashCode != lastCanvasHashCode)) {
                    RenderSystem.disableBlend();
                    RenderSystem.disableDepthTest();
                    lastUniqueId = uniqueId;
                    lastCanvasHashCode = newHashCode;
                    if (Minecraft.getInstance().gui != null) {
                        canvasTooltipData.disable();
                        int w = ModernLifeClient.getCanvasWidth(uniqueId);
                        int h = ModernLifeClient.getCanvasHeight(uniqueId);
                        if (w != 0 && h != 0) {
                            canvasTooltipData.setTextureSize(w, h);
                        } else {
                            canvasTooltipData.setTextureSize(64, 64);
                        }
                        if (itemStack.getTag().contains("UniqueId") && compressed != null) {
                            canvasTooltipData.fromCompressedNbt(compressed);
                            canvasTooltipData.initImage();
                            if (canvasTexture != null) {
                                canvasTexture.close();
                                canvasTexture = null;
                            }
                            if (canvasTexture == null) {
                                canvasTexture = new DynamicTexture(canvasTooltipData.textureWidth(), canvasTooltipData.textureHeight(), true);
                                dynamicTextureLocation = Minecraft.getInstance().textureManager.register("artpad/dyn", canvasTexture);
                                canvasTooltipData.reenable();
                                EaselScreen.updateTexture(canvasTooltipData, canvasTexture);
                            }
                        }
                        canvasTooltipData.reenable();
                    }
                }
                if (compressed == null) {
                    shouldDrawImage = false;
                }
                RenderSystem.setShader(GameRenderer::getPositionTexShader);
                RenderSystem.setShaderTexture(0, CANVAS_TOOLTIP_LOCATION);
                int blitY = y;
                if (blitY < 2) {
                    blitY = 2;
                }
                GuiComponent.blit(pose, x, blitY, 0.0f, 0.0f, CANVAS_TOOLTIP_SIZE, CANVAS_TOOLTIP_SIZE, CANVAS_TOOLTIP_SIZE, CANVAS_TOOLTIP_SIZE);
                if (shouldDrawImage && dynamicTextureLocation != null) {
                    RenderSystem.setShader(GameRenderer::getPositionTexShader);
                    RenderSystem.setShaderTexture(0, dynamicTextureLocation);
                    GuiComponent.blit(pose, x + 1, blitY + 1, 0.0f, 0.0f, CANVAS_TOOLTIP_DYN_TEX_SIZE, CANVAS_TOOLTIP_DYN_TEX_SIZE, CANVAS_TOOLTIP_DYN_TEX_SIZE, CANVAS_TOOLTIP_DYN_TEX_SIZE);
                }
                RenderSystem.enableBlend();
                RenderSystem.enableDepthTest();
            }
        }

        public int getHeight() {
            if (this.stack == null || this.stack == ItemStack.EMPTY || this.stack.getTag() == null || !this.stack.getTag().contains("UniqueId")) {
                return 0;
            }
            return CANVAS_TOOLTIP_SIZE;
        }

        public int getWidth(Font paramFont) {
            return CANVAS_TOOLTIP_SIZE;
        }
    }

    @OnlyIn(Dist.CLIENT)
    @SubscribeEvent
    public void renderTooltipEvent(RenderTooltipEvent.GatherComponents tooltipEvent) {
        List<Either<FormattedText, TooltipComponent>> components = tooltipEvent.getTooltipElements();
        ItemStack itemStack = tooltipEvent.getItemStack();
        if (itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_CANVAS.get()) {
            components.add(0, Either.right(new CanvasPreviewComponent(itemStack)));
        }
    }

    @SubscribeEvent
    public void renderItemInInteractionHandEvent(RenderHandEvent RenderHandEvent) {
        Integer tickValue;
        if (this.isMirrorRendering) {
            RenderHandEvent.setCanceled(true);
        }
        if (CameraItem.usingCamera || CameraItem.pendingSnapshot) {
            RenderHandEvent.setCanceled(true);
        }
        ItemStack itemStack = RenderHandEvent.getItemStack();
        if (itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_HANDGUN.get()) {
            if (Minecraft.getInstance().player.isUsingItem()) {
                RenderHandEvent.getPoseStack().translate(-0.38d, 0.2d, 0.0d);
                RenderHandEvent.getPoseStack().mulPose(Vector3f.ZP.rotationDegrees(-4.0f));
                RenderHandEvent.getPoseStack().mulPose(Vector3f.YP.rotationDegrees(8.0f));
                RenderHandEvent.getPoseStack().mulPose(Vector3f.XP.rotationDegrees(-10.0f));
            }
            Integer tickValue2 = HandgunItem.firingTickMap.get(Minecraft.getInstance().player);
            if (tickValue2 != null && tickValue2.intValue() > 0) {
                float progress = (6 - tickValue2.intValue()) / 6.0f;
                float upswingProgress = progress / 0.75f;
                if (progress <= 0.75f) {
                    RenderHandEvent.getPoseStack().mulPose(Vector3f.XP.rotationDegrees(upswingProgress * 35.0f));
                } else {
                    float downswingProgress = (progress - 0.75f) / 0.25f;
                    RenderHandEvent.getPoseStack().mulPose(Vector3f.XP.rotationDegrees((1.0f - downswingProgress) * 35.0f));
                }
            }
            if (HandgunItem.reloadingTick > 0) {
                RenderHandEvent.getPoseStack().mulPose(Vector3f.YP.rotationDegrees(45.0f));
            }
        }
        if (Minecraft.getInstance() != null && Minecraft.getInstance().player != null && itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_HANDGUN.get() && (tickValue = HandgunItem.firingTickMap.get(Minecraft.getInstance().player)) != null && tickValue.intValue() > 0) {
            int xOffset = 20;
            int yOffset = 20;
            if (!Minecraft.getInstance().player.isUsingItem()) {
                xOffset = 80;
                yOffset = 40;
            }
            int x = (Minecraft.getInstance().getWindow().getGuiScaledWidth() / 2) + xOffset;
            int y = (Minecraft.getInstance().getWindow().getGuiScaledHeight() / 2) + yOffset;
            GuiComponent.fill(RenderHandEvent.getPoseStack(), x, y, x + 20, y + 20, -256);
        }
    }

    public static void stopUsingCamera() {
        CameraItem.usingCamera = false;
        ModernLifeNetwork.INSTANCE.sendToServer(new ServerboundStopUsingCameraPacket());
        resetCameraZoom();
    }

    public static void resetCameraZoom() {
        cameraZoomFactor = 1.0f;
        if (originalFov > 0.0d) {
            Minecraft.getInstance().options.fov = originalFov;
        }
        originalFov = -1.0d;
    }

    @SubscribeEvent
    public void keyInputEvent(InputEvent.KeyInputEvent keyEvent) {
        if (CameraItem.usingCamera && keyEvent.getKey() == 256) {
            stopUsingCamera();
            Minecraft.getInstance().keyboardHandler.keyPress(Minecraft.getInstance().getWindow().getWindow(), 256, 256, 1, 0);
        }
    }

    @SubscribeEvent
    public void onDrawHighlight(DrawSelectionEvent highlightEvent) {
        if (CameraItem.usingCamera || CameraItem.pendingSnapshot) {
            highlightEvent.setCanceled(true);
        }
    }

    @SubscribeEvent
    public void onInteractEvent(PlayerInteractEvent interactEvent) {
        if (CameraItem.usingCamera && !(interactEvent instanceof PlayerInteractEvent.RightClickItem)) {
            if ((interactEvent instanceof PlayerInteractEvent.LeftClickBlock) || (interactEvent instanceof PlayerInteractEvent.LeftClickEmpty)) {
                stopUsingCamera();
            }
            if (interactEvent != null && interactEvent.isCancelable()) {
                interactEvent.setCanceled(true);
            }
        }
        ItemStack itemStack = interactEvent.getPlayer().getMainHandItem();
        if (itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_HANDGUN.get()) {
            if (((interactEvent instanceof PlayerInteractEvent.LeftClickBlock) || (interactEvent instanceof PlayerInteractEvent.LeftClickEmpty)) && interactEvent.isCancelable()) {
                interactEvent.setCanceled(true);
            }
        }
    }

    @SubscribeEvent
    public void onClick(InputEvent.RawMouseEvent mouseEvent) {
        if (Minecraft.getInstance().player != null && !Minecraft.getInstance().player.isSpectator()) {
            ItemStack item = Minecraft.getInstance().player.getMainHandItem();
            if (mouseEvent.getButton() == 0 && mouseEvent.getAction() == 1 && item != null && item.getItem() == CustomBlocks.ITEM_HANDGUN.get() && !Minecraft.getInstance().isPaused() && Minecraft.getInstance().screen == null) {
                CustomBlocks.ITEM_HANDGUN.get().fireGun(Minecraft.getInstance().player);
            }
        }
    }

    @SubscribeEvent
    public void mouseScrollEvent(InputEvent.MouseScrollEvent scrollEvent) {
        if (CameraItem.usingCamera) {
            if (originalFov < 0.0d) {
                originalFov = Minecraft.getInstance().options.fov;
            }
            if (scrollEvent.getScrollDelta() > 0.0d) {
                cameraZoomFactor += 0.5f;
            } else {
                cameraZoomFactor -= 0.5f;
            }
            cameraZoomFactor = Math.min(cameraZoomFactor, 4.5f);
            cameraZoomFactor = Math.max(cameraZoomFactor, 1.0f);
            Minecraft.getInstance().options.fov = (originalFov * 1.0d) / cameraZoomFactor;
            scrollEvent.setCanceled(true);
        }
    }

    private void drawCrosshairLine(PoseStack matrixStack, int x0, int y0, int w0, int h0) {
        int x = (Minecraft.getInstance().getWindow().getGuiScaledWidth() / 2) + x0;
        int y = (Minecraft.getInstance().getWindow().getGuiScaledHeight() / 2) + y0;
        GuiComponent.fill(matrixStack, x, y, x + w0, y + h0, -1);
    }

    private void drawSizedCrosshair(PoseStack matrixStack, int size, int lineLength) {
        drawCrosshairLine(matrixStack, size, 0, lineLength, 1);
        drawCrosshairLine(matrixStack, ((-size) - lineLength) + 1, 0, lineLength, 1);
        drawCrosshairLine(matrixStack, 0, size, 1, lineLength);
        drawCrosshairLine(matrixStack, 0, ((-size) - lineLength) + 1, 1, lineLength);
    }

    @SubscribeEvent
    public void renderPlayerEvent(RenderPlayerEvent.Pre event) {
        ItemStack itemStack = event.getPlayer().getMainHandItem();
        if (itemStack != null && itemStack.getItem() == CustomBlocks.ITEM_HANDGUN.get()) {
            event.getRenderer().m_7200_().f_102816_ = HumanoidModel.ArmPose.CROSSBOW_HOLD;
        }
    }

    @SubscribeEvent
    public void renderOverlayEvent(RenderGameOverlayEvent.Pre overlayEvent) {
        String zoomText;
        ModernBookshelfBlockEntity bookshelf;
        int hitIndex;
        IModFile modFile;
        List<IModInfo> infoList;
        if (this.isMirrorRendering) {
            return;
        }
        if (overlayEvent.getType() == RenderGameOverlayEvent.ElementType.LAYER && (overlayEvent instanceof RenderGameOverlayEvent.PreLayer)) {
            RenderGameOverlayEvent.PreLayer preLayerOverlay = (RenderGameOverlayEvent.PreLayer) overlayEvent;
            if (preLayerOverlay.getOverlay() == ForgeIngameGui.CROSSHAIR_ELEMENT && Minecraft.getInstance().player.getMainHandItem().getItem() == CustomBlocks.ITEM_HANDGUN.get()) {
                overlayEvent.setCanceled(true);
                int movementFactor = 0;
                if (1 != 0) {
                    Vec3 movement = Minecraft.getInstance().player.getDeltaMovement();
                    movementFactor = (int) (((movement.x * movement.x) + (movement.z * movement.z)) / 0.002d);
                }
                if (1 != 0 && !Minecraft.getInstance().player.isUsingItem()) {
                    drawSizedCrosshair(overlayEvent.getMatrixStack(), 5 + movementFactor, 3);
                } else {
                    drawSizedCrosshair(overlayEvent.getMatrixStack(), 2 + movementFactor, 3);
                }
            }
            Entity vehicle = Minecraft.getInstance().player.getVehicle();
            if (vehicle != null && (vehicle instanceof MotorboatEntity) && preLayerOverlay.getOverlay() == ForgeIngameGui.HOTBAR_ELEMENT) {
                MotorboatEntity motorboat = (MotorboatEntity) vehicle;
                Entity controller = motorboat.getControllingPassenger();
                if ((controller instanceof Player) && motorboat.isControlledByLocalInstance()) {
                    float remainingFuel = motorboat.getCurrentFuelLevel();
                    float throttlePercent = motorboat.getCurAccel() / motorboat.getMaxAccel();
                    if (motorboat.isOutOfFuel() || motorboat.status == MotorboatEntity.Status.ON_LAND) {
                        throttlePercent = 0.0f;
                    }
                    Window window = overlayEvent.getWindow();
                    PoseStack matrixStack = overlayEvent.getMatrixStack();
                    RenderSystem.setShader(GameRenderer::getPositionTexShader);
                    RenderSystem.setShaderTexture(0, this.GUI_MOTORBOAT_LOCATION);
                    int xStart = ((int) (window.getGuiScaledWidth() * 0.06d)) - (this.GUI_MOTORBOAT_TEX_SIZE / 2);
                    int yStart = ((int) (window.getGuiScaledHeight() * 0.65d)) - (this.GUI_MOTORBOAT_TEX_SIZE / 2);
                    float throttleBarPct = throttlePercent;
                    RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
                    GuiComponent.blit(matrixStack, xStart, yStart, 0.0f, 0.0f, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    GuiComponent.blit(matrixStack, xStart, yStart, 0.0f, this.GUI_MOTORBOAT_BORDER_HEIGHT, 1 + ((int) Math.ceil((this.GUI_MOTORBOAT_TEX_SIZE - 2) * remainingFuel)), this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 0.5f);
                    GuiComponent.blit(matrixStack, xStart, yStart, 0.0f, this.GUI_MOTORBOAT_BORDER_HEIGHT * 2.0f, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
                    GuiComponent.blit(matrixStack, xStart, yStart + 10, 0.0f, 0.0f, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    GuiComponent.blit(matrixStack, xStart, yStart + 10, 0.0f, this.GUI_MOTORBOAT_BORDER_HEIGHT, 1 + ((int) Math.ceil((this.GUI_MOTORBOAT_TEX_SIZE - 2) * throttleBarPct)), this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 0.5f);
                    GuiComponent.blit(matrixStack, xStart, yStart + 10, 0.0f, this.GUI_MOTORBOAT_BORDER_HEIGHT * 3.0f, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_BORDER_HEIGHT, this.GUI_MOTORBOAT_TEX_SIZE, this.GUI_MOTORBOAT_TEX_SIZE);
                    RenderSystem.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);
                }
            }
            if (preLayerOverlay.getOverlay() == ForgeIngameGui.HOTBAR_ELEMENT) {
                BlockHitResult blockHitResult = Minecraft.getInstance().hitResult;
                if (blockHitResult instanceof BlockHitResult) {
                    BlockHitResult bhr = blockHitResult;
                    BlockPos pos = bhr.getBlockPos();
                    BlockState state = Minecraft.getInstance().player.level.getBlockState(pos);
                    if (state.getBlock() instanceof ModernBookshelfBlock) {
                        BlockEntity blockEntity = Minecraft.getInstance().player.level.getBlockEntity(pos);
                        if ((blockEntity instanceof ModernBookshelfBlockEntity) && (hitIndex = (bookshelf = (ModernBookshelfBlockEntity) blockEntity).getHitIndex(Minecraft.getInstance().player, Minecraft.getInstance().hitResult)) != -1) {
                            ItemStack itemStack = bookshelf.getItem(hitIndex);
                            String modName = "";
                            IModFileInfo modFileInfo = ModList.get().getModFileById(itemStack.getItem().getRegistryName().getNamespace());
                            if (modFileInfo != null && (modFile = modFileInfo.getFile()) != null && (infoList = modFile.getModInfos()) != null && !infoList.isEmpty()) {
                                modName = infoList.get(0).getDisplayName();
                            }
                            MutableComponent m_130948_ = new TextComponent((String) bookshelf.bookNames.get(hitIndex)).m_130948_(Style.EMPTY.withColor(TextColor.fromRgb(16711680)));
                            MutableComponent m_130948_2 = new TextComponent(modName).m_130948_(Style.EMPTY.withColor(TextColor.fromRgb(16711680)));
                            Minecraft.getInstance().font.drawShadow(overlayEvent.getMatrixStack(), m_130948_, overlayEvent.getWindow().getGuiScaledWidth() * 0.3f, overlayEvent.getWindow().getGuiScaledHeight() * 0.35f, 0);
                            Minecraft.getInstance().font.drawShadow(overlayEvent.getMatrixStack(), m_130948_2, overlayEvent.getWindow().getGuiScaledWidth() * 0.3f, overlayEvent.getWindow().getGuiScaledHeight() * 0.38f, 0);
                        }
                    }
                }
            }
        }
        if (overlayEvent.getType() == RenderGameOverlayEvent.ElementType.TEXT && Minecraft.getInstance() != null && Minecraft.getInstance().player != null && ((Minecraft.getInstance().player.getMainHandItem().getItem() == CustomBlocks.ITEM_SPEEDOMETER.get() || Minecraft.getInstance().player.getOffhandItem().getItem() == CustomBlocks.ITEM_SPEEDOMETER.get()) && overlayEvent.getMatrixStack() != null && Minecraft.getInstance() != null && overlayEvent.getWindow() != null && Minecraft.getInstance().font != null)) {
            String speedText = String.format("%.1f bps", Float.valueOf(SpeedometerItem.speed));
            Minecraft.getInstance().font.drawShadow(overlayEvent.getMatrixStack(), new TextComponent(speedText).m_130948_(Style.EMPTY.withColor(TextColor.fromRgb(16711680))), (overlayEvent.getWindow().getGuiScaledWidth() - Minecraft.getInstance().font.width(r0.getVisualOrderText())) / 2, overlayEvent.getWindow().getGuiScaledHeight() * 0.74f, 0);
        }
        if (overlayEvent.getType() == RenderGameOverlayEvent.ElementType.TEXT && Minecraft.getInstance() != null && Minecraft.getInstance().player != null && Minecraft.getInstance().player.getMainHandItem().getItem() == CustomBlocks.ITEM_HANDGUN.get()) {
            HandgunItem handgun = CustomBlocks.ITEM_HANDGUN.get();
            String speedText2 = String.format("%d/%d (%d)", Integer.valueOf(handgun.getCurrentMagazineAmmo(Minecraft.getInstance().player)), Integer.valueOf(handgun.getCurrentMagazineCapacity(Minecraft.getInstance().player)), Integer.valueOf(handgun.getAmmoTotal(Minecraft.getInstance().player)));
            Minecraft.getInstance().font.drawShadow(overlayEvent.getMatrixStack(), new TextComponent(speedText2).m_130948_(Style.EMPTY.withColor(TextColor.fromRgb(16777215))), (overlayEvent.getWindow().getGuiScaledWidth() - Minecraft.getInstance().font.width(r0.getVisualOrderText())) * 0.08f, overlayEvent.getWindow().getGuiScaledHeight() * 0.85f, 0);
        }
        if (CameraItem.pendingSnapshot) {
            CameraItem.pendingSnapshot = false;
            CameraItem.takePhoto();
            stopUsingCamera();
        }
        if (CameraItem.usingCamera && Minecraft.getInstance() != null && Minecraft.getInstance().player != null) {
            if (Minecraft.getInstance().player.getMainHandItem().getItem() == CustomBlocks.ITEM_CAMERA.get()) {
                if (overlayEvent.getMatrixStack() != null && Minecraft.getInstance() != null && Minecraft.getInstance().getWindow() != null && Minecraft.getInstance().font != null) {
                    PoseStack matrixStack2 = overlayEvent.getMatrixStack();
                    Window window2 = Minecraft.getInstance().getWindow();
                    if (((Boolean) ModernLifeConfig.CLIENT.enableCameraViewfinder.get()).booleanValue()) {
                        RenderSystem.setShader(GameRenderer::getPositionTexShader);
                        RenderSystem.setShaderTexture(0, this.CAMERA_VIEWFINDER_LOCATION);
                        int xStart2 = (window2.getGuiScaledWidth() - this.CAMERA_VIEWFINDER_WIDTH) / 2;
                        int yStart2 = (window2.getGuiScaledHeight() - this.CAMERA_VIEWFINDER_HEIGHT) / 2;
                        if (Minecraft.getInstance().gui != null) {
                            Minecraft.getInstance().gui.m_93228_(matrixStack2, xStart2, yStart2, 0, 0, this.CAMERA_VIEWFINDER_WIDTH, this.CAMERA_VIEWFINDER_HEIGHT);
                        }
                        if (cameraZoomFactor - ((int) cameraZoomFactor) == 0.0f) {
                            zoomText = String.format("%dx zoom", Integer.valueOf((int) cameraZoomFactor));
                        } else {
                            zoomText = String.format("%.1fx zoom", Float.valueOf(cameraZoomFactor));
                        }
                        Minecraft.getInstance().font.drawShadow(matrixStack2, new TextComponent(zoomText).m_130948_(Style.EMPTY.withColor(TextColor.fromRgb(2105376))), (window2.getGuiScaledWidth() - Minecraft.getInstance().font.width(r0.getVisualOrderText())) / 2, window2.getGuiScaledHeight() * 0.88f, 0);
                    }
                    overlayEvent.setCanceled(true);
                    return;
                }
                return;
            }
            stopUsingCamera();
        }
    }

    @SubscribeEvent
    public void inputUpdateEvent(MovementInputUpdateEvent event) {
        if (event != null && event.getInput() != null && event.getPlayer() != null) {
            if (event.getPlayer().isUsingItem()) {
                if (event.getPlayer().getUseItem().getItem() == CustomBlocks.ITEM_CHAINSAW.get() || event.getPlayer().getUseItem().getItem() == CustomBlocks.ITEM_FLASHLIGHT.get()) {
                    if (event.getPlayer().getVehicle() == null && !((Boolean) ModernLifeConfig.CLIENT.chainsawSlowsMovementWhenUsed.get()).booleanValue()) {
                        event.getInput().forwardImpulse *= 5.0f;
                        event.getInput().leftImpulse *= 5.0f;
                    }
                } else if (event.getPlayer().getUseItem().getItem() == CustomBlocks.ITEM_HANDGUN.get() && event.getPlayer().getVehicle() == null) {
                    event.getInput().forwardImpulse *= 2.0f;
                    event.getInput().leftImpulse *= 2.0f;
                }
            }
            if ((event.getPlayer().getVehicle() instanceof BicycleEntity) && event.getPlayer().level.getBlockState(event.getPlayer().getVehicle().blockPosition().below()).is(CustomBlocks.BLOCK_PAVED_ROAD.get())) {
                BicycleEntity bike = (BicycleEntity) event.getPlayer().getVehicle();
                event.getInput().forwardImpulse = (float) (r0.forwardImpulse * 1.2d);
                event.getInput().leftImpulse *= 1.0f;
                bike.setSpeedBoost(1.2f);
            }
        }
    }
}
