Jump to content

Recommended Posts

Posted (edited)

This is my first forum post so I aplogize if I do anything wrong or assume this is markdown somewhere since I'm used to it.
I'm building a mod to detect block changes, when people start raids, ...etc to prevent griefing while you afk. 
Here is my code 

package io.github.javaarchive.logitmod;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Nullable;
import javax.imageio.ImageIO;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft;
import net.minecraft.client.main.Main;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Hand;
import net.minecraft.util.ScreenShotHelper;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponent;
import net.minecraft.world.World;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.ForgeConfig.Client;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.TextComponentMessageFormatHandler;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

// The value here should match an entry in the META-INF/mods.toml file
@Mod("logit")
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.FORGE)
public class LogitMod
{
    // Directly reference a log4j logger.
    private static final Logger LOGGER = LogManager.getLogger();
	public boolean DONOTDOUBLEEVENT = true;
    PrintWriter pw;
    public String EVIDENCE_DIR = "evidence";
    public LogitMod() {
    	
        // Register the setup method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
        // Register the enqueueIMC method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
        // Register the processIMC method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
        // Register the doClientStuff method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);

        // Register ourselves for server and other game events we are interested in
        MinecraftForge.EVENT_BUS.register(this);
    	
    }
    public String getFormattedTime() {
    	SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss");  
        Date date = new Date();  
        return formatter.format(date);
    }
    private void setup(final FMLCommonSetupEvent event) 
    {
        // some preinit code
        LOGGER.info("HELLO FROM PREINIT");
        
        try {
        	pw = new PrintWriter(new BufferedWriter(new FileWriter("log-"+this.getFormattedTime()+".txt")));
        	File evidenceDir = new File(EVIDENCE_DIR);
        	if(!evidenceDir.isDirectory()) {
        		evidenceDir.mkdir();
        	}
        }catch(IOException ex) {
        	ex.printStackTrace();
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
              pw.close();
            }
          });
        	LOGGER.info("The DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
    }

    private void doClientStuff(final FMLClientSetupEvent event) {
        // do something that can only be done on the client
        LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().gameSettings);
    }

    private void enqueueIMC(final InterModEnqueueEvent event)
    {
        // some example code to dispatch IMC to another mod
        InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";});
    }

    private void processIMC(final InterModProcessEvent event)
    {
        // some example code to receive and process InterModComms from other mods
        LOGGER.info("Got IMC {}", event.getIMCStream().
                map(m->m.getMessageSupplier().get()).
                collect(Collectors.toList()));
    }
    // You can use SubscribeEvent and let the Event Bus discover methods to call
    @SubscribeEvent
    public void onServerStarting(FMLServerStartingEvent event) {
        // do something when the server starts
        LOGGER.info("HELLO from server starting");
    }
    public boolean isValuable(String name) {
    	if(name.contains("diamond")) {
    		return true;
    	}
    	return false;
    }
    @SubscribeEvent
    public void ItemTossEvent(net.minecraftforge.event.entity.item.ItemTossEvent event) {
        //System.out.println("Item picked up!");
    	
    	if(isValuable(event.getEntityItem().getName().getString().toLowerCase())){
    		Minecraft mc = Minecraft.getInstance();
    		ITextComponent tc = new StringTextComponent("You have dropped a valuable item. It's name is "+event.getEntityItem().getName().getString()+" and it is waiting for you at "+Math.floor(event.getEntityItem().getPosX())+", "+Math.floor(event.getEntityItem().getPosY())+", "+Math.floor(event.getEntityItem().getPosZ()));
    		mc.player.sendMessage(tc);
    		//mc.getConnection()
    		//ScreenshotHelper.
    		/*
    		ScreenShotHelper.saveScreenshot(new File(EVIDENCE_DIR+"/"+getFormattedTime()+".jpg"), mc.currentScreen.width, mc.currentScreen.height, mc.getFramebuffer(), new Consumer<ITextComponent>() {

				@Override
				public void accept(ITextComponent arg0) {
					// TODO Auto-generated method stub
					
				}});
				*/
    		/*try {
				//screenshot.write(new File(EVIDENCE_DIR+"/"+getFormattedTime()+".jpg"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */
    		
    		
    		pw.println("ALERT: You dropped a "+event.getEntityItem().getName().getString());
    	
    	}
        pw.println("You dropped a "+event.getEntityItem().getName().getString()+" at "+Math.floor(event.getEntityItem().getPosX())+", "+Math.floor(event.getEntityItem().getPosY())+", "+Math.floor(event.getEntityItem().getPosZ()));
    }
    // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
    // Event bus for receiving Registry Events)
    
    public void onBlockHarvested(World worldIn, BlockPos pos, BlockState state, PlayerEntity player) {
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	Block block = state.getBlock();
    	pw.println("The player "+player.getName().getString()+" broke(harvested) a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    
    public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
    	if(placer.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	pw.println(placer.getName()+" placed a "+state.getBlock().getNameTextComponent().getString()+" block at "+" at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    
    public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
    	pw.println("Block activated by "+player.getName().getString()+" at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    	if(worldIn.isRemote) {
    		return true;
    	}else {
    		return false;
    	}
    }
    
    public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player) {
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	Block block = state.getBlock();
    	pw.println("The player "+player.getName().getString()+" left-clicked a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    @SubscribeEvent
    public void GuiOpenEvent(GuiScreenEvent gui) {
    	//gui.getClass()
    	pw.flush();
    }
    @SubscribeEvent
    public void onBlockPlaced(BlockEvent.EntityPlaceEvent event)
    {
    	pw.println("You placed a "+event.getPlacedBlock().getBlock().getNameTextComponent().getString()+" at "+event.getPos().getX()+", "+event.getPos().getY()+", "+event.getPos().getZ());
    }
    @SubscribeEvent
    public void onBreakBlock(BreakEvent event) {
    	PlayerEntity player = event.getPlayer();
    	BlockPos pos = event.getPos();
    	Block block = event.getState().getBlock();
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		//return; // We have our own handler for this
    	}
    	pw.println("The player "+player.getName().getString()+" left-clicked a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    @SubscribeEvent
    public void onBlockBreakEvent(BlockEvent.BreakEvent event) 
    {
    	// Check if a spawner broke
    	if(event.getState().getBlock() == Blocks.SPAWNER)
    	{
    		pw.println("ALERT: YOU BROKE A SPAWNER");
    	}
    	pw.println("Broke the block "+event.getState().getBlock().getNameTextComponent().getString()+" at "+event.getPos().getX()+", "+event.getPos().getY()+", "+event.getPos().getZ());
    }
    @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
    public static class RegistryEvents {
        @SubscribeEvent
        public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
            // register a new block here
            LOGGER.info("HELLO from Register Block");
        }
    }
}


This works when I play in a singleplayer world however when I build it, and copy it into a standard forge minecraft 1.15.2 client and run it none of the events are triggered. The log file is created but is empty. I know it's probaly a bad idea to flush the file when the inventory opens but that's just temporary testing. 

Second question: Since I'm not able to test yet but does my code detect other players breaking/placing blocks. If so how can I make it detect those events? 

Edited by javaarchive/rpeng2007

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Posted
19 minutes ago, javaarchive/rpeng2007 said:

if(isValuable(event.getEntityItem().getName().getString().toLowerCase())){

    Minecraft mc = Minecraft.getInstance();

You're reaching across logical sides. You can't do this.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted (edited)

Not sure by what you mean by that, could you elaborate a bit more. The mod is meant to be run on client side only. I only found this by accident when I was looking for where somebody was obtaining their mc variable from. If this is not the right way to do it, please tell me the correct way. I think the only thing I'm using it for is to get the current player's username. 

Edited by javaarchive/rpeng2007

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Posted
1 hour ago, javaarchive/rpeng2007 said:

    public boolean isValuable(String name) {
        if(name.contains("diamond")) {
            return true;
        }
        return false;
    }

This code is awful. Do not compare things to strings. entity.getItem().getItem() == Items.DIAMOND.

48 minutes ago, javaarchive/rpeng2007 said:

Not sure by what you mean by that, could you elaborate a bit more. The mod is meant to be run on client side only.

1 hour ago, javaarchive/rpeng2007 said:

copy it into a standard forge minecraft 1.15.2 client and run it none of the events are triggered

 

The event is only fired on the server side.

 

When you connect to a dedicated server, that server is the logical server, but also the physical server. Because it is physically elsewhere.

However when you play single player, the physical client runs its own integrated server locally on a separate thread, this is the logical server located at the physical client.

When you do something on the logical server that accesses something on the logical client, that's known as "reaching across sides." It works only because the two threads are running in the same JVM. But because they are different process threads you'll sometimes get random and unexpected crashes.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Posted

Thanks for explaining this. This is my third attempt to make an minecraft mod, so I tend to not be able to find the best way to do things. Which event can I listen for on the client side, so I know when some player breaks/places a block that I can see? 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Posted

That's annoying, any way to log when I break/place a block on the client without putting stuff on the server? 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Posted

Thanks for that. It was very helpful. Can this event fire when other players break a block, just curious. 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Posted

Howdy.

You can detect the effects of players breaking a block on the client side, if they're within your render distance.  That might be enough for you?

Your client-side code could check the location of all players, every tick.  And then you could look at the blocks within a reasonable radius of each player, to see if they have changed (been broken, TNT has been placed, etc).  Might be better than nothing, if you have no way to install a mod on the server.

 

-TGG

 

  • Thanks 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • I bestow up to thee, for thy contributions to my enjoyment of this game, my kindest regards, and most heartfelt blessings. May both sides of your pillow be cold tonight. 
    • I wasn't excepting this to be seen this fast and left the post marinating for a while, but thank you for such a quick reply! Regarding what the console shows me when the server fails to boot, you can find those logs on this pastebin link here. From what I could gather, the issue here is with the mod Night Lights. Should I remove this mod, I get the same issue with Rings of Ascension, and lastly with Oh The Biomes We've Gone. When I remove these three mods, the issue goes away, but since the world was generated with the biome mod, I would rather not part ways with it. Thank you for taking some time to read my extensive description, hope the link with the logs helps!
    • Please see https://forums.minecraftforge.net/topic/125488-rules-and-frequently-asked-questions-faq/ for information on how to post your log correctly.
    • Hello!  The detailed description of how you got to where you are is certainly valuable.  But, at the end of the day (well, any time of the day actually), it is going to be the actual logs that going to provide the necessary details to hopefully solve your startup issue. Part of me wonders if you have installed a client-only mod on a dedicated server.  But I may very well be wrong, and it will be the logs that will tell that story.
    • Hello there! I didn't quite know where to go regarding this, but ended up deciding to post it here. I have been running a forge server with around 200 mods for me and some friends to play on casually, but have recently started to get an issue when booting the server. This all started after I decided to add some new mods to the server. Like usual, I add a mod, test run the server for any issues, and if all is well, I'll add a next one and so on until I have added all that I wanted to. After doing so, in all test runs, it all seemed to work just fine. However, the next day, after trying to boot the server, I kept getting an error regarding java.lang.NullPointerException, towards one of the mods I had recently added. So far so good, I removed the mod that was causing the issue, started up the server again, and here in when things took a turn for the worse. I received another java.lang.NullPointerException null error that wouldn't allow me to boot the server, but this time with a mod that wasn't part of the new ones I had recently added. I found this weird, but nonetheless, I removed it thinking it might be causing some conflicts with some of the new ones. Afterwards, booting the server again proved to be impossible, as it gave me another java.lang.NullPointerException null error with the 3rd mod I had ever installed on the server! This mod was there since the start, it added some biomes and had been just fine so far. This turn of events made me remove all the newer mods I had recently added in hopes to fix this whole ordeal, but alas, to no avail. Same error, with that same biome mod that had been there since day one. Reluctantly, I removed the biome mod, booted the server, and voila! The server was running, although without a major mod that had always been there to begin with. As I do not wish to part ways with this mod, specially since it had been working so far without any issues, I tried to bring everything back to how it was before I added those new mods, but kept on getting the same java.lang.NullPointerException null error for the biome mod. Even adding the newer mods won't cause me this error, with exception of the one that started it all, which I find quite odd since the mods I had been using without any issues are now giving me the same error the newer one that started it all gave me. Now, I have checked that everything is up to date regarding the mods, forge (forge-1.20.1-47.3.12) and java. The modpack runs perfectly fine when I start Minecraft itself, and play singleplayer, or even when I open a LAN world, everything works. Everything aside from the server. From what I could gather, this java.lang.NullPointerException null error would point to a missing value of sorts, for an item perhaps, within the mod that is causing the error, but aside from removing the whole mod, I lack the knowledge on how to fix this. With this in mind, if anyone would be so kind as to shine some light into this situation, with a way to fix all this blunder, I would be most grateful!
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.