net.minecraftforge.fml.common.network.NetworkRegistry Java Examples

The following examples show how to use net.minecraftforge.fml.common.network.NetworkRegistry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonProxy.java    From ToroQuest with GNU General Public License v3.0 6 votes vote down vote up
public void preInit(FMLPreInitializationEvent e) {
	//configDirectory = new File(e.getModConfigurationDirectory(), ToroQuest.MODID);
	ToolMaterials.init();
	initConfig(e.getSuggestedConfigurationFile());

	MinecraftForge.EVENT_BUS.register(new CivilizationGeneratorHandlers());
	MinecraftForge.EVENT_BUS.register(new EventHandlers());
	MinecraftForge.EVENT_BUS.register(new CivilizationHandlers());
	MinecraftForge.EVENT_BUS.register(new EntitySpawning());
	VillageHandlerKeep.init();
	// VillageHandlerTrophy.init();
	VillageHandlerShop.init();
	VillageHandlerGuardTower.init();
	VillageHandlerBarracks.init();
	ToroQuestPacketHandler.init();
	NetworkRegistry.INSTANCE.registerGuiHandler(ToroQuest.INSTANCE, new VillageLordGuiHandler());

	DataFixer datafixer = new DataFixer(922);
	EntityVillageLord.registerFixesVillageLord(datafixer);

	Quests.init();

}
 
Example #2
Source File: NetworkEventCodec.java    From OpenModsLib with MIT License 6 votes vote down vote up
@Override
protected void encode(ChannelHandlerContext ctx, NetworkEvent msg, List<Object> out) throws IOException {
	final Channel channel = ctx.channel();
	final Side side = channel.attr(NetworkRegistry.CHANNEL_SOURCE).get();

	final NetworkEventEntry entry = CommonRegistryCallbacks.getObjectToEntryMap(registry).get(msg.getClass());
	Preconditions.checkState(entry != null, "Can't find registration for class %s", msg.getClass());
	final int id = CommonRegistryCallbacks.getEntryIdMap(registry).get(entry);

	final EventDirection validator = entry.getDirection();
	Preconditions.checkState(validator != null && validator.validateSend(side),
			"Invalid direction: sending packet %s on side %s", msg.getClass(), side);

	final PacketBuffer buf = new PacketBuffer(Unpooled.buffer());
	buf.writeVarInt(id);
	msg.writeToStream(buf);

	final FMLProxyPacket packet = new FMLProxyPacket(buf, NetworkEventDispatcher.CHANNEL_NAME);
	packet.setDispatcher(msg.dispatcher);
	out.add(packet);
}
 
Example #3
Source File: NemezEventHandler.java    From Wizardry with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SubscribeEvent
public static void worldTick(TickEvent.WorldTickEvent event) {
	if (event.phase == TickEvent.Phase.START)
		reversals.removeIf((reversal) -> {
			if (reversal.world.get() == event.world) {
				if (reversal.nemez.hasNext()) {
					reversal.nemez.applySnapshot(event.world);
					if (reversal.pos != null && reversal.world.get().getTotalWorldTime() % PacketNemezReversal.SYNC_AMOUNT == 0)
						PacketHandler.NETWORK.sendToAllAround(new PacketNemezReversal(reversal.nemez),
								new NetworkRegistry.TargetPoint(reversal.world.get().provider.getDimension(),
										reversal.pos.getX() + 0.5, reversal.pos.getY() + 0.5, reversal.pos.getZ() + 0.5, 96));
				} else {
					for (Entity entity : reversal.nemez.getTrackedEntities(event.world))
						entity.setNoGravity(false);
					return true;
				}
			}
			return reversal.world.get() == null;
		});
}
 
Example #4
Source File: Signals.java    From Signals with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void PreInit(FMLPreInitializationEvent event){
    event.getModMetadata().version = Versions.fullVersionString();
    NetworkRegistry.INSTANCE.registerGuiHandler(instance, proxy);
    proxy.preInit();
    ModBlocks.init();
    ModItems.init();
    CapabilityMinecartDestination.register();
    CapabilityDestinationProvider.register();
    MinecraftForge.EVENT_BUS.register(proxy);
    MinecraftForge.EVENT_BUS.register(new com.minemaarten.signals.event.EventHandler());
    MinecraftForge.EVENT_BUS.register(new RailReplacerEventHandler());
    BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject(ModItems.TICKET, new BehaviorDispenseTicket());

    ChunkLoadManager.INSTANCE.init();

    asmData = event.getAsmData();

    if(!SignalsConfig.enableRailNetwork) {
        Log.warning("RAIL NETWORK IS NOT FUNCTIONAL!");
    }
}
 
Example #5
Source File: EntitySpellProjectile.java    From Wizardry with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Called when the projectile entity hits another block or entity, or reaches the end of its path.
 *
 * @param data The {@link SpellData} attached to the spell.
 */
protected void goBoom(SpellRing spellRing, SpellData data) {
	motionX = 0;
	motionY = 0;
	motionZ = 0;

	if (spellRing.getChildRing() != null)
		spellRing.getChildRing().runSpellRing(world, data, true);

	if (doesRender())
		PacketHandler.NETWORK.sendToAllAround(new PacketExplode(getPositionVector(), spellRing.getPrimaryColor(), spellRing.getSecondaryColor(), 0.3, 0.3, RandUtil.nextInt(30, 50), 10, 25, true),
				new NetworkRegistry.TargetPoint(world.provider.getDimension(), posX, posY, posZ, 512));

	setDead();
	world.removeEntity(this);
}
 
Example #6
Source File: MCPacketHandler.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, PacketAbstract packet) throws Exception {
	INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();

	switch (FMLCommonHandler.instance().getEffectiveSide()) {
		case CLIENT:
			FMLClientHandler.instance().getClient().addScheduledTask(() -> packet.handleClientSide(NovaMinecraft.proxy.getClientPlayer()));
			break;
		case SERVER:
			FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> packet.handleServerSide(((NetHandlerPlayServer) netHandler).player));
			break;
		default:
			break;
	}

}
 
Example #7
Source File: MCPacketHandler.java    From NOVA-Core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, PacketAbstract packet) throws Exception {
	INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();

	switch (FMLCommonHandler.instance().getEffectiveSide()) {
		case CLIENT:
			FMLClientHandler.instance().getClient().addScheduledTask(() -> packet.handleClientSide(NovaMinecraft.proxy.getClientPlayer()));
			break;
		case SERVER:
			FMLCommonHandler.instance().getMinecraftServerInstance().addScheduledTask(() -> packet.handleServerSide(((NetHandlerPlayServer) netHandler).playerEntity));
			break;
		default:
			break;
	}

}
 
Example #8
Source File: CustomStuff4.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
    CapabilityItemHandlerSupplier.register();
    MinecraftForge.EVENT_BUS.register(EventHandler.class);

    initPlugins(event.getAsmData());

    File configDir = event.getModConfigurationDirectory();
    File modsDir = new File(configDir.getParent(), "mods");

    registerPackets();

    NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
    ModLoader.initMods(modsDir);
}
 
Example #9
Source File: AdvancedRocketry.java    From AdvancedRocketry with MIT License 5 votes vote down vote up
@EventHandler
public void serverStopped(FMLServerStoppedEvent event) {
	zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions();
	zmaster587.advancedRocketry.cable.NetworkRegistry.clearNetworks();
	SpaceObjectManager.getSpaceManager().onServerStopped();
	zmaster587.advancedRocketry.api.Configuration.MoonId = -1;
	DimensionManager.getInstance().overworldProperties.resetProperties();
	((BlockSeal)AdvancedRocketryBlocks.blockPipeSealer).clearMap();
	DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 8000, "Dimensions including and after this number are allowed to be made into planets");
	
	DimensionManager.getInstance().knownPlanets.clear();
	
	if(!zmaster587.advancedRocketry.api.Configuration.lockUI)
		proxy.saveUILayout(config);
}
 
Example #10
Source File: FireRecipe.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void tick(World world, BlockPos pos) {
	currentDuration++;
	if (currentDuration % 10 == 0) {
		PacketHandler.NETWORK.sendToAllAround(new PacketDevilDustFizzle(new Vec3d(pos).add(0.5, 0.5, 0.5), currentDuration), new NetworkRegistry.TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 20));
		world.playSound(null, pos.getX(), pos.getY(), pos.getZ(), ModSounds.FRYING_SIZZLE, SoundCategory.BLOCKS, 0.7F, (float) RandUtil.nextDouble(0.8, 1.3));
	}
}
 
Example #11
Source File: EntityFairy.java    From Wizardry with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onDeath(@Nonnull DamageSource cause) {
	if (getIsInvulnerable()) return;

	if (!world.isRemote) {
		FairyData dataFairy = getDataFairy();
		if (dataFairy == null) return;

		if (dataFairy.isDepressed) {

			ItemStack stack = new ItemStack(ModItems.FAIRY_ITEM);
			NBTHelper.setTag(stack, "fairy", dataFairy.serializeNBT());

			world.removeEntity(this);

			EntityItem entityItem = new EntityItem(world);
			entityItem.setPosition(posX, posY, posZ);
			entityItem.setItem(stack);
			entityItem.setPickupDelay(20);
			entityItem.setNoDespawn();

			world.spawnEntity(entityItem);
			return;
		}

		super.onDeath(cause);

		if (getHealth() <= 0)
			PacketHandler.NETWORK.sendToAllAround(new PacketExplode(getPositionVector().add(0, 0.25, 0), dataFairy.primaryColor, dataFairy.secondaryColor, 0.5, 0.5, RandUtil.nextInt(100, 200), 75, 25, true),
					new NetworkRegistry.TargetPoint(world.provider.getDimension(), posX, posY, posZ, 256));
	}
}
 
Example #12
Source File: TileEntityAltar.java    From CommunityMod with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void onContentsChanged(int slot) {
	if (!world.isRemote) {
		ExtraRandomness.network.sendToAllAround(
				new PacketUpdateAltar(TileEntityAltar.this),
				new NetworkRegistry.TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 64)
		);
	}
}
 
Example #13
Source File: ValkyrienSkiesControl.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
private void registerNetworks() {
    controlNetwork = NetworkRegistry.INSTANCE.newSimpleChannel("control_network");
    controlNetwork
        .registerMessage(PilotControlsMessageHandler.class, PilotControlsMessage.class, 2,
            Side.SERVER);
    controlNetwork
        .registerMessage(MessageStartPilotingHandler.class, MessageStartPiloting.class, 3,
            Side.CLIENT);
    controlNetwork
        .registerMessage(MessageStopPilotingHandler.class, MessageStopPiloting.class, 4,
            Side.CLIENT);
    controlNetwork.registerMessage(MessagePlayerStoppedPilotingHandler.class,
        MessagePlayerStoppedPiloting.class, 5, Side.SERVER);
}
 
Example #14
Source File: ValkyrienSkiesMod.java    From Valkyrien-Skies with Apache License 2.0 5 votes vote down vote up
private void registerNetworks(FMLStateEvent event) {
    physWrapperNetwork = NetworkRegistry.INSTANCE.newSimpleChannel("physChannel");
    physWrapperNetwork.registerMessage(PhysWrapperPositionHandler.class,
        WrapperPositionMessage.class, 0, Side.CLIENT);
    physWrapperNetwork.registerMessage(SubspacedEntityRecordHandler.class,
        SubspacedEntityRecordMessage.class, 1, Side.CLIENT);
    physWrapperNetwork.registerMessage(SubspacedEntityRecordHandler.class,
        SubspacedEntityRecordMessage.class, 2, Side.SERVER);
    physWrapperNetwork.registerMessage(VSGuiButtonHandler.class,
        VSGuiButtonMessage.class, 3, Side.SERVER);
}
 
Example #15
Source File: CommonProxy.java    From GokiStats with MIT License 5 votes vote down vote up
public void registerHandlers() {
    MinecraftForge.EVENT_BUS.register(new GokiStats());
    MinecraftForge.EVENT_BUS.register(new GokiSounds());
    MinecraftForge.EVENT_BUS.register(new CommonHandler());
    MinecraftForge.EVENT_BUS.register(new TickHandler());
    MinecraftForge.EVENT_BUS.register(new StatCapabilityHandler());

    NetworkRegistry.INSTANCE.registerGuiHandler(GokiStats.instance,
            new GuiHandler());
}
 
Example #16
Source File: CraftingKeys.java    From CraftingKeys with MIT License 5 votes vote down vote up
/**
 * This method will be executed while loading.
 *
 * @param event Input Event from FML
 */
@EventHandler
public void load(FMLInitializationEvent event) {

    // Registering
    FMLCommonHandler.instance().bus().register(this);
    MinecraftForge.EVENT_BUS.register(this);
    NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiConfigHandler());
    KeyBindings.init();
    Logger.info("load(e)", "Registered Mod.");

}
 
Example #17
Source File: ProductionLine.java    From Production-Line with MIT License 5 votes vote down vote up
@Mod.EventHandler
    public void init(FMLInitializationEvent event) {
        PLOreDictionary.init();
        // register Recipes. 注册合成
//        PLRecipes.init();
        //register gui handler
        NetworkRegistry.INSTANCE.registerGuiHandler(INSTANCE, GuiHandler.getInstance());
        //register achievement
        PLAchievement.init();
        //register achievement page
        AchievementPage.registerAchievementPage(PLAchievement.pagePL);
        //register ore gen bus. 注册矿石生成总线
        PLWorldGen.init();
        proxy.init();
    }
 
Example #18
Source File: TofuMain.java    From TofuCraftReload with MIT License 5 votes vote down vote up
@EventHandler
public void preInit(FMLPreInitializationEvent event) {
    proxy.preInit(event);

    logger = event.getModLog();

    TofuEntityRegister.entitySpawn();

    TofuCompat.preInit();

    GameRegistry.registerWorldGenerator(new TofuOreGenerator(), 0);

    MapGenStructureIO.registerStructure(MapGenTofuVillage.Start.class,"TofuVillage");
    StructureTofuVillagePieces.registerVillagePieces();
    MapGenStructureIO.registerStructure(StructureTofuMineshaftStart.class,"TofuMineshaft");
    StructureTofuMineshaftPieces.registerStructurePieces();
    MapGenStructureIO.registerStructure(MapGenTofuCastle.Start.class, "TofuCastle");
    TofuCastlePiece.registerTofuCastlePiece();

    NetworkRegistry.INSTANCE.registerGuiHandler(this, new TofuGuiHandler());


    zunda = new DamageSource("zunda") {
        @Override
        public ITextComponent getDeathMessage(EntityLivingBase entityLivingBaseIn) {
            String s = "death.attack.zunda";
            String s1 = s + ".player";

            return new TextComponentString(entityLivingBaseIn.getDisplayName().getFormattedText() + " ").appendSibling(new TextComponentTranslation(s1, new Object[]{entityLivingBaseIn.getDisplayName()}));
        }
    }.setDamageIsAbsolute();

    TOFU_DIMENSION = DimensionType.register("Tofu World", "_tofu", TofuConfig.dimensionID, WorldProviderTofu.class, false);
    DimensionManager.registerDimension(TofuConfig.dimensionID, TOFU_DIMENSION);

    TofuVillages.register();
}
 
Example #19
Source File: Levels.java    From Levels with GNU General Public License v2.0 5 votes vote down vote up
@EventHandler
public void preInit(FMLPreInitializationEvent event)
{
	configDir = new File(event.getModConfigurationDirectory() + "/" + Reference.MODID);
	configDir.mkdirs();
	Config.init(configDir);
	
	ModEvents.register();
	proxy.preInit();
	
	network = NetworkRegistry.INSTANCE.newSimpleChannel(Reference.MODID);
	network.registerMessage(PacketAttributeSelection.Handler.class, PacketAttributeSelection.class, 0, Side.SERVER);
	network.registerMessage(PacketMythicSound.Handler.class, PacketMythicSound.class, 1, Side.CLIENT);
}
 
Example #20
Source File: ClientProxy.java    From TFC2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void registerGuiHandler()
{
	NetworkRegistry.INSTANCE.registerGuiHandler(TFC.instance, new GuiHandler());
	// Register Gui Event Handler
	MinecraftForge.EVENT_BUS.register(new GuiHandler());
}
 
Example #21
Source File: EnderUtilities.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
    ConfigReader.loadConfigsFromFile(event.getSuggestedConfigurationFile());
    ModRegistry.checkLoadedMods();

    proxy.registerEventHandlers();
    proxy.registerEntities();
    proxy.registerKeyBindings();
    proxy.registerRenderers();

    EnderUtilitiesCapabilities.register();
    PacketHandler.init(); // Initialize network stuff
    NetworkRegistry.INSTANCE.registerGuiHandler(this, new EnderUtilitiesGUIHandler());
}
 
Example #22
Source File: Effects.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void addItemTeleportEffects(World world, BlockPos pos)
{
    PacketHandler.INSTANCE.sendToAllAround(
            new MessageAddEffects(MessageAddEffects.EFFECT_ENDER_TOOLS, MessageAddEffects.PARTICLES | MessageAddEffects.SOUND,
                pos.getX() + 0.5d, pos.getY() + 0.5d, pos.getZ() + 0.5d, 8, 0.2f, 0.3f),
                new NetworkRegistry.TargetPoint(world.provider.getDimension(), pos.getX(), pos.getY(), pos.getZ(), 24.0d));
}
 
Example #23
Source File: TeleportEntity.java    From enderutilities with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void addTeleportSoundsAndParticles(World world, double x, double y, double z)
{
    if (world.isRemote == false)
    {
        PacketHandler.INSTANCE.sendToAllAround(new MessageAddEffects(MessageAddEffects.EFFECT_TELEPORT, MessageAddEffects.PARTICLES | MessageAddEffects.SOUND, x, y, z),
                new NetworkRegistry.TargetPoint(world.provider.getDimension(), x, y, z, 24.0d));
    }
}
 
Example #24
Source File: RpcCallDispatcher.java    From OpenModsLib with MIT License 5 votes vote down vote up
private RpcCallDispatcher(IForgeRegistry<MethodEntry> methodRegistry, IForgeRegistry<TargetTypeProvider> targetRegistry) {
	this.channels = NetworkRegistry.INSTANCE.newChannel(CHANNEL_NAME, new RpcCallCodec(targetRegistry, methodRegistry), new RpcCallInboundHandler());
	ExtendedOutboundHandler.install(this.channels);

	this.senders = new Senders();

	this.proxyFactory = new RpcProxyFactory(methodRegistry);
}
 
Example #25
Source File: RpcCallCodec.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
	final PacketBuffer input = new PacketBuffer(msg.payload());

	final Side side = ctx.channel().attr(NetworkRegistry.CHANNEL_SOURCE).get();

	final IRpcTarget target;
	final MethodEntry method;
	final Object[] args;

	{
		final int targetId = input.readVarInt();
		final BiMap<Integer, TargetTypeProvider> idToEntryMap = CommonRegistryCallbacks.getEntryIdMap(targetRegistry).inverse();
		final TargetTypeProvider entry = idToEntryMap.get(targetId);
		target = entry.createRpcTarget();
		EntityPlayer player = getPlayer(msg);
		target.readFromStreamStream(side, player, input);
	}

	{
		final BiMap<MethodEntry, Integer> eventIdMap = CommonRegistryCallbacks.getEntryIdMap(methodRegistry);
		final int methodId = input.readVarInt();
		method = eventIdMap.inverse().get(methodId);
		args = method.paramsCodec.readArgs(input);
	}

	int bufferJunkSize = input.readableBytes();
	Preconditions.checkState(bufferJunkSize == 0, "%s junk bytes left in buffer, method = %s", bufferJunkSize, method);

	out.add(new RpcCall(target, method, args));
	input.release();
}
 
Example #26
Source File: NetworkEventCodec.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {
	final Channel channel = ctx.channel();
	final Side side = channel.attr(NetworkRegistry.CHANNEL_SOURCE).get();

	final PacketBuffer payload = new PacketBuffer(msg.payload());
	final int typeId = payload.readVarInt();
	final NetworkEventEntry type = CommonRegistryCallbacks.getEntryIdMap(registry).inverse().get(typeId);

	final EventDirection validator = type.getDirection();
	Preconditions.checkState(validator != null && validator.validateReceive(side),
			"Invalid direction: receiving packet %s on side %s", msg.getClass(), side);

	final NetworkEvent event = type.createPacket();
	event.readFromStream(payload);
	event.dispatcher = msg.getDispatcher();

	event.side = side;

	final INetHandler handler = msg.handler();
	if (handler != null) event.sender = OpenMods.proxy.getPlayerFromHandler(handler);

	final int bufferJunkSize = payload.readableBytes();
	if (bufferJunkSize > 0) Log.warn("%s junk bytes left in buffer, event %s", bufferJunkSize, event);

	out.add(event);
	payload.release();
}
 
Example #27
Source File: ExtendedOutboundHandler.java    From OpenModsLib with MIT License 5 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
	if (!(msg instanceof FMLProxyPacket)) {
		ctx.write(msg);
		return;
	}

	final Channel channel = ctx.channel();

	final IPacketTargetSelector<?> target = channel.attr(MESSAGETARGET).get();
	if (target == null) {
		ctx.write(msg);
		return;
	}

	final FMLProxyPacket pkt = (FMLProxyPacket)msg;

	final Side channelSide = channel.attr(NetworkRegistry.CHANNEL_SOURCE).get();

	Preconditions.checkState(target.isAllowedOnSide(channelSide), "Packet not allowed on side");

	final String channelName = channel.attr(NetworkRegistry.FML_CHANNEL).get();

	Object arg = channel.attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).get();

	try {
		final Collection<NetworkDispatcher> dispatchers = getDispatchers(target, arg);
		for (NetworkDispatcher dispatcher : dispatchers)
			dispatcher.sendProxy(pkt);

	} catch (Throwable t) {

		throw new IllegalStateException(String.format(
				"Failed to select and send message (selector %s, arg: %s, channel: %s, side: %s)",
				target, arg, channelName, channelSide), t);
	}

}
 
Example #28
Source File: NetUtils.java    From OpenModsLib with MIT License 5 votes vote down vote up
public static void executeSynchronized(ChannelHandlerContext ctx, Runnable runnable) {
	final IThreadListener thread = FMLCommonHandler.instance().getWorldThread(ctx.channel().attr(NetworkRegistry.NET_HANDLER).get());
	if (!thread.isCallingFromMinecraftThread()) {
		thread.addScheduledTask(runnable);
	} else {
		runnable.run();
	}
}
 
Example #29
Source File: SyncChannelHolder.java    From OpenModsLib with MIT License 5 votes vote down vote up
private SyncChannelHolder() {
	final EnumMap<Side, FMLEmbeddedChannel> channels = NetworkRegistry.INSTANCE.newChannel(CHANNEL_NAME, new InboundSyncHandler());

	for (Map.Entry<Side, FMLEmbeddedChannel> e : channels.entrySet()) {
		final FMLEmbeddedChannel channel = e.getValue();
		ExtendedOutboundHandler.install(channel);
		senders.put(e.getKey(), ExtPacketSenderFactory.createMultiplePlayersSender(channel));
	}
}
 
Example #30
Source File: HoloInventory.java    From HoloInventory with MIT License 5 votes vote down vote up
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event)
{
    logger = event.getModLog();

    config = new Configuration(event.getSuggestedConfigurationFile());
    updateConfig();

    int id = 0;
    snw = NetworkRegistry.INSTANCE.newSimpleChannel(MODID);

    // Request packets (client -> server)
    snw.registerMessage(EntityRequest.Handler.class, EntityRequest.class, id++, Side.SERVER);
    snw.registerMessage(TileRequest.Handler.class, TileRequest.class, id++, Side.SERVER);

    // Response packets (server -> client)
    snw.registerMessage(PlainInventory.Handler.class, PlainInventory.class, id++, Side.CLIENT);
    snw.registerMessage(MerchantRecipes.Handler.class, MerchantRecipes.class, id++, Side.CLIENT);

    if (event.getSide().isClient())
    {
        //noinspection MethodCallSideOnly
        ClientEventHandler.init();
    }

    MinecraftForge.EVENT_BUS.register(this);
    MinecraftForge.EVENT_BUS.register(ServerEventHandler.I);
}