Java Code Examples for net.minecraft.world.WorldServer

The following examples show how to use net.minecraft.world.WorldServer. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: LookingGlass   Source File: PacketRequestTE.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handle(ByteBuf data, EntityPlayer player) {
	if (ModConfigs.disabled) return;
	int dim = data.readInt();
	int xPos = data.readInt();
	int yPos = data.readInt();
	int zPos = data.readInt();

	if (!DimensionManager.isDimensionRegistered(dim)) return;
	WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim);
	if (world == null) return;
	TileEntity tile = world.getTileEntity(xPos, yPos, zPos);
	if (tile != null) {
		//FIXME: This is currently a very "forceful" method of doing this, and not technically guaranteed to produce correct results
		// This would be much better handled by using the getDescriptionPacket method and wrapping that packet in a LookingGlass
		// packet to control delivery timing, allowing for processing the packet while the correct target world is the active world
		// This idea requires that that system be in place, though, so until then this hack will hopefully hold.
		NBTTagCompound tag = new NBTTagCompound();
		tile.writeToNBT(tag);
		ServerPacketDispatcher.getInstance().addPacket(player, PacketTileEntityNBT.createPacket(xPos, yPos, zPos, tag, dim));
	}
}
 
Example 2
protected void tryDoVenting() {
    BlockPos machinePos = metaTileEntity.getPos();
    EnumFacing ventingSide = getVentingSide();
    BlockPos ventingBlockPos = machinePos.offset(ventingSide);
    IBlockState blockOnPos = metaTileEntity.getWorld().getBlockState(ventingBlockPos);
    if (blockOnPos.getCollisionBoundingBox(metaTileEntity.getWorld(), ventingBlockPos) == Block.NULL_AABB) {
        metaTileEntity.getWorld()
            .getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(ventingBlockPos), EntitySelectors.CAN_AI_TARGET)
            .forEach(entity -> entity.attackEntityFrom(DamageSources.getHeatDamage(), 6.0f));
        WorldServer world = (WorldServer) metaTileEntity.getWorld();
        double posX = machinePos.getX() + 0.5 + ventingSide.getFrontOffsetX() * 0.6;
        double posY = machinePos.getY() + 0.5 + ventingSide.getFrontOffsetY() * 0.6;
        double posZ = machinePos.getZ() + 0.5 + ventingSide.getFrontOffsetZ() * 0.6;

        world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, posX, posY, posZ,
            7 + world.rand.nextInt(3),
            ventingSide.getFrontOffsetX() / 2.0,
            ventingSide.getFrontOffsetY() / 2.0,
            ventingSide.getFrontOffsetZ() / 2.0, 0.1);
        world.playSound(null, posX, posY, posZ, SoundEvents.BLOCK_LAVA_EXTINGUISH, SoundCategory.BLOCKS, 1.0f, 1.0f);
        setNeedsVenting(false);
    } else if (!ventingStuck) {
        setVentingStuck(true);
    }
}
 
Example 3
Source Project: GregTech   Source File: RoutePath.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
public boolean burnCablesInPath(World world, long voltage, long amperage) {
    for (BlockPos blockPos : path.keySet()) {
        WireProperties wireProperties = path.get(blockPos);
        if (voltage > wireProperties.voltage || amperage > wireProperties.amperage) {
            TileEntity tileEntity = world.getTileEntity(blockPos);
            if (tileEntity instanceof TileEntityCable) {
                world.setBlockToAir(blockPos);
                world.setBlockState(blockPos, Blocks.FIRE.getDefaultState());

                if (!world.isRemote) {
                    ((WorldServer) world).spawnParticle(EnumParticleTypes.SMOKE_LARGE,
                        blockPos.getX() + 0.5, blockPos.getY() + 0.5, blockPos.getZ() + 0.5,
                        5 + world.rand.nextInt(3), 0.0, 0.0, 0.0, 0.1);
                }
            }
        }
    }
    return true;
}
 
Example 4
public static boolean targetOutsideOfPlayerRange(ItemStack stack, EntityPlayer player)
{
    TargetData target = TargetData.getTargetFromSelectedModule(stack, ModuleType.TYPE_LINKCRYSTAL);

    if (target == null)
    {
        return true;
    }

    // We allow a max range of 64 blocks, to hopefully be on the safer side
    //return target.dimension != player.dimension || player.getDistanceSq(target.posX, target.posY, target.posZ) >= 4096.0d;

    WorldServer world = FMLCommonHandler.instance().getMinecraftServerInstance().getWorld(target.dimension);

    if ((player instanceof EntityPlayerMP) == false || world == null ||
         world.getPlayerChunkMap().isPlayerWatchingChunk((EntityPlayerMP) player, target.pos.getX() >> 4, target.pos.getZ() >> 4) == false)
    {
        return true;
    }

    return false;
}
 
Example 5
Source Project: OpenModsLib   Source File: StructureRegistry.java    License: MIT License 6 votes vote down vote up
public Map<String, BlockPos> getNearestStructures(final WorldServer world, final BlockPos pos) {
	final ImmutableMap.Builder<String, BlockPos> result = ImmutableMap.builder();
	visitStructures(world, (generator, structure) -> {
		try {
			BlockPos structPos = generator.getNearestStructurePos(world, structure, pos, true);

			if (structPos != null) {
				if (!Strings.isNullOrEmpty(structure)) result.put(structure, structPos);
			}
		} catch (IndexOutOfBoundsException e) {
			// bug in MC, just ignore
			// hopefully fixed by magic of ASM
		}
	});

	return result.build();
}
 
Example 6
Source Project: mocreaturesdev   Source File: CustomSpawner.java    License: GNU General Public License v3.0 6 votes vote down vote up
public final int despawnVanillaAnimals(WorldServer worldObj)
{
    int count = 0;
    for (int j = 0; j < worldObj.loadedEntityList.size(); j++)
    {
        Entity entity = (Entity) worldObj.loadedEntityList.get(j);
        if (!(entity instanceof EntityLiving))
        {
            continue;
        }
        if ((entity instanceof EntityCow || entity instanceof EntitySheep || entity instanceof EntityPig || entity instanceof EntityOcelot || entity instanceof EntityChicken || entity instanceof EntitySquid || entity instanceof EntityWolf))
        {
            count += entityDespawnCheck(worldObj, (EntityLiving) entity);

        }
    }
    return count;
}
 
Example 7
public static void teleportToDimension(EntityPlayer player, int dimension, double x, double y, double z) {
	int oldDimension = player.getEntityWorld().provider.getDimension();
	EntityPlayerMP entityPlayerMP = (EntityPlayerMP) player;
	MinecraftServer server = player.getEntityWorld().getMinecraftServer();
	WorldServer worldServer = server.getWorld(dimension);
	player.addExperienceLevel(0);
	if (worldServer == null || worldServer.getMinecraftServer() == null) { // Dimension doesn't exist
		throw new IllegalArgumentException("Dimension: " + dimension + " doesn't exist!");
	}
	worldServer.getMinecraftServer().getPlayerList().transferPlayerToDimension(entityPlayerMP, dimension, new GTCommandTeleporter(worldServer, x, y, z));
	player.setPositionAndUpdate(x, y, z);
	if (oldDimension == 1) {
		// For some reason teleporting out of the end does weird things.
		player.setPositionAndUpdate(x, y, z);
		worldServer.spawnEntity(player);
		worldServer.updateEntityWithOptionalForce(player, false);
	}
}
 
Example 8
private static Map<CellLoc, Short> calculateCellLocs(WorldServer world) {
    ConcurrentHashMap<CellLoc, Short> oldDat = MazeHandler.labyrinth;
    ConcurrentHashMap<CellLoc, Short> bufferOld = new ConcurrentHashMap<CellLoc, Short>(labyrinthCopy);
    MazeHandler.labyrinth = labyrinthCopy;
    int chX = getHighestPossibleRandWH(); //To ensure we're always +x and +z
    int chZ = getHighestPossibleRandWH();
    int w = randWH(world.rand);
    int h = randWH(world.rand);
    while (MazeHandler.mazesInRange(chX, chZ, w, h)) {
        chX++; //We grow the mazes in +x direction!
    }
    MazeThread mt = new MazeThread(chX, chZ, w, h, world.rand.nextLong());
    mt.run();
    Map<CellLoc, Short> locs = calculateDifferences(bufferOld);
    labyrinthCopy = MazeHandler.labyrinth;
    MazeHandler.labyrinth = oldDat;
    return locs;
}
 
Example 9
Source Project: Kettle   Source File: SpigotCommand.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
    if (!testPermission(sender)) return true;

    if (args.length != 1) {
        sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
        return false;
    }

    if (args[0].equals("reload")) {
        Command.broadcastCommandMessage(sender, ChatColor.RED + "Please note that this command is not supported and may cause issues.");
        Command.broadcastCommandMessage(sender, ChatColor.RED + "If you encounter any issues please use the /stop command to restart your server.");

        MinecraftServer console = MinecraftServer.getServerCB();
        org.spigotmc.SpigotConfig.init((File) console.options.valueOf("spigot-settings"));
        for (WorldServer world : console.worlds) {
            world.spigotConfig.init();
        }
        console.server.reloadCount++;

        Command.broadcastCommandMessage(sender, ChatColor.GREEN + "Reload complete.");
    }

    return true;
}
 
Example 10
Source Project: WearableBackpacks   Source File: BackpackDataItems.java    License: MIT License 6 votes vote down vote up
public static void generateLoot(ItemStackHandler items, String tableStr, long seed,
                                World world, EntityPlayer player) {
	Random rnd = new Random(seed);
	double maxFullness = (0.6 + rnd.nextDouble() * 0.2);
	int maxOccupiedSlots = (int)Math.ceil(items.getSlots() * maxFullness);
	
	LootTableManager manager = world.getLootTableManager();
	LootTable table = manager.getLootTableFromLocation(new ResourceLocation(tableStr));
	LootContext context = new LootContext(((player != null) ? player.getLuck() : 0),
	                                      (WorldServer)world, manager, player, null, null);
	List<ItemStack> loot = table.generateLootForPools(rnd, context);
	Collections.shuffle(loot);
	
	List<Integer> randomizedSlots = new ArrayList<Integer>(items.getSlots());
	for (int i = 0; i < items.getSlots(); i++) randomizedSlots.add(i);
	Collections.shuffle(randomizedSlots);
	for (int i = 0; (i < maxOccupiedSlots) && (i < loot.size()); i++) {
		ItemStack stack = loot.get(i);
		int slot = randomizedSlots.get(i);
		items.setStackInSlot(slot, stack);
	}
}
 
Example 11
Source Project: ToroQuest   Source File: MessageQuestUpdate.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public IMessage onMessage(final MessageQuestUpdate message, MessageContext ctx) {
	if (ctx.side != Side.SERVER) {
		return null;
	}

	final EntityPlayerMP player = ctx.getServerHandler().player;

	if (player == null) {
		return null;
	}

	final WorldServer worldServer = player.getServerWorld();

	worldServer.addScheduledTask(new Runnable() {
		@Override
		public void run() {
			new Worker(message.action).work(message, player);
		}
	});

	return null;
}
 
Example 12
Source Project: GriefPrevention   Source File: BlockUtils.java    License: MIT License 6 votes vote down vote up
private static void chunkLoadPostProcess(Chunk chunk) {
    if (chunk != null) {
        WorldServer world = (WorldServer) chunk.getWorld();
        world.getChunkProvider().id2ChunkMap.put(ChunkPos.asLong(chunk.x, chunk.z), chunk);

        org.spongepowered.api.world.Chunk spongeChunk = (org.spongepowered.api.world.Chunk) chunk;
        for (Direction direction : CARDINAL_SET) {
            Vector3i neighborPosition = spongeChunk.getPosition().add(direction.asBlockOffset());
            ChunkProviderBridge spongeChunkProvider = (ChunkProviderBridge) world.getChunkProvider();
            net.minecraft.world.chunk.Chunk neighbor = spongeChunkProvider.bridge$getLoadedChunkWithoutMarkingActive(neighborPosition.getX(), neighborPosition.getZ());
            if (neighbor != null) {
                int neighborIndex = directionToIndex(direction);
                int oppositeNeighborIndex = directionToIndex(direction.getOpposite());
                ((ChunkBridge) spongeChunk).bridge$setNeighborChunk(neighborIndex, neighbor);
                ((ChunkBridge) neighbor).bridge$setNeighborChunk(oppositeNeighborIndex, (net.minecraft.world.chunk.Chunk)(Object) chunk);
            }
        }

        chunk.populate(world.getChunkProvider(), world.getChunkProvider().chunkGenerator);
    }
}
 
Example 13
Source Project: Cyberware   Source File: CyberwareAPI.java    License: MIT License 6 votes vote down vote up
public static void updateData(Entity targetEntity)
{
	if (!targetEntity.worldObj.isRemote)
	{
		WorldServer world = (WorldServer) targetEntity.worldObj;
		
		NBTTagCompound nbt = CyberwareAPI.getCapability(targetEntity).serializeNBT();
		
		if (targetEntity instanceof EntityPlayer)
		{
			PACKET_HANDLER.sendTo(new CyberwareSyncPacket(nbt, targetEntity.getEntityId()), (EntityPlayerMP) targetEntity);
			//System.out.println("Sent data for player " + ((EntityPlayer) targetEntity).getName() + " to that player's client");
		}

		for (EntityPlayer trackingPlayer : world.getEntityTracker().getTrackingPlayers(targetEntity))
		{
			PACKET_HANDLER.sendTo(new CyberwareSyncPacket(nbt, targetEntity.getEntityId()), (EntityPlayerMP) trackingPlayer);
			
			if (targetEntity instanceof EntityPlayer)
			{
				//System.out.println("Sent data for player " + ((EntityPlayer) targetEntity).getName() + " to player " + trackingPlayer.getName());
			}
		}
	}

}
 
Example 14
Source Project: YUNoMakeGoodMap   Source File: StructureLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void generate(World world, BlockPos pos)
{
    PlacementSettings settings = new PlacementSettings();
    Template temp = null;
    String suffix = world.provider.getDimensionType().getSuffix();
    String opts = world.getWorldInfo().getGeneratorOptions() + suffix;

    if (!Strings.isNullOrEmpty(opts))
        temp = StructureUtil.loadTemplate(new ResourceLocation(opts), (WorldServer)world, true);
    if (temp == null)
        temp = StructureUtil.loadTemplate(new ResourceLocation("/config/", this.fileName + suffix), (WorldServer)world, !Strings.isNullOrEmpty(suffix));
    if (temp == null)
        return; //If we're not in the overworld, and we don't have a template...

    BlockPos spawn = StructureUtil.findSpawn(temp, settings);
    if (spawn != null)
    {
        pos = pos.subtract(spawn);
        world.setSpawnPoint(pos);
    }

    temp.addBlocksToWorld(world, pos, settings, 0); //Push to world, with no neighbor notifications!
    world.getPendingBlockUpdates(new StructureBoundingBox(pos, pos.add(temp.getSize())), true); //Remove block updates, so that sand doesn't fall!
}
 
Example 15
Source Project: Valkyrien-Skies   Source File: TileEntityPassengerChair.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public TileEntity createRelocatedTile(BlockPos newPos, ShipTransform transform,
    CoordinateSpaceType coordinateSpaceType) {
    TileEntityPassengerChair relocatedTile = new TileEntityPassengerChair();
    relocatedTile.setWorld(getWorld());
    relocatedTile.setPos(newPos);

    if (chairEntityUUID != null) {
        EntityMountableChair chairEntity = (EntityMountableChair) ((WorldServer) getWorld())
            .getEntityFromUuid(chairEntityUUID);
        if (chairEntity != null) {
            Vec3d newMountPos = transform
                .transform(chairEntity.getMountPos(), TransformType.SUBSPACE_TO_GLOBAL);
            chairEntity.setMountValues(newMountPos, coordinateSpaceType, newPos);
        } else {
            chairEntityUUID = null;
        }
    }

    relocatedTile.chairEntityUUID = this.chairEntityUUID;
    // Move everything to the new tile.
    this.chairEntityUUID = null;
    this.markDirty();
    return relocatedTile;
}
 
Example 16
Source Project: malmo   Source File: InventoryCommandsImplementation.java    License: MIT License 6 votes vote down vote up
@Override
public InventoryChangeMessage onMessage(final InventoryMessage message, MessageContext ctx)
{
    final EntityPlayerMP player = ctx.getServerHandler().playerEntity;
    IThreadListener mainThread = (WorldServer)ctx.getServerHandler().playerEntity.world;
    mainThread.addScheduledTask(new Runnable()
    {
        @Override
        public void run()
        {
            ItemStack[] changes = null;
            if (message.combine)
                changes = combineSlots(player, message.invA, message.slotA, message.invB, message.slotB, message.containerPos);
            else
                changes = swapSlots(player, message.invA, message.slotA, message.invB, message.slotB, message.containerPos);
            if (changes != null)
                MalmoMod.network.sendTo(new InventoryChangeMessage(changes[0], changes[1]), player);
        }
    });
    return null;
}
 
Example 17
Source Project: TFC2   Source File: SMapRequestPacket.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public IMessage onMessage(final SMapRequestPacket message, final MessageContext ctx) {
	IThreadListener mainThread = (WorldServer) ctx.getServerHandler().player.world; // or Minecraft.getMinecraft() on the client
	mainThread.addScheduledTask(new Runnable() 
	{
		@Override
		public void run() 
		{
			int j;
			IslandMap map = WorldGen.getInstance().getIslandMap(message.islandX, message.islandZ);
			long seed = ctx.getServerHandler().player.world.getSeed()+Helper.combineCoords(message.islandX, message.islandZ);
			TFC.network.sendTo(new CMapPacket(message.islandX, message.islandZ, seed), ctx.getServerHandler().player);
		}
	});
	return null; // no response in this case
}
 
Example 18
Source Project: pycode-minecraft   Source File: PythonCode.java    License: MIT License 6 votes vote down vote up
private void ensureCompiled() {
    if (!this.codeChanged) return;
    FMLLog.fine("Eval my code: %s", this.code);

    // now execute the code
    try {
        PythonEngine.eval(this.code, this.context);
        if (!world.isRemote) {
            ((WorldServer)world).spawnParticle(EnumParticleTypes.CRIT,
                    pos.getX() + .5, pos.getY() + 1, pos.getZ() + .5,
                    20, 0, 0, 0, .5, new int[0]);
        }
    } catch (ScriptException e) {
        failz0r(world, pos, "Error running code, traceback:\n%s", stackTraceToString(e));
    }
    this.codeChanged = false;
}
 
Example 19
Source Project: TofuCraftReload   Source File: EntityTofuGandlem.java    License: MIT License 5 votes vote down vote up
@Override
public void updateTask() {
    super.updateTask();
    --this.shottick;

    if (this.shottick == 60 || this.shottick == 80) {
        EntityTofuGandlem.this.playSound(SoundEvents.BLOCK_IRON_TRAPDOOR_OPEN, 2.0F, 1.4F);
        ((WorldServer) EntityTofuGandlem.this.world).spawnParticle(EnumParticleTypes.CRIT, EntityTofuGandlem.this.posX, EntityTofuGandlem.this.posY, EntityTofuGandlem.this.posZ, 15, 0.2D, 0.2D, 0.2D, 0.0D);
    }

    if (this.shottick <= 20) {
        if (EntityTofuGandlem.this.ticksExisted % 5 == 0) {
            for (int i = 0; i < 6; i++) {
                EntityThrowable projectile = new EntityFukumame(EntityTofuGandlem.this.world, EntityTofuGandlem.this);

                Vec3d vec3d = EntityTofuGandlem.this.getLook(1.0F);

                playSound(SoundEvents.ENTITY_SNOWBALL_THROW, 3.0F, 1.0F / (EntityTofuGandlem.this.getRNG().nextFloat() * 0.4F + 0.8F));

                projectile.setLocationAndAngles(EntityTofuGandlem.this.posX + vec3d.x * 1.3D, EntityTofuGandlem.this.posY + (EntityTofuGandlem.this.getEyeHeight() / 2), EntityTofuGandlem.this.posZ + vec3d.z * 1.2D, EntityTofuGandlem.this.rotationYaw, EntityTofuGandlem.this.rotationPitch);

                float d0 = (EntityTofuGandlem.this.rand.nextFloat() * 12.0F) - 6.0F;

                projectile.shoot(EntityTofuGandlem.this, EntityTofuGandlem.this.rotationPitch, EntityTofuGandlem.this.rotationYaw + d0, 0.0F, 1.5f, 0.8F);
                EntityTofuGandlem.this.world.spawnEntity(projectile);
            }
        }
    }
}
 
Example 20
Source Project: Sakura_mod   Source File: ItemShinai.java    License: MIT License 5 votes vote down vote up
@Override
public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityLivingBase entityLiving, int timeLeft) {
    int i = this.getMaxItemUseDuration(stack) - timeLeft;
    if (i < 0) return;
        entityLiving.swingArm(entityLiving.getActiveHand());

        float f = (float) entityLiving.getEntityAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getAttributeValue();
        f += EnchantmentHelper.getModifierForCreature(stack, entityLiving.getCreatureAttribute()) / 1.2F;

        float f1 = i / 15F;
        f1 = (f1 * f1 + f1 * 2.0F) / 2F;
        if(f1>8F) f1=8f;
        float f3 = f1 + EnchantmentHelper.getSweepingDamageRatio(entityLiving) * f ;

        float sweepingRatio = EnchantmentHelper.getSweepingDamageRatio(entityLiving);

        for (Entity entitylivingbase : worldIn.getEntitiesWithinAABB(Entity.class, entityLiving.getEntityBoundingBox().grow(1.6D + sweepingRatio * 1.2D, 0.5D + sweepingRatio * 0.15D, 1.6D + sweepingRatio * 1.2D))) {
            if (entitylivingbase != entityLiving && !entityLiving.isOnSameTeam(entitylivingbase)) {
                if (entitylivingbase instanceof EntityLivingBase) {
                	f1 = f1/10;
                    ((EntityLivingBase) entitylivingbase).knockBack(entityLiving, 0.4F + 0.6F * f1 * EnchantmentHelper.getSweepingDamageRatio(entityLiving), MathHelper.sin(entityLiving.rotationYaw * 0.017453292F), (-MathHelper.cos(entityLiving.rotationYaw * 0.017453292F)));
                    entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) entityLiving), f3);
                }

                if (entitylivingbase instanceof MultiPartEntityPart) {
                    entitylivingbase.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) entityLiving), f3);
                }
            }
        }
        worldIn.playSound(null, entityLiving.posX, entityLiving.posY, entityLiving.posZ, SoundEvents.ENTITY_PLAYER_ATTACK_SWEEP, entityLiving.getSoundCategory(), 1.0F, 1.0F);
        if (worldIn instanceof WorldServer) {
            double d0 = (-MathHelper.sin(entityLiving.rotationYaw * 0.017453292F));
            double d1 = MathHelper.cos(entityLiving.rotationYaw * 0.017453292F);
            ((WorldServer) worldIn).spawnParticle(EnumParticleTypes.SWEEP_ATTACK, entityLiving.posX + d0, entityLiving.posY + entityLiving.height * 0.5D, entityLiving.posZ + d1, 0, d0, 0.0D, d1, 0.0D);
        }
        stack.damageItem(2, entityLiving);
        ((EntityPlayer) entityLiving).getCooldownTracker().setCooldown(this, 25);

}
 
Example 21
Source Project: CommunityMod   Source File: Nyan.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@SubscribeEvent
public static void onLivingUpdate(LivingEvent.LivingUpdateEvent event) {
	final Entity entity = event.getEntity();
	final World world = entity.getEntityWorld();

	if(world.isRemote) {
		return;
	}

	final MinecraftServer server = world.getMinecraftServer();
	final NBTTagCompound data = entity.getEntityData();

	if(data.hasUniqueId(NYANED_ENTITY_UUID_KEY)) {
		final Entity nyanedEntity =
				server.getEntityFromUuid(data.getUniqueId(NYANED_ENTITY_UUID_KEY));

		if(nyanedEntity == null || nyanedEntity.isDead) {
			world.removeEntity(entity);
			return;
		}
	}

	if(data.getBoolean(HAS_NYAN_ENTITY_KEY)) {
		updateNyanEntity(server, (WorldServer) world, entity, data);
	} else if(!data.hasKey(HAS_NYAN_ENTITY_KEY)) {
		if(entity instanceof EntityPlayer || random.nextInt(10) == 0) {
			data.setBoolean(HAS_NYAN_ENTITY_KEY, true);
			updateNyanEntity(server, (WorldServer) world, entity, data);
		} else {
			data.setBoolean(HAS_NYAN_ENTITY_KEY, false);
		}
	}
}
 
Example 22
public AIBreakBlock(EntityGolemBase golem) {
    this.golem = golem;

    if (golem.worldObj instanceof WorldServer) {
        this.player = new GolemFakePlayer((WorldServer) golem.worldObj, golem);
    }

    setMutexBits(3);
}
 
Example 23
public static FakePlayer get(WorldServer world) {
    FakePlayer ret = GREGTECH_PLAYER != null ? GREGTECH_PLAYER.get() : null;
    if (ret == null) {
        ret = FakePlayerFactory.get(world, GREGTECH);
        GREGTECH_PLAYER = new WeakReference<>(ret);
    }
    return ret;
}
 
Example 24
@Override
public void update() {
    super.update();
    ItemStack baitStack = importItems.getStackInSlot(0);
    if (!getWorld().isRemote && energyContainer.getEnergyStored() >= energyAmountPerFish && getTimer() % fishingTicks == 0L && !baitStack.isEmpty()) {
        WorldServer world = (WorldServer) this.getWorld();
        int waterCount = 0;
        int edgeSize = (int) Math.sqrt(WATER_CHECK_SIZE);
        for (int x = 0; x < edgeSize; x++){
            for (int z = 0; z < edgeSize; z++){
                BlockPos waterCheckPos = getPos().down().add(x - edgeSize / 2, 0, z - edgeSize / 2);
                if (world.getBlockState(waterCheckPos).getBlock() instanceof BlockLiquid &&
                    world.getBlockState(waterCheckPos).getMaterial() == Material.WATER) {
                    waterCount++;
                }
            }
        }
        if (waterCount == WATER_CHECK_SIZE) {
            LootTable table = world.getLootTableManager().getLootTableFromLocation(LootTableList.GAMEPLAY_FISHING);
            NonNullList<ItemStack> itemStacks = NonNullList.create();
            itemStacks.addAll(table.generateLootForPools(world.rand, new LootContext.Builder(world).build()));
            if(addItemsToItemHandler(exportItems, true, itemStacks)) {
                addItemsToItemHandler(exportItems, false, itemStacks);
                energyContainer.removeEnergy(energyAmountPerFish);
                baitStack.shrink(1);
            }
        }
    }
    if(!getWorld().isRemote && getTimer() % 5 == 0) {
        pushItemsIntoNearbyHandlers(getFrontFacing());
    }
}
 
Example 25
Source Project: AdvancedRocketry   Source File: TeleporterNoPortal.java    License: MIT License 5 votes vote down vote up
public void teleport(Entity entity, WorldServer world) {

		if (entity.isEntityAlive()) {
			entity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, entity.rotationYaw, entity.rotationPitch);
			world.spawnEntity(entity);
			world.updateEntityWithOptionalForce(entity, false);
		}
		entity.setWorld(world);
	}
 
Example 26
Source Project: OpenModsLib   Source File: NetUtils.java    License: MIT License 5 votes vote down vote up
public static Set<EntityPlayerMP> getPlayersWatchingEntity(WorldServer server, Entity entity) {
	final EntityTracker tracker = server.getEntityTracker();

	@SuppressWarnings("unchecked")
	final Set<? extends EntityPlayerMP> trackingPlayers = (Set<? extends EntityPlayerMP>)tracker.getTrackingPlayers(entity);
	return ImmutableSet.copyOf(trackingPlayers);
}
 
Example 27
Source Project: ChickenChunks   Source File: ChunkLoaderEventHandler.java    License: MIT License 5 votes vote down vote up
@SubscribeEvent
public void worldTick(WorldTickEvent event) {
    if (event.phase == Phase.END && !event.world.isRemote) {
        ChunkLoaderManager.tickEnd((WorldServer) event.world);
        PlayerChunkViewerManager.instance().calculateChunkChanges((WorldServer) event.world);
    }
}
 
Example 28
Source Project: AdvancedRocketry   Source File: TileSpaceLaser.java    License: MIT License 5 votes vote down vote up
/**
 * Checks to see if the situation for firing the laser exists... and changes the state accordingly
 */
public void checkCanRun() {
	//Laser requires lense, redstone power, not be jammed, and be in orbit and energy to function
	if(world.isBlockIndirectlyGettingPowered(getPos()) == 0 || !isAllowedToRun()) {
		if(laserSat.isAlive()) {
			laserSat.deactivateLaser();
		}

		setRunning(false);
	} else if(!laserSat.isAlive() && !finished && !laserSat.getJammed() && world.isBlockIndirectlyGettingPowered(getPos()) > 0 && canMachineSeeEarth()) {

		//Laser will be on at this point
		int orbitDimId = ((WorldProviderSpace)this.world.provider).getDimensionProperties(getPos()).getParentPlanet();
		if(orbitDimId == SpaceObjectManager.WARPDIMID)
			return;
		WorldServer orbitWorld = DimensionManager.getWorld(orbitDimId);

		if(orbitWorld == null) {
			DimensionManager.initDimension(orbitDimId);
			orbitWorld = DimensionManager.getWorld(orbitDimId);
			if(orbitWorld == null)
				return;
		}


		if(ticket == null) {
			ticket = ForgeChunkManager.requestTicket(AdvancedRocketry.instance, this.world, Type.NORMAL);
			if(ticket != null)
				ForgeChunkManager.forceChunk(ticket, new ChunkPos(getPos().getX() / 16 - (getPos().getX() < 0 ? 1 : 0), getPos().getZ() / 16 - (getPos().getZ() < 0 ? 1 : 0)));
		}

		setRunning(laserSat.activateLaser(orbitWorld, laserX, laserZ));
	}

	if(!this.world.isRemote)
		PacketHandler.sendToNearby(new PacketMachine(this, (byte)12), 128, pos, this.world.provider.getDimension());
}
 
Example 29
Source Project: simpleretrogen   Source File: WorldRetrogen.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SubscribeEvent
public void tickStart(TickEvent.WorldTickEvent tick)
{
    World w = tick.world;
    if (!(w instanceof WorldServer))
    {
        return;
    }
    if (tick.phase == TickEvent.Phase.START)
    {
        counter = 0;
        getSemaphoreFor(w);
    }
    else
    {
        ListMultimap<ChunkPos, String> pending = pendingWork.get(w);
        if (pending == null)
        {
            return;
        }
        ImmutableList<Entry<ChunkPos, String>> forProcessing = ImmutableList.copyOf(Iterables.limit(pending.entries(), maxPerTick + 1));
        for (Entry<ChunkPos, String> entry : forProcessing)
        {
            if (counter++ > maxPerTick)
            {
                FMLLog.fine("Completed %d retrogens this tick. There are %d left for world %s", counter, pending.size(), w.getWorldInfo().getWorldName());
                return;
            }
            runRetrogen((WorldServer)w, entry.getKey(), entry.getValue());
        }
    }
}
 
Example 30
Source Project: OpenModsLib   Source File: EntityBlock.java    License: MIT License 5 votes vote down vote up
private boolean tryPlaceBlock(final WorldServer world, final BlockPos pos) {
	return FakePlayerPool.instance.executeOnPlayer(world, (PlayerUserReturning<Boolean>)fakePlayer -> {
		if (tryPlaceBlock(fakePlayer, world, pos, EnumFacing.UP)) return true;

		for (EnumFacing dir : PLACE_DIRECTIONS) {
			if (tryPlaceBlock(fakePlayer, world, pos.offset(dir), dir)) return true;
		}
		return false;
	});

}
 
Example 31
Source Project: NotEnoughItems   Source File: NEIServerUtils.java    License: MIT License 5 votes vote down vote up
public static void toggleRaining(World world, boolean notify) {
    boolean raining = !world.isRaining();
    if (!raining)//turn off
    {
        ((WorldServer) world).provider.resetRainAndThunder();
    } else {
        world.getWorldInfo().setRaining(!isRaining(world));
    }

    if (notify) {
        ServerUtils.sendChatToAll(new TextComponentTranslation("nei.chat.rain." + (raining ? "on" : "off")));
    }
}
 
Example 32
Source Project: Thermos   Source File: CraftWorld.java    License: GNU General Public License v3.0 5 votes vote down vote up
public CraftWorld(net.minecraft.world.WorldServer world, ChunkGenerator gen, Environment env) {
    this.world = world;
    this.generator = gen;

    environment = env;

    if (server.chunkGCPeriod > 0) {
        chunkGCTickCount = rand.nextInt(server.chunkGCPeriod);
    }
}
 
Example 33
Source Project: Kettle   Source File: CraftWorld.java    License: GNU General Public License v3.0 5 votes vote down vote up
public CraftWorld(WorldServer world, ChunkGenerator gen, Environment env) {
    this.world = world;
    this.generator = gen;

    environment = env;

    if (server.chunkGCPeriod > 0) {
        chunkGCTickCount = rand.nextInt(server.chunkGCPeriod);
    }
}
 
Example 34
@Nonnull
private FakePlayer getPlayer()
{
    if (this.fakePlayer == null)
    {
        int dim = this.getWorld().provider.getDimension();

        this.fakePlayer = FakePlayerFactory.get((WorldServer) this.getWorld(),
                new GameProfile(new UUID(dim, dim), Reference.MOD_ID + ":drawbridge"));
    }

    return this.fakePlayer;
}
 
Example 35
Source Project: mocreaturesdev   Source File: CustomSpawner.java    License: GNU General Public License v3.0 5 votes vote down vote up
public final int despawnMob(WorldServer worldObj, Class... classList)
{
    List<Class> myList = new ArrayList();
    for (Class element : classList)
    {
        myList.add(element);
    }
    return despawnMob(worldObj, myList);
}
 
Example 36
Source Project: pycode-minecraft   Source File: RoofGen.java    License: MIT License 5 votes vote down vote up
public RoofGen(WorldServer world, BlockPos pos, EnumFacing actualFacing,
               String material, int aWidth, int aDepth, ArgParser spec) throws BlockTypeError {
    this.world = world;
    this.stair = this.getRoofStair(material);
    if (this.stair == null) {
        // not a stair material so go with just blocks
        this.stair = this.filler = this.slab = PyRegistry.getBlockVariant(spec, pos, actualFacing, world);
    } else {
        this.filler = this.getRoofFiller(material);
        this.slab = this.getSlabBlock(material);
    }
    this.north_south = actualFacing == EnumFacing.NORTH || actualFacing == EnumFacing.SOUTH;
    this.fill = spec.getBoolean("fill", true);

    // alter pos, width and depth based on orientation so that the
    // code which always generates in the EAST facing will work
    switch (actualFacing) {
        case EAST:
            this.width = aWidth;
            this.depth = aDepth;
            this.pos = pos.add(1, 0, 0);
            break;
        case WEST:
            this.width = aWidth;
            this.depth = aDepth;
            this.pos = pos.add(-aDepth, 0, -(aWidth-1));
            break;
        case NORTH:
            this.width = aDepth;
            this.depth = aWidth;
            this.pos = pos.add(0, 0, -aDepth);
            break;
        case SOUTH:
            this.width = aDepth;
            this.depth = aWidth;
            this.pos = pos.add(-(aWidth-1), 0, 1);
            break;
    }
}
 
Example 37
Source Project: NotEnoughItems   Source File: NEIServerUtils.java    License: MIT License 5 votes vote down vote up
public static void toggleRaining(World world, boolean notify) {
    boolean raining = !world.isRaining();
    if (!raining)//turn off
        ((WorldServer) world).provider.resetRainAndThunder();
    else
        world.getWorldInfo().setRaining(!isRaining(world));

    if (notify)
        ServerUtils.sendChatToAll(new ChatComponentTranslation("nei.chat.rain." + (raining ? "on" : "off")));
}
 
Example 38
@Override
public void handle(ByteBuf data, EntityPlayer player) {
	if (ModConfigs.disabled) return;
	int dim = data.readInt();
	int xPos = data.readInt();
	int yPos = data.readInt();
	int zPos = data.readInt();

	if (!DimensionManager.isDimensionRegistered(dim)) return;
	WorldServer world = MinecraftServer.getServer().worldServerForDimension(dim);
	if (world == null) return;
	Chunk chunk = world.getChunkFromChunkCoords(xPos, zPos);
	if (!chunk.isChunkLoaded) chunk = world.getChunkProvider().loadChunk(xPos, zPos);
	ServerPacketDispatcher.getInstance().addPacket(player, PacketChunkInfo.createPacket(chunk, true, yPos, dim));
}
 
Example 39
Source Project: Wizardry   Source File: BlockUtils.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static EntityPlayerMP makeBreaker(@Nonnull World world, @Nonnull BlockPos pos, @Nullable Entity entity) {
	if (entity instanceof EntityPlayerMP) {
		return (EntityPlayerMP) entity;
	}
	EntityPlayerMP bro = FakePlayerFactory.get((WorldServer) world, BREAKER);
	bro.moveToBlockPosAndAngles(pos, 0, -90);
	return bro;
}
 
Example 40
Source Project: mocreaturesdev   Source File: CustomSpawner.java    License: GNU General Public License v3.0 5 votes vote down vote up
public final int despawnMob(WorldServer worldObj, List<Class> classList)
{
    int count = 0;
    if (classList == null)
    {
        classList = vanillaClassList;
    }

    for (int j = 0; j < worldObj.loadedEntityList.size(); j++)
    {
        Entity entity = (Entity) worldObj.loadedEntityList.get(j);
        if (!(entity instanceof EntityLiving))
        {
            continue;
        }
        for (Iterator iterator = classList.iterator(); iterator.hasNext();)
        {
            if (iterator != null)
            {
                Class class2 = (Class) iterator.next();
                if (class2 == entity.getClass())
                {
                    count += entityDespawnCheck(worldObj, (EntityLiving) entity);
                }
            }
        }

    }
    return count;
}