use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.
the class EntityUtil method handleDisplaceEntityPortalEvent.
@Nullable
public static MoveEntityEvent.Teleport.Portal handleDisplaceEntityPortalEvent(Entity entityIn, int targetDimensionId, @Nullable Teleporter teleporter) {
SpongeImplHooks.registerPortalAgentType(teleporter);
final MinecraftServer mcServer = SpongeImpl.getServer();
final IMixinPlayerList mixinPlayerList = (IMixinPlayerList) mcServer.getPlayerList();
final IMixinEntity mixinEntity = (IMixinEntity) entityIn;
final Transform<World> fromTransform = mixinEntity.getTransform();
final WorldServer fromWorld = ((WorldServer) entityIn.world);
final IMixinWorldServer fromMixinWorld = (IMixinWorldServer) fromWorld;
boolean sameDimension = entityIn.dimension == targetDimensionId;
// handle the end
if (targetDimensionId == 1 && fromWorld.provider instanceof WorldProviderEnd) {
targetDimensionId = 0;
}
WorldServer toWorld = mcServer.getWorld(targetDimensionId);
// not being loaded then short-circuit to prevent unnecessary logic from running
if (!sameDimension && fromWorld == toWorld) {
return null;
}
if (teleporter == null) {
teleporter = toWorld.getDefaultTeleporter();
}
final Map<String, String> portalAgents = fromMixinWorld.getActiveConfig().getConfig().getWorld().getPortalAgents();
String worldName = "";
String teleporterClassName = teleporter.getClass().getName();
// check for new destination in config
if (teleporterClassName.equals("net.minecraft.world.Teleporter")) {
worldName = portalAgents.get("minecraft:default_" + toWorld.provider.getDimensionType().getName().toLowerCase(Locale.ENGLISH));
if (worldName == null && toWorld.provider instanceof WorldProviderHell) {
worldName = portalAgents.get("minecraft:default_nether");
}
} else {
// custom
worldName = portalAgents.get("minecraft:" + teleporter.getClass().getSimpleName());
}
if (worldName != null && !worldName.equals("")) {
for (WorldProperties worldProperties : Sponge.getServer().getAllWorldProperties()) {
if (worldProperties.getWorldName().equalsIgnoreCase(worldName)) {
Optional<World> spongeWorld = Sponge.getServer().loadWorld(worldProperties);
if (spongeWorld.isPresent()) {
toWorld = (WorldServer) spongeWorld.get();
teleporter = toWorld.getDefaultTeleporter();
if (fromWorld.provider.isNether() || toWorld.provider.isNether()) {
((IMixinTeleporter) teleporter).setNetherPortalType(true);
} else {
((IMixinTeleporter) teleporter).setNetherPortalType(false);
}
}
}
}
}
adjustEntityPostionForTeleport(mixinPlayerList, entityIn, fromWorld, toWorld);
try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame();
TeleportingContext context = EntityPhase.State.CHANGING_DIMENSION.createPhaseContext().setTargetWorld(toWorld).buildAndSwitch()) {
Sponge.getCauseStackManager().pushCause(teleporter);
Sponge.getCauseStackManager().pushCause(mixinEntity);
Sponge.getCauseStackManager().addContext(EventContextKeys.TELEPORT_TYPE, TeleportTypes.PORTAL);
if (entityIn.isEntityAlive() && !(fromWorld.provider instanceof WorldProviderEnd)) {
fromWorld.profiler.startSection("placing");
// Note: We must always use placeInPortal to support mods.
if (!((IMixinTeleporter) teleporter).isVanilla() || entityIn.getLastPortalVec() != null) {
teleporter.placeInPortal(entityIn, entityIn.rotationYaw);
}
fromWorld.profiler.endSection();
}
// Complete phases, just because we need to. The phases don't actually do anything, because the processing resides here.
// Grab the exit location of entity after being placed into portal
final Transform<World> portalExitTransform = mixinEntity.getTransform().setExtent((World) toWorld);
// Use setLocationAndAngles to avoid firing MoveEntityEvent to plugins
mixinEntity.setLocationAndAngles(fromTransform);
final MoveEntityEvent.Teleport.Portal event = SpongeEventFactory.createMoveEntityEventTeleportPortal(Sponge.getCauseStackManager().getCurrentCause(), fromTransform, portalExitTransform, (PortalAgent) teleporter, mixinEntity, true);
SpongeImpl.postEvent(event);
final Vector3i chunkPosition = mixinEntity.getLocation().getChunkPosition();
final IMixinTeleporter toMixinTeleporter = (IMixinTeleporter) teleporter;
final List<BlockSnapshot> capturedBlocks = context.getCapturedBlocks();
final Transform<World> toTransform = event.getToTransform();
if (event.isCancelled()) {
// We need to make sure to only restore the location if
if (!portalExitTransform.getExtent().getUniqueId().equals(mixinEntity.getLocation().getExtent().getUniqueId())) {
// update cache
((IMixinTeleporter) teleporter).removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
if (!capturedBlocks.isEmpty()) {
for (BlockSnapshot original : Lists.reverse(capturedBlocks)) {
original.restore(true, BlockChangeFlags.NONE);
}
capturedBlocks.clear();
}
mixinEntity.setLocationAndAngles(fromTransform);
} else {
// Call setTransform to let plugins know mods changed the position
// Guarantees plugins such as Nucleus can track changed locations properly
mixinEntity.setTransform(mixinEntity.getTransform());
}
return event;
}
if (!portalExitTransform.equals(toTransform)) {
// if plugin set to same world, just set the transform
if (fromWorld == toTransform.getExtent()) {
// force cancel so we know to skip remaining logic
event.setCancelled(true);
// update cache
toMixinTeleporter.removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
// Undo created portal
if (!capturedBlocks.isEmpty()) {
for (BlockSnapshot original : Lists.reverse(capturedBlocks)) {
original.restore(true, BlockChangeFlags.NONE);
}
}
capturedBlocks.clear();
mixinEntity.setLocationAndAngles(toTransform);
return event;
}
} else {
if (toWorld.provider instanceof WorldProviderEnd) {
BlockPos blockpos = entityIn.world.getTopSolidOrLiquidBlock(toWorld.getSpawnPoint());
entityIn.moveToBlockPosAndAngles(blockpos, entityIn.rotationYaw, entityIn.rotationPitch);
}
}
if (!capturedBlocks.isEmpty() && !TrackingUtil.processBlockCaptures(capturedBlocks, EntityPhase.State.CHANGING_DIMENSION, context)) {
toMixinTeleporter.removePortalPositionFromCache(ChunkPos.asLong(chunkPosition.getX(), chunkPosition.getZ()));
}
if (!event.getKeepsVelocity()) {
entityIn.motionX = 0;
entityIn.motionY = 0;
entityIn.motionZ = 0;
}
return event;
}
}
use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.
the class EntityUtil method getPlayerRespawnLocation.
// Internal to MixinPlayerList. has side effects
public static Location<World> getPlayerRespawnLocation(EntityPlayerMP playerIn, @Nullable WorldServer targetWorld) {
final Location<World> location = ((World) playerIn.world).getSpawnLocation();
tempIsBedSpawn = false;
if (targetWorld == null) {
// Target world doesn't exist? Use global
return location;
}
final Dimension targetDimension = (Dimension) targetWorld.provider;
int targetDimensionId = ((IMixinWorldServer) targetWorld).getDimensionId();
// that world. (Usually overworld unless a mod says otherwise).
if (!targetDimension.allowsPlayerRespawns()) {
targetDimensionId = SpongeImplHooks.getRespawnDimension((WorldProvider) targetDimension, playerIn);
targetWorld = targetWorld.getMinecraftServer().getWorld(targetDimensionId);
}
Vector3d targetSpawnVec = VecHelper.toVector3d(targetWorld.getSpawnPoint());
BlockPos bedPos = SpongeImplHooks.getBedLocation(playerIn, targetDimensionId);
if (bedPos != null) {
// Player has a bed
boolean forceBedSpawn = SpongeImplHooks.isSpawnForced(playerIn, targetDimensionId);
BlockPos bedSpawnLoc = EntityPlayer.getBedSpawnLocation(targetWorld, bedPos, forceBedSpawn);
if (bedSpawnLoc != null) {
// The bed exists and is not obstructed
tempIsBedSpawn = true;
targetSpawnVec = new Vector3d(bedSpawnLoc.getX() + 0.5D, bedSpawnLoc.getY() + 0.1D, bedSpawnLoc.getZ() + 0.5D);
} else {
// Bed invalid
playerIn.connection.sendPacket(new SPacketChangeGameState(0, 0.0F));
// Vanilla behaviour - Delete the known bed location if invalid
// null = remove location
bedPos = null;
}
// Set the new bed location for the new dimension
// Temporarily for setSpawnPoint
int prevDim = playerIn.dimension;
playerIn.dimension = targetDimensionId;
playerIn.setSpawnPoint(bedPos, forceBedSpawn);
playerIn.dimension = prevDim;
}
return new Location<>((World) targetWorld, targetSpawnVec);
}
use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.
the class SpongeEntityArchetype method apply.
@SuppressWarnings("unchecked")
@Override
public Optional<org.spongepowered.api.entity.Entity> apply(Location<World> location) {
final Vector3d position = location.getPosition();
final double x = position.getX();
final double y = position.getY();
final double z = position.getZ();
final BlockPos blockPos = new BlockPos(x, y, z);
final World world = location.getExtent();
final WorldServer worldServer = (WorldServer) world;
Entity entity = null;
try {
Class<? extends Entity> oclass = (Class<? extends Entity>) this.type.getEntityClass();
if (oclass != null) {
entity = oclass.getConstructor(net.minecraft.world.World.class).newInstance(world);
}
} catch (Exception exception) {
exception.printStackTrace();
}
if (entity == null) {
return Optional.empty();
}
this.data.setTag("Pos", NbtDataUtil.newDoubleNBTList(x, y, z));
this.data.setInteger("Dimension", ((IMixinWorldInfo) location.getExtent().getProperties()).getDimensionId());
entity.readFromNBT(this.data);
this.data.removeTag("Pos");
this.data.removeTag("Dimension");
final org.spongepowered.api.entity.Entity spongeEntity = EntityUtil.fromNative(entity);
final List<org.spongepowered.api.entity.Entity> entities = new ArrayList<>();
entities.add(spongeEntity);
final SpawnEntityEvent.Custom event = SpongeEventFactory.createSpawnEntityEventCustom(Sponge.getCauseStackManager().getCurrentCause(), entities);
if (!event.isCancelled()) {
final IMixinWorldServer mixinWorldServer = (IMixinWorldServer) worldServer;
entity.setPositionAndRotation(x, y, z, entity.rotationYaw, entity.rotationPitch);
if (entity instanceof EntityLiving) {
mixinWorldServer.forceSpawnEntity(entity);
((EntityLiving) entity).onInitialSpawn(worldServer.getDifficultyForLocation(blockPos), null);
((EntityLiving) entity).spawnExplosionParticle();
} else {
mixinWorldServer.forceSpawnEntity(entity);
}
return Optional.of(spongeEntity);
}
return Optional.empty();
}
use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.
the class MixinExplosion method doExplosionB.
/**
* @author gabizou - March 26th, 2017
* @reason Since forge will attempt to call the normalized method for modded blocks,
* we must artificially capture the block position for any block drops or changes during the
* explosion phase.
*
* Does the second part of the explosion (sound, particles, drop spawn)
*/
@Overwrite
public void doExplosionB(boolean spawnParticles) {
this.world.playSound((EntityPlayer) null, this.x, this.y, this.z, SoundEvents.ENTITY_GENERIC_EXPLODE, SoundCategory.BLOCKS, 4.0F, (1.0F + (this.world.rand.nextFloat() - this.world.rand.nextFloat()) * 0.2F) * 0.7F);
if (this.size >= 2.0F) {
if (this.world instanceof WorldServer) {
((WorldServer) this.world).spawnParticle(EnumParticleTypes.EXPLOSION_HUGE, this.x, this.y, this.z, 1, 0, 0, 0, 0.1D);
} else {
this.world.spawnParticle(EnumParticleTypes.EXPLOSION_HUGE, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D);
}
} else {
if (this.world instanceof WorldServer) {
((WorldServer) this.world).spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, this.x, this.y, this.z, 1, 0, 0, 0, 0.1D);
} else {
this.world.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, this.x, this.y, this.z, 1.0D, 0.0D, 0.0D);
}
}
if (this.shouldBreakBlocks) {
// Sponge - use 'shouldBreakBlocks' instead of 'damagesTerrain'
for (BlockPos blockpos : this.affectedBlockPositions) {
IBlockState iblockstate = this.world.getBlockState(blockpos);
Block block = iblockstate.getBlock();
if (spawnParticles) {
double d0 = (double) ((float) blockpos.getX() + this.world.rand.nextFloat());
double d1 = (double) ((float) blockpos.getY() + this.world.rand.nextFloat());
double d2 = (double) ((float) blockpos.getZ() + this.world.rand.nextFloat());
double d3 = d0 - this.x;
double d4 = d1 - this.y;
double d5 = d2 - this.z;
double d6 = (double) MathHelper.sqrt(d3 * d3 + d4 * d4 + d5 * d5);
d3 = d3 / d6;
d4 = d4 / d6;
d5 = d5 / d6;
double d7 = 0.5D / (d6 / (double) this.size + 0.1D);
d7 = d7 * (double) (this.world.rand.nextFloat() * this.world.rand.nextFloat() + 0.3F);
d3 = d3 * d7;
d4 = d4 * d7;
d5 = d5 * d7;
this.world.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, (d0 + this.x) / 2.0D, (d1 + this.y) / 2.0D, (d2 + this.z) / 2.0D, d3, d4, d5, new int[0]);
this.world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0, d1, d2, d3, d4, d5, new int[0]);
}
if (iblockstate.getMaterial() != Material.AIR) {
if (block.canDropFromExplosion((net.minecraft.world.Explosion) (Object) this)) {
// Sponge Start - Track the block position being destroyed
final PhaseTracker phaseTracker = PhaseTracker.getInstance();
final PhaseData peek = phaseTracker.getCurrentPhaseData();
// We need to capture this block position if necessary
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(blockpos);
}
block.dropBlockAsItemWithChance(this.world, blockpos, this.world.getBlockState(blockpos), 1.0F / this.size, 0);
// And then un-set the captured block position
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(null);
}
}
// Sponge Start - Track the block position being destroyed
final PhaseTracker phaseTracker = PhaseTracker.getInstance();
final PhaseData peek = phaseTracker.getCurrentPhaseData();
// We need to capture this block position if necessary
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(blockpos);
}
// Because we need to hook into forge.
SpongeImplHooks.blockExploded(block, this.world, blockpos, (net.minecraft.world.Explosion) (Object) this);
// And then un-set the captured block position
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(null);
}
// Sponge End
}
}
}
if (this.causesFire) {
for (BlockPos blockpos1 : this.affectedBlockPositions) {
if (this.world.getBlockState(blockpos1).getMaterial() == Material.AIR && this.world.getBlockState(blockpos1.down()).isFullBlock() && this.random.nextInt(3) == 0) {
// Sponge Start - Track the block position being destroyed
final PhaseTracker phaseTracker = PhaseTracker.getInstance();
final PhaseData peek = phaseTracker.getCurrentPhaseData();
// We need to capture this block position if necessary
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(blockpos1);
}
phaseTracker.setBlockState((IMixinWorldServer) this.world, blockpos1, Blocks.FIRE.getDefaultState(), BlockChangeFlags.ALL);
// And then un-set the captured block position
if (peek.state.requiresBlockPosTracking()) {
peek.context.getCaptureBlockPos().setPos(null);
}
}
}
}
}
use of org.spongepowered.common.interfaces.world.IMixinWorldServer in project SpongeCommon by SpongePowered.
the class ChunkSaveHelper method writeChunks.
@SuppressWarnings("rawtypes")
public static void writeChunks(File file, boolean logAll) {
try {
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
try (JsonWriter writer = new JsonWriter(new FileWriter(file))) {
writer.setIndent(" ");
writer.beginArray();
for (World spongeWorld : SpongeImpl.getGame().getServer().getWorlds()) {
WorldServer world = (WorldServer) spongeWorld;
writer.beginObject();
writer.name("name").value(((SaveHandler) ((WorldServer) spongeWorld).getSaveHandler()).saveDirectoryName);
writer.name("dimensionId").value(((IMixinWorldServer) spongeWorld).getDimensionId());
writer.name("players").value(world.playerEntities.size());
writer.name("loadedChunks").value(world.getChunkProvider().getLoadedChunks().size());
writer.name("activeChunks").value(world.getChunkProvider().getLoadedChunkCount());
writer.name("entities").value(world.loadedEntityList.size());
writer.name("tiles").value(world.loadedTileEntityList.size());
Object2IntMap<ChunkPos> chunkEntityCounts = new Object2IntOpenHashMap<>();
chunkEntityCounts.defaultReturnValue(0);
Object2IntMap<Class> classEntityCounts = new Object2IntOpenHashMap<>();
classEntityCounts.defaultReturnValue(0);
Object2IntMap<Entity> entityCollisionCounts = new Object2IntOpenHashMap<>();
Set<BlockPos> collidingCoords = new HashSet<>();
for (int i = 0; i < world.loadedEntityList.size(); i++) {
Entity entity = world.loadedEntityList.get(i);
ChunkPos chunkCoords = new ChunkPos((int) entity.posX >> 4, (int) entity.posZ >> 4);
chunkEntityCounts.put(chunkCoords, chunkEntityCounts.getInt(chunkCoords) + 1);
classEntityCounts.put(entity.getClass(), classEntityCounts.getInt(entity.getClass()) + 1);
if ((entity.getCollisionBoundingBox() != null) && logAll) {
BlockPos coords = new BlockPos(GenericMath.floor(entity.posX), GenericMath.floor(entity.posY), GenericMath.floor(entity.posZ));
if (!collidingCoords.contains(coords)) {
collidingCoords.add(coords);
int size = entity.world.getEntitiesWithinAABBExcludingEntity(entity, entity.getCollisionBoundingBox().grow(1, 1, 1)).size();
if (size < 5) {
continue;
}
entityCollisionCounts.put(entity, size);
}
}
}
Object2IntMap<ChunkPos> chunkTileCounts = new Object2IntOpenHashMap<>();
chunkTileCounts.defaultReturnValue(0);
Object2IntMap<Class> classTileCounts = new Object2IntOpenHashMap<>();
classTileCounts.defaultReturnValue(0);
writer.name("tiles").beginArray();
for (int i = 0; i < world.loadedTileEntityList.size(); i++) {
TileEntity tile = world.loadedTileEntityList.get(i);
if (logAll) {
writer.beginObject();
writer.name("type").value(tile.getClass().toString());
writer.name("x").value(tile.getPos().getX());
writer.name("y").value(tile.getPos().getY());
writer.name("z").value(tile.getPos().getZ());
writer.name("isInvalid").value(tile.isInvalid());
// writer.name("canUpdate").value(tile.canUpdate());
writer.name("block").value("" + tile.getBlockType());
writer.endObject();
}
ChunkPos chunkCoords = new ChunkPos(tile.getPos().getX() >> 4, tile.getPos().getZ() >> 4);
chunkTileCounts.put(chunkCoords, chunkTileCounts.getInt(chunkCoords) + 1);
classTileCounts.put(tile.getClass(), classTileCounts.getInt(tile.getClass()) + 1);
}
writer.endArray();
if (logAll) {
writeChunkCounts(writer, "topEntityColliders", entityCollisionCounts, 20);
}
writeChunkCounts(writer, "entitiesByClass", classEntityCounts);
writeChunkCounts(writer, "entitiesByChunk", chunkEntityCounts);
writeChunkCounts(writer, "tilesByClass", classTileCounts);
writeChunkCounts(writer, "tilesByChunk", chunkTileCounts);
// Dimension
writer.endObject();
}
// Dimensions
writer.endArray();
}
} catch (Throwable throwable) {
SpongeImpl.getLogger().error("Could not save chunk info report to " + file);
}
}
Aggregations